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.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;

import org.knowm.xchart.*;

class main {

 // XChart



static class XChartRealTimeTest extends DynModule {
  transient double phase = 0;
  
  JComponent visualize() {
    double[][] initdata = getSineData(phase);

    // Create Chart
    final XYChart chart = QuickChart.getChart("Simple XChart Real-time Demo", "Radians", "Sine", "sine", initdata[0], initdata[1]);

    final JComponent panel = new XChartPanel(chart);
    awtEvery(panel, 200, new Runnable() {  public void run() { try { 
      phase += 2 * Math.PI * 2 / 20.0;
      double[][] data = getSineData(phase);

      chart.updateXYSeries("sine", data[0], data[1], null);
      revalidate(panel);
    
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "phase += 2 * Math.PI * 2 / 20.0;\r\n      double[][] data = getSineData(phase);..."; }});
    return panel;
  }

  double[][] getSineData(double phase) {
    double[] xData = new double[100];
    double[] yData = new double[100];
    for (int i = 0; i < l(xData); i++) {
      double radians = phase + (2 * Math.PI / xData.length * i);
      xData[i] = radians;
      yData[i] = Math.sin(radians);
    }
    return new double[][] { xData, yData };
  }
}
static <A extends JComponent> A awtEvery(A component, long delay, Object r) {
  swingEvery(component, delay, r);
  return component;
}

static <A extends JComponent> A awtEvery(A component, long delay, long firstDelay, Object r) {
  swingEvery(component, delay, firstDelay, r);
  return component;
}

static void awtEvery(RootPaneContainer frame, long delay, Object r) {
  swingEvery(frame, delay, r);
}
static void revalidate(final Component c) {
  if (c == null || !c.isShowing()) return;
  { 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..."; }}); }
}

static void revalidate(RootPaneContainer c) { revalidate((Component) c); }
static void revalidate(JFrame f) { revalidate((Component) f); }
static void revalidate(JInternalFrame f) { revalidate((Component) f); }
static RuntimeException rethrow(Throwable t) {
  
  if (t instanceof Error)
    _handleError((Error) t);
  
  throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
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(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 void swingEvery(JComponent component, long delay, Object r) {
  installTimer(component, delay, r);
}

static void swingEvery(JComponent component, long delay, long firstDelay, Object r) {
  installTimer(component, r, delay, firstDelay);
}

static void swingEvery(RootPaneContainer frame, long delay, Object r) {
  installTimer(frame, delay, r);
}

static void swingEvery(RootPaneContainer frame, long delay, long firstDelay, Object r) {
  installTimer(frame, delay, firstDelay, r);
}
static Object swing(Object f) {
  return swingAndWait(f);
}

static <A> A swing(F0<A> f) {
  return (A) swingAndWait(f);
}
static void _handleError(Error e) {
  call(javax(), "_handleError", e);
}
static <A> A call(Object o) {
  return (A) callF(o);
}

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

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






// 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>() { 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 __610 = tempActivity(r); try {
      try {
        if (!allPaused())
          if (isFalse(callF(r)))
            cancelTimer(timer.get());
      } catch (Throwable __e) { _handleException(__e); }
    } finally { _close(__610); }} 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 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();
  }
}
static Class javax() {
  return getJavaX();
}
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, B, C> C callF(F2<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(Object f, Object... args) { try {
  if (f instanceof String)
    return callMC((String) f, 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));
} catch (Exception __e) { throw rethrow(__e); } }

// 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")) {
        m.setAccessible(true);
        l.add(m);
      }
    if (!l.isEmpty()) break;
    _c = _c.getSuperclass();
  } while (_c != null);
  callF_cache.put(c, l);
  return l;
}
static Object call_cached(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);
    
    // TODO: (super-rare) case where method exists static and non-static
    // with different args
    
    Method me = cache.findMethod(method, args);
    if (me == null)
      throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
    if ((me.getModifiers() & Modifier.STATIC) == 0)
      throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not static");
    return invokeMethod(me, null, args);
  } else {
    Class c = o.getClass();
    _MethodCache cache = callOpt_getCache(c);

    Method me = cache.findMethod(method, args);
    if (me == null)
      throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
    return invokeMethod(me, o, args);
  }
} catch (Exception __e) { throw rethrow(__e); } }


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

static _MethodCache callOpt_getCache(Class c) {
  synchronized(callOpt_cache) {
    _MethodCache cache = callOpt_cache.get(c);
    if (cache == null)
      callOpt_cache.put(c, cache = new _MethodCache(c));
    return cache;
  }
}
static int toInt(Object o) {
  if (o == null) return 0;
  if (o instanceof Number)
    return ((Number) o).intValue();
  if (o instanceof String)
    return parseInt((String) o);
  throw fail("woot not int: " + getClassName(o));
}

static int toInt(long l) {
  if (l != (int) l) throw fail("Too large for int: " + l);
  return (int) l;
}
static AutoCloseable tempActivity(Object r) {
  return null;
}
static boolean allPaused() {
  return ping_pauseAll;
}
static boolean isFalse(Object o) {
  return eq(false, o);
}
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 volatile PersistableThrowable _handleException_lastException;
static List _handleException_onException = synchroList(ll("printStackTrace2"));

static void _handleException(Throwable e) {
  _handleException_lastException = persistableThrowable(e);
  
  Throwable e2 = innerException(e);
  if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException)
    return;
    
  for (Object f : cloneList(_handleException_onException)) try {
    callF(f, e);
  } catch (Throwable e3) {
    printStackTrace2(e3); // not using pcall here - it could lead to endless loops
  }
}

static void _close(AutoCloseable c) { try {
  if (c != null) c.close();
} catch (Exception __e) { throw rethrow(__e); } }
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(innerException(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) {
    }
  });
}
// 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 Class __javax;

static Class getJavaX() { try {
  
  return __javax;
} catch (Exception __e) { throw rethrow(__e); } }
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 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 matching arguments 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) {
          m.setAccessible(true);
          multiMapPut(callMC_cache, m.getName(), m);
        }
      c = c.getSuperclass();
    }
  }
}
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(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)
      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 joinWithComma(Collection<String> 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 List<String> classNames(Collection l) {
  return getClassNames(l);
}

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


//sbool ping_actions_shareable = true;
static volatile boolean ping_pauseAll;
static int ping_sleep = 100; // poll pauseAll flag every 100

static volatile boolean ping_anyActions;
static Map<Thread, Object> ping_actions = newWeakHashMap();


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

// returns true when it slept
static boolean ping_impl() { try {
  if (ping_pauseAll && !isAWTThread()) {
    do
      Thread.sleep(ping_sleep);
    while (ping_pauseAll);
    return true;
  }
  
  
  if (ping_anyActions) { // don't allow sharing ping_actions
    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 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 int parseInt(String s) {
  return empty(s) ? 0 : Integer.parseInt(s);
}

static int parseInt(char c) {
  return Integer.parseInt(str(c));
}
static boolean eq(Object a, Object b) {
  return a == null ? b == null : a == b || a.equals(b);
}


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

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

static <A> List<A> ll(A... a) {
  ArrayList l = new ArrayList(a.length);
  for (A x : a) l.add(x);
  return l;
}
static PersistableThrowable persistableThrowable(Throwable e) {
  return e == null ? null : new PersistableThrowable(e);
}
static Throwable innerException(Throwable e) {
  return getInnerException(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 boolean headless() {
  return isHeadless();
}
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 int print_maxLineLength = 0; // 0 = unset

static boolean print_silent; // 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 void print() {
  print("");
}

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

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

static void print_noNewLine(String s) {
  
  Object f = print_byThread == null ? null : print_byThread.get();
  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;
  

  print_raw(s);
}

static void print_raw(String s) {
  s = fixNewLines(s);
  // TODO if (print_maxLineLength != 0)
  StringBuffer 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);
}
static Throwable printStackTrace(Throwable 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 String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); }

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

static String hideCredentials(Object o) {
  return hideCredentials(str(o));
}
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 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 Class mc() {
  return main.class;
}
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 RuntimeException asRuntimeException(Throwable t) {
  
  if (t instanceof Error)
    _handleError((Error) t);
  
  return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static Throwable getExceptionCause(Throwable e) {
  Throwable c = e.getCause();
  return c != null ? c : e;
}
static String joinWithSpace(Collection<String> c) {
  return join(" ", c);
}

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

static boolean isInstanceX(Class type, Object arg) {
  if (type == boolean.class) return arg instanceof Boolean;
  if (type == int.class) return arg instanceof Integer;
  if (type == long.class) return arg instanceof Long;
  if (type == float.class) return arg instanceof Float;
  if (type == short.class) return arg instanceof Short;
  if (type == char.class) return arg instanceof Character;
  if (type == byte.class) return arg instanceof Byte;
  if (type == double.class) return arg instanceof Double;
  return type.isInstance(arg);
}
public static <A> String join(String glue, Iterable<A> strings) {
  if (strings == null) return "";
  StringBuilder buf = new StringBuilder();
  Iterator<A> i = strings.iterator();
  if (i.hasNext()) {
    buf.append(i.next());
    while (i.hasNext())
      buf.append(glue).append(i.next());
  }
  return buf.toString();
}

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

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

static String str(char[] c) {
  return new String(c);
}
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 <A, B> Map<A, B> newWeakHashMap() {
  return _registerWeakMap(synchroMap(new WeakHashMap()));
}
static Thread currentThread() {
  return Thread.currentThread();
}
static String getStackTrace2(Throwable e) {
  return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ",
    hideCredentials(str(getInnerException(e)))) + "\n");
}
static boolean empty(Collection c) { return c == null || c.isEmpty(); }
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(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(File f) { return getFileSize(f) == 0; }
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 <A> ArrayList<A> asList(A[] a) {
  return a == null ? new ArrayList<A>() : new ArrayList<A>(Arrays.asList(a));
}

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

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 Object collectionMutex(Object o) {
  String c = className(o);
  if (eq(c, "java.util.TreeMap$KeySet"))
    c = className(o = getOpt(o, "m"));
  else if (eq(c, "java.util.HashMap$KeySet"))
    c = className(o = get_raw(o, "this$0"));

  
  
  if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
    c = className(o = get_raw(o, "m"));
    
  
    
  return o;
}
static boolean endsWithLetterOrDigit(String s) {
  return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length()-1));
}
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 StringBuilder)) return;
    StringBuilder buf = (StringBuilder) ( _buf);
    max /= 2;
    if (buf.length() > max) try {
      int newLength = max/2;
      int ofs = buf.length()-newLength;
      String newString = buf.substring(ofs);
      buf.setLength(0);
      buf.append("[...] ").append(newString);
    } catch (Exception e) {
      buf.setLength(0);
    }
  }
} catch (Exception __e) { throw rethrow(__e); } }
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 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 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 List<VF1<Map>> _threadInheritInfo_retrievers = synchroList();

static void _threadInheritInfo(Object info) {
  if (info == null) return;
  pcallFAll(_threadInheritInfo_retrievers, (Map) info);
}
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 <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 Collections.synchronizedMap(new HashMap());
}



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 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 String replacePrefix(String prefix, String replacement, String s) {
  if (!startsWith(s, prefix)) return s;
  return replacement + substring(s, l(prefix));
}
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 Throwable getException(Runnable r) {
  try {
    callF(r);
    return null;
  } catch (Throwable e) {
    return e;
  }
}
static String className(Object o) {
  return getClassName(o);
}
static Object getOpt(Object o, String field) {
  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;
    f.setAccessible(true);
    return f.get(o);
  } catch (Exception e) {
    throw new RuntimeException(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;
    f.setAccessible(true);
    return f.get(null);
  } catch (Exception e) {
    throw new RuntimeException(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;
}

// 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) {
      f.setAccessible(true);
      return f.get(o);
    }
      
    
  } catch (Exception e) {
    throw asRuntimeException(e);
  }
  throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}

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

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

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 boolean eqOneOf(Object o, Object... l) {
  for (Object x : l) if (eq(o, x)) return true; return false;
}
static <A> int indexOf(List<A> l, A a, int startIndex) {
  if (l == null) return -1;
  for (int i = startIndex; i < l(l); 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) {
  if (x == null) return -1;
  for (int i = 0; i < l(x); i++)
    if (eq(x[i], a))
      return i;
  return -1;
}
// 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 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 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 void printException(Throwable e) {
  printStackTrace(e);
}
static boolean startsWith(String a, String b) {
  return a != null && a.startsWith(b);
}

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



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


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

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


//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 Object getOpt_cached(Object o, String field) { try {
  if (o == null) return null;

  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 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);
  
  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();
    Class _c = c;
    do {
      for (Field f : _c.getDeclaredFields()) {
        f.setAccessible(true);
        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 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 pcallFunction(Object f, Object... args) {
  try { return callFunction(f, args); } catch (Throwable __e) { _handleException(__e); }
  return null;
}


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 boolean neq(Object a, Object b) {
  return !eq(a, b);
}
static void clear(Collection c) {
  if (c != null) c.clear();
}
static <A, B> void put(Map<A, B> map, A a, B b) {
  if (map != null) map.put(a, b);
}
static boolean isSubtypeOf(Class a, Class b) {
  return b.isAssignableFrom(a); // << always hated that method, let's replace it!
}
static Object callFunction(Object f, Object... args) {
  return callF(f, args);
}


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

  // 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); } }
}static abstract class VF1<A> {
  abstract void get(A a);
}static class Var<A> implements IVar<A> {
  A v; // you can access this directly if you use one thread
  
  Var() {}
  Var(A v) {
  this.v = v;}
  
  public synchronized void set(A a) {
    if (v != a) {
      v = a;
      notifyAll();
    }
  }
  
  public synchronized A get() { return v; }
  public synchronized boolean has() { return v != null; }
  public synchronized void clear() { v = null; }
  
  public String toString() { return str(get()); }
}static class PersistableThrowable {
  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;
  }
}static abstract class F0<A> {
  abstract A get();
}static abstract class DynModule {
  String name, toolTip;
  PersistableThrowable _error;
  Map<String, Collection<String>> mechLists;
  Map<String, Boolean> _persistenceInfo;
  
  transient Object _host;
  transient Map timers = newWeakHashMap(); // all kinds of resources actually; value is closer helper
  transient Set<AutoCloseable> _resources = synchroHashSet();
  transient Lock lock; // set by stem
  transient boolean persistOnChangedField = true;
  transient int changeCount;
  transient Object changeCountSync = new Object();
  transient List onChange;
  transient boolean verboseTimers;
  transient ReliableSingleThread rstUpdate;
  transient Set<String> componentFieldsToKeep;
  transient Map<String, Object> transientGeneralMap = synchroHashMap();
  transient Q q; // module command queue
  
  DynModule() {
    dm_initErrorHandling();
    setMainDesktopPane((JDesktopPane) getCreatorOpt("desktop"));
  }
  
  boolean isVisible() { return isTrue(getOpt(_host, "visible")); }
  
  String moduleName() { return name; }
  
  void setModuleName(String name) {
    String oldName = this.name;
    if (!eq(name, oldName)) {
      this.name = name;
      possiblyInternalFrameTitle(vis(), name);
      vmBus_send("moduleNameChange", this, oldName, name);
    }
  }
  
  void setModuleToolTip(String toolTip) {
    this.toolTip = toolTip;
  }
  
  JComponent vis() {
    return (JComponent) getOpt(_host, "vis");
  }
  
  <A extends AutoCloseable> A ownResource(A a) {
    if (a != null)
      _resources.add(a);
    return a;
  }
  
  <A> A ownTimer(A timer) {
    if (timer instanceof AutoCloseable) ownResource((AutoCloseable) timer);
    ownTimer(timer, "cancelTimerOrInterruptThread");
    return timer;
  }
  
  void ownTimer(Object timer, Object closerHelper) {
    timers.put(timer, closerHelper);
  }
  
  void singleTimer(java.util.Timer timer) {
    stopAllTimers();
    ownTimer(timer);
  }
  
  void stopAllTimers() {
    for (AutoCloseable resource : getAndClearList(_resources)) {
      if (verboseTimers)
        print("Releasing resource: " + resource);
      try { resource.close(); } catch (Throwable __e) { _handleException(__e); }
    }
      
    { final Map<Object, Object> __249 = getAndClearMap(timers); for (Object timer : keys( __249)) { Object closerHelper =__249.get(timer); 
      if (verboseTimers)
        print("Stopping timer: " + closerHelper + " / " + timer);
      pcallF(closerHelper, timer);
    }
  }}
  
  void cleanMeUp_dynModule() {
    stopAllTimers();
  }
  
  void persistMe() {
    synchronized(changeCountSync) { ++changeCount; }
    pcallFAll(onChange); callOpt(_host, "_change");
    updateMe();
  }
  
  void _change() { persistMe(); }
  void change() { persistMe(); }
  
  void updateMe() {
    Lock __250 = lock; lock(__250); try {
    update();
  } finally { unlock(__250); } }
  
  void changeAndUpdate() { _change(); updateMe(); }
  
  boolean setField(String name, Object value) {
    Lock __251 = lock; lock(__251); try {
    if (eq(get(this, name), value)) return false;
    set(this, name, value);
    if (persistOnChangedField && !isFalse(mapGet(_persistenceInfo, name)))
      _change();
    return true;
  } finally { unlock(__251); } }
  
  <A> A setFieldAndReturn(String name, A value) {
    setField(name, value);
    return value;
  }
  
  boolean setFields(Object... params) {
    boolean change = false;
    for (int i = 0; i < l(params); i += 2)
      if (setField((String) params[i], params[i+1])) change = true;
    return change;
  }
  
  void start() {}
  
  void revisualize() {
    call(creator(), "revisualizeModule", _host);
  }
  
  AutoCloseable enter() {
    return tempSetThreadLocal(dm_currentModule_value, new WeakReference(this));
  }
  
  AutoCloseable enterAndLock() {
    return combineAutoCloseables(enter(), tempLock(lock));
  }
  
  boolean setError(Throwable e) {
    setField("_error" , persistableThrowable(e));
    return true;
  }
  
  void clearError() {
    setField("_error" , null);
  }
  
  void onChange(Runnable r) {
    Lock __252 = lock; lock(__252); try {
    if (onChange == null) onChange = synchroList();
    addIfNotThere(onChange, r);
  } finally { unlock(__252); } }
  
  void update() {}
  
  void unvisualize() {
    zeroAllFieldsOfTypeExcept(this, Component.class, componentFieldsToKeep);
  }
  
  List<AbstractAction> menuItems() {
    return null;
  }
  
  void enhanceFrame(Container f) {
    internalFramePopupMenuFromActions_threaded(f, menuItems());
    String switchableFields = callOpt(this, "switchableFields");
    for (String field : splitAtSpace(switchableFields))
      if (eq(boolean.class, fieldType(this, field)))
        dm_boolFieldMenuItem(f, field);
  }
  
  // assume this is called in start(), so no locking
  ReliableSingleThread rstUpdate() {
    if (rstUpdate == null) rstUpdate = dm_rst(this, new Runnable() {  public void run() { try {  updateMe(); 
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "updateMe();"; }});
    return rstUpdate;
  }
  
  Q q() {
    if (q == null) {
      Lock __253 = lock; lock(__253); try {
      if (q == null) q = dm_startQ();
    } finally { unlock(__253); } }
    return q;
  }
  
  <A> A withUpdate(A a) {
    rstUpdate().trigger();
    return a;
  }
  
  DynModule module() { return this; }
}

static void _registerTimer(java.util.Timer timer) {
  _registerTimer_original(timer);
  dm_currentModule().ownTimer(timer);
}
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 class Q implements AutoCloseable {
  String name = "Unnamed Queue";
  List<Runnable> q = synchroLinkedList();
  ReliableSingleThread rst = new ReliableSingleThread(new Runnable() {  public void run() { try {  _run() ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "_run()"; }});
  volatile boolean retired;
  
  Q() {}
  Q(String name) {
  this.name = name;}
  
  void add(Runnable r) {
    q.add(r);
    _trigger();
  }
  
  void _trigger() {
    rst.name = name;
    rst.go();
  }
  
  void add(Object r) {
    add(toRunnable(r));
  }
  
  void _run() {
    Runnable r;
    while (licensed() && !retired && (r = syncPopFirst(q)) != null) {
      try { r.run(); } catch (Throwable __e) { _handleException(__e); }
    }
  }
  
  public void close() { retired = true; } // TODO: interrupt thread
  void done() {} // legacy function
  
  boolean isEmpty() { return q.isEmpty(); }
  int size() { return q.size(); }
}static class ReliableSingleThread implements Runnable {
  Object runnable;
  boolean trigger;
  Thread thread;
  String name = "Single Thread";
  F0<AutoCloseable> enter; // optional ownership marker, e.g. for DynModules
  
  ReliableSingleThread(Object runnable) {
  this.runnable = runnable;}
  
  void trigger() { go(); }
  synchronized void go() {
    trigger = true;
    if (!running()) {
       AutoCloseable __261 = callF(enter); try {
      thread = startThread(name, new Runnable() {  public void run() { try {  _run(); 
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "_run();"; }});
    } finally { _close(__261); }}
  }
  public void run() { go(); }
  void get() { go(); } // so you can use the ! syntax
  
  synchronized boolean running() { return thread != null; }
  
  // use only if this is the last time you trigger this
  void triggerAndWait() {
    trigger();
    while (running()) sleep(1);
  }
  
  void _run() {
    while (licensed()) {
      synchronized(this) {
        if (!trigger) {
          thread = null;
          break;
        }
        trigger = false;
      }
      pcallF(runnable);
    }
  }
  
  synchronized void cancel() {
    cancelAndInterruptThread(thread);
    thread = null;
  }
}static interface IVar<A> {
  void set(A a);
  A get();
  boolean has();
  void clear();
}

static List<String> myInnerClasses_list=litlist(
"_MethodCache", "VF1", "Var", "F0", "LiveValue", "F1", "F2", "Flag", "Q", "componentPopupMenu_Adapter", "getOpt_Map", "PersistableThrowable", "ReliableSingleThread", "XChartRealTimeTest", "DynModule", "IVar", "Pair");

static List<String> myInnerClasses() {
  return myInnerClasses_list;
}

static InheritableThreadLocal < WeakReference < DynModule > > dm_currentModule_value = new InheritableThreadLocal();

static DynModule dm_currentModule() {
  return getWeakRef(dm_currentModule_value.get());
}

// prevent memory leak
static void cleanMeUp_dm_currentModule() {
  dm_currentModule_value = new InheritableThreadLocal();
}
static void cancelTimerOrInterruptThread(Object timer) {
  if (timer instanceof Thread && !(timer instanceof AutoCloseable)) // AutoCloseable takes precedence
    interruptThread((Thread) timer);
  else
    cancelTimer(timer);
}
  static Method findMethod(Object o, String method, Object... args) {
    try {
      if (o == null) return null;
      if (o instanceof Class) {
        Method m = findMethod_static((Class) o, method, args, false);
        if (m == null) return null;
        m.setAccessible(true);
        return m;
      } else {
        Method m = findMethod_instance(o, method, args, false);
        if (m == null) return null;
        m.setAccessible(true);
        return m;
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

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

        if ((m.getModifiers() & Modifier.STATIC) == 0 || !findMethod_checkArgs(m, args, debug))
          continue;

        return m;
      }
      c = c.getSuperclass();
    }
    return null;
  }

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

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



static Flag dm_initErrorHandling_flag = new Flag();

static void dm_initErrorHandling() {
  raiseFlagAndDo(dm_initErrorHandling_flag, new Runnable() {  public void run() { try { 
    _handleException_addHandler("dm_initErrorHandling_handler");
    
    assertNull(_onRegisterThread);
    _onRegisterThread = new VF1<Thread>() { public void get(Thread t) { try { 
      DynModule m = dm_currentModule();
      if (m == null) printStackTrace("New thread made outside of a module");
      else m.ownTimer(t);
     } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "DynModule m = dm_currentModule();\r\n      if (m == null) printStackTrace(\"New ..."; }};
    _threadInfo_makers.add(new VF1<Map>() { public void get(Map map) { try {  mapPut(map, "dm_currentModule_value", dm_currentModule()) ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "mapPut(map, 'dm_currentModule_value, dm_currentModule())"; }});
    _threadInheritInfo_retrievers.add(new VF1<Map>() { public void get(Map map) { try { 
      Object mod = map.get("dm_currentModule_value");
      if (mod instanceof DynModule) dm_currentModule_value.set(new WeakReference((DynModule) mod));
     } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "O mod = map.get('dm_currentModule_value);\r\n      if (mod instanceof DynModule..."; }});
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "_handleException_addHandler(f dm_initErrorHandling_handler);\r\n    \r\n    asser..."; }});
}

static void dm_initErrorHandling_handler(Throwable e) {
  DynModule m = dm_currentModule();
  if (m == null)
    print("Weird: Error outside of module");
  else
    m.setField("_error" , persistableThrowable(e));
}



static void setMainDesktopPane(JDesktopPane desktop) {
  mainDesktopPane_value = desktop;
}
static <A> A getCreatorOpt(String field) {
  return (A) getOpt(creator(), field);
}
static boolean isTrue(Object o) {
  if (o instanceof Boolean)
    return ((Boolean) o).booleanValue();
  if (o == null) return false;
  if (o instanceof ThreadLocal)
    return isTrue(((ThreadLocal) o).get());
  throw fail(getClassName(o));
}
static <A extends Component> A possiblyInternalFrameTitle(A c, String title) {
  JInternalFrame f = getInternalFrame(c);
  if (f != null) internalFrameTitle(f, title);
  else frameTitle(getFrame(c), title);
  return c;
}
static void vmBus_send(String msg, Object... args) {
  Object arg = empty(args) ? null
    : l(args) == 1 ? args[0]
    : args;
  pcallFAll(vm_busListeners_live(), msg, arg);
  pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg);
}

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


static void ownResource(AutoCloseable c) {
  _registerAutoCloseable(c);
}
static <A> List<A> getAndClearList(Collection<A> l) {
  if (l == null) return emptyList();
  synchronized(collectionMutex(l)) {
    List<A> out = cloneList(l);
    l.clear();
    return out;
  }
}
static <A, B> Map<A, B> getAndClearMap(Map<A, B> map) {
  if (map == null) return emptyMap();
  synchronized(collectionMutex(map)) {
    Map<A, B> out = cloneMap(map);
    map.clear();
    return out;
  }
}
static <A, B> Set<A> keys(Map<A, B> map) {
  return map == null ? new HashSet() : map.keySet();
}

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






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

static <A> A callOpt(Object o, String method, Object... args) {
  return (A) callOpt_cached(o, method, args);
}
static void lock(Lock lock) { try {
  ping();
  if (lock == null) return;
  try {
    lock.lockInterruptibly();
  } catch (InterruptedException e) {
    print("Locking interrupted! I probably deadlocked, oops.");
    printStackTrace(e);
    rethrow(e);
  }
  ping();
} catch (Exception __e) { throw rethrow(__e); } }

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 void unlock(Lock lock, String msg) {
  if (lock == null) return;
  print("Unlocking: " + msg);
  lock.unlock();
}

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

static void set(Class c, String field, Object value) {
  try {
    Field f = set_findStaticField(c, field);
    f.setAccessible(true);
    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 <A, B> B mapGet(Map<A, B> map, A a) {
  return map == null || a == null ? null : map.get(a);
}
static WeakReference<Object> creator_class;

static Object creator() {
  return creator_class == null ? null : creator_class.get();
}
static <A> AutoCloseable tempSetThreadLocal(final ThreadLocal<A> tl, A a) {
  final A prev = setThreadLocal(tl, a);
  return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception {  tl.set(prev); }};
}
static AutoCloseable combineAutoCloseables(final AutoCloseable a, final AutoCloseable b) {
  return a == null ? b : b == null ? a : new AutoCloseable() { public String toString() { return "a.close(); b.close();"; } public void close() throws Exception {  a.close(); b.close(); }};
}

static AutoCloseable combineAutoCloseables(Iterable<AutoCloseable> l) {
  return foldl(new F2<AutoCloseable, AutoCloseable, AutoCloseable>() { AutoCloseable get(AutoCloseable a, AutoCloseable b) { try { return  combineAutoCloseables(a,b) ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "combineAutoCloseables(a,b)"; }}, null, l);
}
static AutoCloseable tempLock(final Lock lock) {
  if (lock == null) return null;
  lock(lock);
  return new AutoCloseable() { public String toString() { return "unlock(lock);"; } public void close() throws Exception {  unlock(lock); }};
}
static <A> boolean addIfNotThere(Collection<A> c, A a) {
  return setAdd(c, a);
}
static void zeroAllFieldsOfTypeExcept(Object o, Class type, String... exceptions) {
  zeroAllFieldsOfTypeExcept(o, type, asSet(exceptions));
}

static void zeroAllFieldsOfTypeExcept(Object o, Class type, Collection<String> exceptions) {
  Set<String> set = asSet(exceptions);
  for (String field : allFields(o))
    if (!set.contains(field) && instanceOf(getOpt(o, field), type))
      set(o, field, null);
}
static void internalFramePopupMenuFromActions_threaded(Container f, List<AbstractAction> actions) {
  if (!(f instanceof JInternalFrame)) return;
  for (final AbstractAction a : unnull(actions))
    if (a != null)
      internalFramePopupMenuItem(((JInternalFrame) f), str(a.getValue(Action.NAME)), runnableThread(new Runnable() {  public void run() { try {  callAction(a) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "callAction(a)"; }}));
}
static List<String> splitAtSpace(String s) {
  return empty(s) ? emptyList() : asList(s.split("\\s+"));
}
static Class fieldType(Object o, String field) {
  Field f = getField(o, field);
  return f == null ? null : f.getType();
}
static void dm_boolFieldMenuItem(Container frame, final String field, final Object... _) {
  final DynModule m = dm_current_mandatory();
  final String humanized = humanizeFormLabel(field);
  internalFrameTitlePopupMenu(((JInternalFrame) frame), new VF1<JPopupMenu>() { public void get(JPopupMenu menu) { try { 
    menu.add(jCheckBoxMenuItem(humanized, (boolean) _get(m, field), new VF1<Boolean>() { public void get(Boolean b) { try { 
      m.setField(field, b);
      callF(optPar(_, "onSet"));
     } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "m.setField(field, b);\r\n      callF(optPar(_, 'onSet));"; }}));
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "menu.add(jCheckBoxMenuItem(humanized, (bool) _get(m, field), voidfunc(bool b)..."; }});
}
static ReliableSingleThread dm_rst(DynModule mod, Runnable r) {
  return dm_rst(mod, new ReliableSingleThread(r));
}

static ReliableSingleThread dm_rst(DynModule mod, ReliableSingleThread rst) {
  rst.enter = dm_rEnter(mod);
  return rst;
}
static Q dm_startQ() {
  Q q = startQ();
  q.rst.enter = dm_rEnter(dm_current_mandatory()); 
  dm_ownResource(q);
  return q;
}
static Set<java.util.Timer> _registerTimer_list = newWeakHashSet();

static void _registerTimer_original(java.util.Timer timer) {
  _registerTimer_list.add(timer);
}

static void cleanMeUp__registerTimer() {
  cancelTimers(getAndClearList(_registerTimer_list));
}
static int hashCodeFor(Object a) {
  return a == null ? 0 : a.hashCode();
}
static <A> List<A> synchroLinkedList() {
  return Collections.synchronizedList(new LinkedList<A>());
}

static Class _run(String progID, String... args) {
  Class main = hotwire(progID);
  callMain(main, args);
  return main;
}
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 volatile boolean licensed_yes = true;

static boolean licensed() {
  ping();
  return licensed_yes;
}

static void licensed_off() {
  licensed_yes = false;
}
static <A> A syncPopFirst(List<A> l) {
  if (empty(l)) return null;
  synchronized(l) {
    A a = first(l);
    l.remove(0);
    return a;
  }
}
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 volatile boolean sleep_noSleep;

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 void cancelAndInterruptThread(Thread t) {
  if (t == null) return;
  cancelThread(t);
  t.interrupt();
}


static <A> ArrayList<A> litlist(A... a) {
  ArrayList l = new ArrayList(a.length);
  for (A x : a) l.add(x);
  return l;
}
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 Object _onAWTEnter_f;

static AutoCloseable _onAWTEnter() {
  return (AutoCloseable) callF(_onAWTEnter_f);
}
static JDesktopPane mainDesktopPane_value;

static JDesktopPane mainDesktopPane() {
  return mainDesktopPane_value;
}
static <A> A getWeakRef(WeakReference<A> ref) {
  return ref == null ? null : ref.get();
}
static void interruptThread(Thread t) {
  if (t == null) return;
  t.interrupt();
  URLConnection c = (URLConnection) ( vm_generalSubMap("URLConnection per thread").get(t));
  if (c != null) { try {
    print("Closing URLConnection of interrupted thread.");
    call(c, "disconnect");
  } catch (Throwable __e) { _handleException(__e); }}
}
static void raiseFlagAndDo(Flag flag, Runnable r) {
  if (flag.raise()) callF(r);
}
static void _handleException_addHandler(Object handler) {
  addIfNotThere(_handleException_onException, handler);
}
static <A> A assertNull(A a) {
  assertTrue(a == null);
  return a;
}

static <A> A assertNull(String msg, A a) {
  assertTrue(msg, a == null);
  return a;
}
static <A, B> void mapPut(Map<A, B> map, A key, B value) {
  if (map != null && key != null && value != null) map.put(key, value);
}
static JInternalFrame getInternalFrame(final Object _o) {
  return _o == null ? null : swing(new F0<JInternalFrame>() { 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 extends Component> A internalFrameTitle(A c, final String title) {
  final JInternalFrame f = getInternalFrame(c);
  if (f != null) { swing(new Runnable() {  public void run() { try {  f.setTitle(unnull(title)); 
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "f.setTitle(unnull(title));"; }}); }
  return c;
}

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

static String internalFrameTitle(Component c) {
  final JInternalFrame f = getInternalFrame(c);
  return f == null ? null : swing(new F0<String>() { String get() { try { return  f.getTitle() ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "f.getTitle()"; }});
}

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

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

static String frameTitle(Component c) {
  return getFrameTitle(c);
}

static JFrame getFrame(final Object _o) {
  return swing(new F0<JFrame>() { 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 Set vm_busListeners_live() {
  return vm_generalIdentityHashSet("busListeners");
}
static Map<String, Set> vm_busListenersByMessage_live() {
  return vm_generalHashMap("busListenersByMessage");
}
static Set<AutoCloseable> _registerAutoCloseable_set = synchroHashSet();

static void _registerAutoCloseable(AutoCloseable c) {
  addIfNotNull(_registerAutoCloseable_set, c);
}

static void cleanMeUp__registerAutoCloseable() {
  closeAutoCloseables(getAndClearList(_registerAutoCloseable_set));
}
static List emptyList() {
  return new ArrayList();
  //ret Collections.emptyList();
}

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

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

// get correct type at once
static <A> List<A> emptyList(Class<A> c) {
  return new ArrayList();
}
static Map emptyMap() {
  return new HashMap();
}
static <A, B> Map<A, B> cloneMap(Map<A, B> map) {
  if (map == null) return new HashMap();
  // assume mutex is equal to collection
  synchronized(map) {
    return map instanceof TreeMap ? new TreeMap((TreeMap) map) // copies comparator
      : map instanceof LinkedHashMap ? new LinkedHashMap(map)
      : new HashMap(map);
  }
}
static void lockOrFail(Lock lock, long timeout) { try {
  ping();
  if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
    String s = "Couldn't acquire lock after " + timeout + " ms.";
    if (lock instanceof ReentrantLock) {
      ReentrantLock l = (ReentrantLock) ( lock);
      s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
    }
    throw fail(s);
  }
  ping();
} catch (Exception __e) { throw rethrow(__e); } }
static ReentrantLock fairLock() {
  return new ReentrantLock(true);
}
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)
      value = ((Long) value).intValue();
    
    if (type == LinkedHashMap.class && value instanceof Map)
      { f.set(o, asLinkedHashMap((Map) value)); return; }
    
    
    throw e;
  }
}
static <A> A setThreadLocal(ThreadLocal<A> tl, A value) {
  if (tl == null) return null;
  A old = tl.get();
  tl.set(value);
  return old;
}
static <A, B> A foldl(F2<A, B, A> f, A seed, Iterable<B> l) {
  A a = seed;
  if (l != null) for(B b : l)
    a = callF(f, a, b);
  return a;
}
static <A> boolean setAdd(Collection<A> c, A a) {
  if (c == null || c.contains(a)) return false;
  c.add(a);
  return true;
}
static Set asSet(Object[] array) {
  HashSet set = new HashSet();
  for (Object o : array)
    if (o != null)
      set.add(o);
  return set;
}

static Set<String> asSet(String[] array) {
  TreeSet<String> set = new TreeSet();
  for (String o : array)
    if (o != null)
      set.add(o);
  return set;
}

static <A> Set<A> asSet(Iterable<A> l) {
  if (l instanceof Set) return (Set) l;
  HashSet<A> set = new HashSet();
  for (A o : unnull(l))
    if (o != null)
      set.add(o);
  return set;
}
static Set<String> allFields(Object o) {
  TreeSet<String> fields = new TreeSet();
  Class _c = _getClass(o);
  do {
    for (Field f : _c.getDeclaredFields())
      fields.add(f.getName());
    _c = _c.getSuperclass();
  } while (_c != null);
  return fields;
}
static boolean instanceOf(Object o, String className) {
  if (o == null) return false;
  String c = o.getClass().getName();
  return eq(c, className) || eq(c, "main$" + className);
}

static boolean instanceOf(Object o, Class c) {
  if (c == null) return false;
  return c.isInstance(o);
}
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 <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[]) new Object[0] : a;
}

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



//ifclass Symbol

static void internalFramePopupMenuItem(Container f, final String name, final Object action) {
  internalFrameTitlePopupMenuItem(((JInternalFrame) f), name, action);
}
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 void callAction(Action a) {
  if (a != null) a.actionPerformed(null);
}
static Field getField(Object o, String field) {
  if (o == null) return null;
  return setOpt_findField(_getClass(o), field);
}
static DynModule dm_current_mandatory() {
  return assertNotNull("No module set!", dm_currentModule());
}
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")
  );
}
// menuMaker = voidfunc(JPopupMenu)
static void internalFrameTitlePopupMenu(final JInternalFrame f, final Object... params) {
  { swing(new Runnable() {  public void run() { try { 
    Object menuMaker;
    if (l(params) == 1)
      menuMaker = params[0];
    else
      menuMaker = new VF1<JPopupMenu>() { public void get(JPopupMenu menu) { try {  addMenuItems(menu, params) ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "addMenuItems(menu, params)"; }};
    
    Component titleComponent = getInternalFrameTitlePaneComponent(f);
    if (!(titleComponent instanceof JComponent))
      print("Can't add internal frame title popup menu!");
    else
      componentPopupMenu((JComponent) titleComponent, menuMaker);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "Object menuMaker;\r\n    if (l(params) == 1)\r\n      menuMaker = params[0];\r\n   ..."; }}); }
}
// r : runnable or voidfunc(bool)
static JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, final Object r) {
  final JCheckBoxMenuItem mi = new JCheckBoxMenuItem(text, checked);
  addActionListener(mi, new Runnable() {  public void run() { try {  callF(r, isChecked(mi)) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "callF(r, isChecked(mi))"; }});
  return mi;
}
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 <A> A _get(A[] l, int idx) {
  return idx >= 0 && idx < l(l) ? l[idx] : null;
}
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 <A> A optPar(Object[] params, String name) {
  return optParam(params, name);
}

static <A> A optPar(Object[] params, String name, A defaultValue) {
  return optParam(params, name, defaultValue);
}
static F0<AutoCloseable> dm_rEnter(final DynModule mod) {
  return mod == null ? null : new F0<AutoCloseable>() { AutoCloseable get() { try { return  mod.enter() ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "mod.enter()"; }};
}
static Q startQ() {
  return new Q();
}

static Q startQ(String name) {
  return new Q(name);
}
static AutoCloseable dm_ownResource(AutoCloseable resource) {
  dm_currentModuleMandatory().ownResource(resource);
  return resource;
}
static <A> Set<A> newWeakHashSet() {
  return synchroWeakHashSet();
}
static void cancelTimers(Collection timers) {
  for (Object timer : timers) cancelTimer(timer);
}
static Class<?> hotwire(String src) {
  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 <A> A callMain(A c, String... args) {
  callOpt(c, "main", new Object[] {args});
  return c;
}

static void callMain() {
  callMain(mc());
}
static void addToContainer(final Container a, final Component b) {
  if (a != null && b != null) { swing(new Runnable() {  public void run() { try {  a.add(b); 
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "a.add(b);"; }}); }
}
static Object first(Object list) {
  return empty((List) list) ? null : ((List) list).get(0);
}

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



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) {
  return toRunnable(r);
}
// runnable = Runnable or String (method name)
static Thread newThread(Object runnable) {
  return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
}

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

static Thread newThread(String name, Object runnable) {
  return newThread(runnable, name);
}
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 void cancelThread(Thread t) {
  if (t == null) return;
  ping();
  /*O mc = getWeakRef((WeakReference) vm_generalWeakSubMap("thread2mc").get(t));
  ifdef cancelThread_verbose
  print("cancelThread: mc=" + mc);
  endifdef
  if (mc != null) {
    Map ping_actions = cast get(mc, 'ping_actions);
    synchronized(ping_actions) {
      ping_actions.put(t, "cancelled");
      set(mc, ping_anyActions := true);
    }
  } else*/ synchronized(ping_actions) {
    ping_actions.put(t, "cancelled");
    ping_anyActions = true;
  }
}


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 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 List<AbstractButton> buttonsInGroup(ButtonGroup g) {
  if (g == null) return ll();
  return asList(g.getElements());
}
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 String getFrameTitle(Component c) {
  JFrame f = getFrame(c);
  return f == null ? null : f.getTitle();
}
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> void addIfNotNull(Collection<A> l, A a) {
  if (a != null && l != null) l.add(a);
}


static void closeAutoCloseables(Collection<AutoCloseable> l) {
  if (l != null) for (AutoCloseable c : l) { try { c.close(); } catch (Throwable __e) { _handleException(__e); }}
}
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 <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 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 getClass(realm).getClassLoader().loadClass(classNameToVM(name));
  } catch (ClassNotFoundException e) {
    return null; // could optimize this
  }
}
static void internalFrameTitlePopupMenuItem(JInternalFrame f, final String name, final Object action) {
  internalFrameTitlePopupMenu(f, 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)"; }});
}
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); // possible improvement: skip setAccessible
} 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);
    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) {
        f.setAccessible(true);
        return f;
      }
    _c = _c.getSuperclass();
  } while (_c != null);
  return null;
}
static HashMap litmap(Object... x) {
  HashMap map = new HashMap();
  litmap_impl(map, x);
  return map;
}

static void litmap_impl(Map map, Object... x) {
  for (int i = 0; i < x.length-1; i += 2)
    if (x[i+1] != null)
      map.put(x[i], x[i+1]);
}
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>() { 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 void addMenuItems(JMenu m, Object... x) {
  fillJMenu(m, x);
}

static void addMenuItems(JPopupMenu m, Object... x) {
  fillJPopupMenu(m, x);
}
static JComponent getInternalFrameTitlePaneComponent(JInternalFrame f) {
  return (JComponent) childWithClassNameEndingWith(f, "InternalFrameTitlePane");
}



static Map<JComponent, List> componentPopupMenu_map;
static ThreadLocal<MouseEvent> componentPopupMenu_mouseEvent;

static void componentPopupMenu_init() {
  { swing(new Runnable() {  public void run() { try { 
    if (componentPopupMenu_map == null)
      componentPopupMenu_map = or((Map<JComponent, List>) getOpt(creator(), "componentPopupMenu_map"), (Map<JComponent, List>) (Map) newWeakHashMap());
    if (componentPopupMenu_mouseEvent == null)
      componentPopupMenu_mouseEvent = or((ThreadLocal<MouseEvent>) getOpt(creator(), "componentPopupMenu_mouseEvent"), new ThreadLocal());
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (componentPopupMenu_map == null)\r\n      componentPopupMenu_map = or((Map<J..."; }}); }
}

// menuMaker = voidfunc(JPopupMenu)
static void componentPopupMenu(final JComponent component, final Object menuMaker) {
  componentPopupMenu_init();
  if (component != null && menuMaker != null) { swing(new Runnable() {  public void run() { try { 
    List maker = componentPopupMenu_map.get(component);
    if (maker == null) {
      componentPopupMenu_map.put(component, maker = new ArrayList());
      component.addMouseListener(new componentPopupMenu_Adapter(maker));
    }
    maker.add(menuMaker);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "List maker = componentPopupMenu_map.get(component);\r\n    if (maker == null) {..."; }}); }
}

static class componentPopupMenu_Adapter extends MouseAdapter {
  List maker;
  
  componentPopupMenu_Adapter(List maker) {
  this.maker = maker;}
  
  public void mousePressed(MouseEvent e) { displayMenu(e); }
  public void mouseReleased(MouseEvent e) { displayMenu(e); }

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


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(final JCheckBox checkBox) {
  return checkBox != null && (boolean) swing(new F0<Boolean>() { Boolean get() { try { return  checkBox.isSelected() ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "checkBox.isSelected()"; }});
}

static boolean isChecked(final JCheckBoxMenuItem mi) {
  return mi != null && (boolean) swing(new F0<Boolean>() { Boolean get() { try { return  mi.isSelected() ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "mi.isSelected()"; }});
}
static <A> A optParam(ThreadLocal<A> tl, A defaultValue) {
  return optPar(tl, defaultValue);
}

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

static <A> A optParam(Object[] opt, String name, A defaultValue) {
  if (!even(l(opt))) throw fail("Odd parameter length");
  for (int i = 0; i < l(opt); i += 2)
    if (eq(opt[i], name))
      return (A) opt[i+1];
  return defaultValue;
}

static <A> A optParam(Object[] opt, String name) {
  return optParam(opt, name, null);
}
static DynModule dm_currentModuleMandatory() {
  return dm_current_mandatory();
}
static <A> Set<A> synchroWeakHashSet() {
  return Collections.newSetFromMap((Map) newWeakHashMap());
}
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 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 == '\0')
      out.append("\\0");
    else
      out.append(c);
  }
  out.append('"');
}
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 String programID() {
  return getProgramID();
}

static String programID(Object o) {
  return getProgramID(o);
}
static Runnable _topLevelErrorHandling(final Runnable runnable) {
  final Object info = _threadInfo();
  return new Runnable() {  public void run() { try { 
    try {
      _threadInheritInfo(info);
      runnable.run();
    } catch (Throwable __e) { _handleException(__e); }
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "pcall {\r\n      _threadInheritInfo(info);\r\n      runnable.run();\r\n    }"; }};
}


static <A> A vm_generalMap_get(Object key) {
  return (A) vm_generalMap().get(key);
}
static Object vm_generalMap_put(Object key, Object value) {
  return mapPutOrRemove(vm_generalMap(), key, value);
}
static <A, B> Map<A, B> newWeakMap() {
  return newWeakHashMap();
}
static <A> WeakReference<A> newWeakReference(A a) {
  return a == null ? null : new WeakReference(a);
}
static Frame getAWTFrame(final Object _o) {
  return swing(new F0<Frame>() { 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 <A> Set<A> syncIdentityHashSet() {
  return (Set) synchronizedSet(identityHashSet());
}
static Map syncHashMap() {
  return synchroHashMap();
}
static Class<?> getClass(String name) {
  try {
    return Class.forName(name);
  } catch (ClassNotFoundException e) {
    return null;
  }
}

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

static Class getClass(Object realm, String name) { try {
  try {
    return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
  } catch (ClassNotFoundException e) {
    return null;
  }
} catch (Exception __e) { throw rethrow(__e); } }
static String classNameToVM(String name) {
  return name.replace(".", "$");
}
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 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) {
      f.setAccessible(true);
      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) {
    f.setAccessible(true);
    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 boolean containsSpaces(String s) {
  return indexOf(s, ' ') >= 0;
}
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)
    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 (Object o : l)
      x.add(callF(f, 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()) {
    Map.Entry e = (Map.Entry) _e;
    x.add(callF(f, e.getKey(), e.getValue()));
  }
  return x;
}
static <A> A getOrKeep(Map<A, ? extends A> map, A 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();
  for (int i = 0; i < l(s); i++)
    if (isUpperCaseLetter(s.charAt(i)) && i > j) {
      l.add(substring(s, j, i));
      j = i;
    }
  if (j < l(s))
    l.add(substring(s, j));
  return l;
}
static void fillJMenu(final JMenu m, Object... x) {
  //ifdef fillJMenu_debug
  //print("fillJMenu " + m);
  //endifdef
  if (x == null) return;
  for (int i = 0; i < l(x); i++) {
    Object o = x[i], y = get(x, i+1);
    if (o instanceof List)
      fillJMenu(m, asArray((List) o));
    else if (eqOneOf(o, "***", "---", "===", ""))
      m.addSeparator();
    
    else if (o instanceof LiveValue && ((LiveValue) o).getType() == String.class && isRunnableX(y)) {
      final LiveValue<String> lv = (LiveValue<String>) ( o);
      final JMenuItem mi = jmenuItem(or2(unCurlyBracket(lv.get()), "..."), y);
      bindLiveValueListenerToComponent(mi, lv, new Runnable() {  public void run() { try { 
        String s = lv.get();
        if (isCurlyBracketed(s)) {
          setEnabled(mi, false);
          s = unCurlyBracket(s);
        } else
          setEnabled(mi, true);
        setText(mi, s);
        revalidate(m);
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "String s = lv.get();\r\n        if (isCurlyBracketed(s)) {\r\n          setEnable..."; }});
      print("bound live value " + lv + " to menu item " + mi);
      m.add(mi);
      ++i;
    }
    
    else if (o instanceof String && isRunnableX(y)) {
      m.add(jmenuItem((String) o, y));
      ++i;
    } else if (o instanceof JMenuItem)
      m.add((JMenuItem) o); // "call" might use wrong method
    else if (o instanceof String || o instanceof Action || o instanceof Component)
      call(m, "add", o);
    else
      print("Unknown menu item: " + o);
  }
}
static void fillJPopupMenu(JPopupMenu m, Object... x) {
  if (x == null) return;
  for (int i = 0; i < l(x); i++) {
    Object o = x[i], y = get(x, i+1);
    if (o instanceof List)
      fillJPopupMenu(m, asArray((List) o));
    else if (eqOneOf(o, "***", "---", "===", ""))
      m.addSeparator();
    
    else if (o instanceof LiveValue && ((LiveValue) o).getType() == String.class && isRunnableX(y)) {
      final LiveValue<String> lv = (LiveValue<String>) ( o);
      final JMenuItem mi = jmenuItem("", y);
      bindLiveValueListenerToComponent(mi, lv, new Runnable() {  public void run() { try { 
        String s = lv.get();
        if (isCurlyBracketed(s)) {
          setEnabled(mi, false);
          s = unCurlyBracket(s);
        } else
          setEnabled(mi, true);
        setText(mi, s);
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "String s = lv.get();\r\n        if (isCurlyBracketed(s)) {\r\n          setEnable..."; }});
      m.add(mi);
    }
    
    else if (o instanceof String && isRunnableX(y)) {
      m.add(jmenuItem((String) o, y));
      ++i;
    } else if (o instanceof JMenuItem)
      m.add((JMenuItem) o); // "call" might use wrong method
    else if (o instanceof String || o instanceof Action || o instanceof Component)
      call(m, "add", o);
    else
      print("Unknown menu item: " + o);
  }
}
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 or(A a, A b) {
  return a != null ? a : b;
}
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 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 __291 = holdInstance(instanceToHold); try {
    callF(runnable);
  } finally { _close(__291); }} catch (Throwable __e) { messageBox(__e); }}};
}
static boolean even(int i) {
  return (i & 1) == 0;
}

static boolean even(long i) {
  return (i & 1) == 0;
}
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 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 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 <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 boolean jmenuItem_newThreads;

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

static JMenuItem jmenuItem(final String text, final Object r) {
  return swing(new F0<JMenuItem>() { JMenuItem get() { try { 
    Pair<String, Integer> p = jmenu_autoMnemonic(text);
    JMenuItem mi = new JMenuItem(p.a);
    if (p.b != 0) mi.setMnemonic(p.b);
    mi.addActionListener(jmenuItem_newThreads
      ? actionListenerInNewThread(r)
      : actionListener(r));
    return mi;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "Pair<S, Int> p = jmenu_autoMnemonic(text);\r\n    JMenuItem mi = new JMenuItem(..."; }});
}
static MenuItem menuItem(String text, final Object r) {
  MenuItem mi = new MenuItem(text);
  mi.addActionListener(actionListener(r));
  return mi;
}
static boolean isUpperCaseLetter(char c) {
  return Character.isUpperCase(c);
}
static Object[] asArray(List l) {
  return toObjectArray(l);
}

static <A> A[] asArray(Class<A> type, List l) {
  return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size()));
}
static boolean isRunnableX(Object o) {
  if (o == null) return false;
  if (o instanceof String) return hasMethod(mc(), (String) o);
  return o instanceof Runnable || hasMethod(o, "get");
}
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 String unCurlyBracket(String s) {
  return tok_unCurlyBracket(s);
}
static <A extends JComponent> A bindLiveValueListenerToComponent(A component, final LiveValue lv, final Runnable listener) {
  if (lv != null)
    bindToComponent(component,
      new Runnable() {  public void run() { try { 
        
        lv.onChangeAndNow(listener);
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "ifdef bindLiveValueListenerToComponent_debug\r\n          print(\"bindLiveValueL..."; }},
      new Runnable() {  public void run() { try {  lv.removeOnChangeListener(listener) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "lv.removeOnChangeListener(listener)"; }});
  return component;
}
static boolean isCurlyBracketed(String s) {
  return isCurlyBraced(s);
}
static void setEnabled(final JComponent c, final boolean enable) {
  if (c != null) { swing(new Runnable() {  public void run() { try {  c.setEnabled(enable); 
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "c.setEnabled(enable);"; }}); }
}
static boolean setText_opt = true; // optimize by calling getText first

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

static <A extends JComboBox> A setText(final A c, Object text) {
  // only for editable combo boxes at this point
  final String s = strUnnull(text);
  { swing(new Runnable() {  public void run() { try { 
    c.getEditor().setItem(s);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "c.getEditor().setItem(s);"; }}); }
  return c;
}

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

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

static <A> A setText(final A c, Object text) {
  if (c == null) return null;
  final String s = strUnnull(text);
  { swing(new Runnable() {  public void run() { try { 
    if (!setText_opt || neq(callOpt(c, "getText"), s))
      call(c, "setText", s);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (!setText_opt || neq(callOpt(c, \"getText\"), s))\r\n      call(c, \"setText\", s);"; }}); }
  return c;
}
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 List<Component> getComponents(final Component c) {
  return !(c instanceof Container) ? emptyList() : asList(swing(new F0<Component[]>() { Component[] get() { try { return  ((Container) c).getComponents() ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "((Container) c).getComponents()"; }}));
}
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 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 String formatSnippetIDOpt(String s) {
  return isSnippetID(s) ? formatSnippetID(s) : s;
}
static String formatSnippetID(String id) {
  return "#" + parseSnippetID(id);
}

static String formatSnippetID(long id) {
  return "#" + id;
}
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;
  return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) { throw rethrow(__e); } }


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 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 {
    { Thread _t_0 = new Thread("Action Listener") {
public void run() { try {
  
       AutoCloseable __454 = holdInstance(instanceToHold); try {
      callF(runnable);
    } finally { _close(__454); }} catch (Throwable __e) { _handleException(__e); } }
};
startThread(_t_0); }
  } catch (Throwable __e) { messageBox(__e); }}};
}
static Object[] toObjectArray(Collection c) {
  List l = asList(c);
  return l.toArray(new Object[l.size()]);
}

static boolean hasMethod(Object o, String method, Object... args) {
  return findMethod(o, method, args) != null;
}
static String tok_unCurlyBracket(String s) {
  return isCurlyBraced(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s;
}
static <A extends JComponent> A bindToComponent(final A component, final Runnable onShow, final Runnable onUnShow) {
  { swing(new Runnable() {  public void run() { try { 
    component.addAncestorListener(new AncestorListener() {
      public void ancestorAdded(AncestorEvent event) {
        pcallF(onShow);
      }
  
      public void ancestorRemoved(AncestorEvent event) {
        pcallF(onUnShow);
      }
  
      public void ancestorMoved(AncestorEvent event) {
      }
    });
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "component.addAncestorListener(new AncestorListener {\r\n      public void ances..."; }}); }
  return component;
}

static <A extends JComponent> A bindToComponent(A component, Runnable onShow) {
  return bindToComponent(component, onShow, null);
}
static boolean isCurlyBraced(String s) {
  List<String> tok = tok_combineCurlyBrackets_keep(javaTok(s));
  return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "{", "}");
}
static String strUnnull(Object o) {
  return o == null ? "" : str(o);
}
static String jlabel_textAsHTML_center_ifNeeded(String text) {
  if (swic(text, "<html>") && ewic(text, "</html>")) return text;
  if (!containsNewLines(text)) return text;
  return jlabel_textAsHTML_center(text);
}
static char lastChar(String s) {
  return empty(s) ? '\0' : s.charAt(l(s)-1);
}
static String[] dropLast(String[] a, int n) {
  n = Math.min(n, a.length);
  String[] b = new String[a.length-n];
  System.arraycopy(a, 0, b, 0, b.length);
  return b;
}

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 String getSelectedItem(JList l) {
  return (String) l.getSelectedValue();
}

static String getSelectedItem(JComboBox cb) {
  return strOrNull(cb.getSelectedItem());
}
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;
}
  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 boolean isLetterOrDigit(char c) {
  return Character.isLetterOrDigit(c);
}
static <A> List<A> dropFirstThreeAndLastThree(List<A> l) {
  return dropFirstAndLast(3, l);
}
// TODO: extended multi-line strings

static int javaTok_n, javaTok_elements;
static boolean javaTok_opt;

static List<String> javaTok(String s) {
  ++javaTok_n;
  ArrayList<String> tok = new ArrayList();
  int l = s == null ? 0 : s.length();
  
  int i = 0, n = 0;
  while (i < l) {
    int j = i;
    char c, d;
    
    // scan for whitespace
    while (j < l) {
      c = s.charAt(j);
      d = j+1 >= l ? '\0' : s.charAt(j+1);
      if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
        ++j;
      else if (c == '/' && d == '*') {
        do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
        j = Math.min(j+2, l);
      } else if (c == '/' && d == '/') {
        do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
      } else
        break;
    }
    
    tok.add(javaTok_substringN(s, i, j));
    ++n;
    i = j;
    if (i >= l) break;
    c = s.charAt(i);
    d = i+1 >= l ? '\0' : s.charAt(i+1);

    // scan for non-whitespace
    
    // Special JavaX syntax: 'identifier
    if (c == '\'' && Character.isJavaIdentifierStart(d) && i+2 < l && "'\\".indexOf(s.charAt(i+2)) < 0) {
      j += 2;
      while (j < l && Character.isJavaIdentifierPart(s.charAt(j)))
        ++j;
    } else if (c == '\'' || c == '"') {
      char opener = c;
      ++j;
      while (j < l) {
        int c2 = s.charAt(j);
        if (c2 == opener || c2 == '\n' && opener == '\'') { // allow multi-line strings, but not for '
          ++j;
          break;
        } else if (c2 == '\\' && j+1 < l)
          j += 2;
        else
          ++j;
      }
    } else if (Character.isJavaIdentifierStart(c))
      do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
    else if (Character.isDigit(c)) {
      do ++j; while (j < l && Character.isDigit(s.charAt(j)));
      if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
    } else if (c == '[' && d == '[') {
      do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
      j = Math.min(j+2, l);
    } else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
      do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
      j = Math.min(j+3, l);
    } else
      ++j;
      
    tok.add(javaTok_substringC(s, i, j));
    ++n;
    i = j;
  }
  
  if ((tok.size() % 2) == 0) tok.add("");
  javaTok_elements += tok.size();
  return tok;
}

static List<String> javaTok(List<String> tok) {
  return javaTokWithExisting(join(tok), tok);
}
static List<String> tok_combineCurlyBrackets_keep(List<String> tok) {
  List<String> l = new ArrayList();
  for (int i = 0; i < l(tok); i++) {
    String t = tok.get(i);
    if (odd(i) && eq(t, "{")) {
      int j = findEndOfCurlyBracketPart(tok, i);
      l.add(joinSubList(tok, i, j));
      i = j-1;
    } else
      l.add(t);
  }
  return l;
}
static boolean startsWithAndEndsWith(String s, String prefix, String suffix) {
  return startsWith(s, prefix) && endsWith(s, suffix);
}
static boolean swic(String a, String b) {
  return startsWithIgnoreCase(a, b);
}


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


static boolean containsNewLines(String s) {
  return containsNewLine(s);
}
static String jlabel_textAsHTML_center(String text) {
  return "<html><div style=\"text-align: center;\">"
    + replace(htmlencode(text), "\n", "<br>")
    + "</div></html>";
}
static <A> List<A> subList(List<A> l, int startIndex) {
  return subList(l, startIndex, l(l));
}

static <A> List<A> subList(List<A> l, int startIndex, int endIndex) {
  if (l == null) return null;
  startIndex = Math.max(0, startIndex);
  endIndex = Math.min(l(l), endIndex);
  if (startIndex >= endIndex) return ll();
  return l.subList(startIndex, endIndex);
}


static String strOrNull(Object o) {
  return o == null ? null : str(o);
}
static <A> A popLast(List<A> l) {
  return liftLast(l);
}
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> List<A> dropFirstAndLast(int n, List<A> l) {
  return new ArrayList(subList(l, n, l(l)-n));
}

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

static String dropFirstAndLast(String s) {
  return substring(s, 1, l(s)-1);
}
static String javaTok_substringN(String s, int i, int j) {
  if (i == j) return "";
  if (j == i+1 && s.charAt(i) == ' ') return " ";
  return s.substring(i, j);
}
static String javaTok_substringC(String s, int i, int j) {
  return s.substring(i, j);
}
static List<String> javaTokWithExisting(String s, List<String> existing) {
  ++javaTok_n;
  int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
  ArrayList<String> tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
  int l = s.length();
  
  int i = 0, n = 0;
  while (i < l) {
    int j = i;
    char c, d;
    
    // scan for whitespace
    while (j < l) {
      c = s.charAt(j);
      d = j+1 >= l ? '\0' : s.charAt(j+1);
      if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
        ++j;
      else if (c == '/' && d == '*') {
        do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
        j = Math.min(j+2, l);
      } else if (c == '/' && d == '/') {
        do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
      } else
        break;
    }
    
    if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
      tok.add(existing.get(n));
    else
      tok.add(javaTok_substringN(s, i, j));
    ++n;
    i = j;
    if (i >= l) break;
    c = s.charAt(i);
    d = i+1 >= l ? '\0' : s.charAt(i+1);

    // scan for non-whitespace
    
    // Special JavaX syntax: 'identifier
    if (c == '\'' && Character.isJavaIdentifierStart(d) && i+2 < l && "'\\".indexOf(s.charAt(i+2)) < 0) {
      j += 2;
      while (j < l && Character.isJavaIdentifierPart(s.charAt(j)))
        ++j;
    } else if (c == '\'' || c == '"') {
      char opener = c;
      ++j;
      while (j < l) {
        if (s.charAt(j) == opener /*|| s.charAt(j) == '\n'*/) { // allow multi-line strings
          ++j;
          break;
        } else if (s.charAt(j) == '\\' && j+1 < l)
          j += 2;
        else
          ++j;
      }
    } else if (Character.isJavaIdentifierStart(c))
      do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
    else if (Character.isDigit(c)) {
      do ++j; while (j < l && Character.isDigit(s.charAt(j)));
      if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
    } else if (c == '[' && d == '[') {
      do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
      j = Math.min(j+2, l);
    } else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
      do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
      j = Math.min(j+3, l);
    } else
      ++j;
      
    if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
      tok.add(existing.get(n));
    else
      tok.add(javaTok_substringC(s, i, j));
    ++n;
    i = j;
  }
  
  if ((tok.size() % 2) == 0) tok.add("");
  javaTok_elements += tok.size();
  return tok;
}

static boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
  return t.length() == j-i
    && s.regionMatches(i, t, 0, j-i); // << could be left out, but that's brave
}
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)); }
// i must point at the (possibly imaginary) opening bracket
// index returned is index of closing bracket + 1
static int findEndOfCurlyBracketPart(List<String> cnc, int i) {
  int j = i+2, level = 1;
  while (j < cnc.size()) {
    if (eq(cnc.get(j), "{")) ++level;
    else if (eq(cnc.get(j), "}")) --level;
    if (level == 0)
      return j+1;
    ++j;
  }
  return cnc.size();
}

static String joinSubList(List<String> l, int i, int j) {
  return join(subList(l, i, j));
}

static String joinSubList(List<String> l, int i) {
  return join(subList(l, i));
}
static boolean startsWithIgnoreCase(String a, String b) {
  return regionMatchesIC(a, 0, b, 0, b.length());
}
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 containsNewLine(String s) {
  return contains(s, '\n'); // screw \r, nobody needs it
}
static <A> List<A> replace(List<A> l, A a, A b) {
  for (int i = 0; i < l(l); i++)
    if (eq(l.get(i), a))
      l.set(i, b);
  return l;
}

static String replace(String s, String a, String b) {
  return s == null ? null : a == null || b == null ? s : s.replace(a, b);
}

static String replace(String s, char a, char b) {
  return s == null ? null : s.replace(a, b);
}
static String htmlencode(Object o) {
  return htmlencode(str(o));
}

static String htmlencode(String s) {
  if (s == null) return "";
  StringBuilder out = new StringBuilder(Math.max(16, s.length()));
  for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      /*if (c >= 0x100)
        out.append("&#x").append(charToHex(c)).append(';');
      else*/ if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&')
          out.append("&#").append((int) c).append(';');
      else
          out.append(c);
  }
  return out.toString();
}
static <A> A liftLast(List<A> l) {
  if (l.isEmpty()) return null;
  int i = l(l)-1;
  A a = l.get(i);
  l.remove(i);
  return a;
}
static long parseLong(String s) {
  if (s == null) return 0;
  return Long.parseLong(dropSuffix("L", s));
}

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


static boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
  
  
    return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
  
}
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 dropSuffix(String suffix, String s) {
  return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}


static abstract class LiveValue<A> {
  abstract Class<A> getType();
  abstract A get();
  abstract void onChange(Runnable l);
  abstract void removeOnChangeListener(Runnable l);
  
  void onChangeAndNow(Runnable l) {
    onChange(l);
    callF(l);
  }
}static abstract class F1<A, B> {
  abstract B get(A a);
}static abstract class F2<A, B, C> {
  abstract C get(A a, B b);
}/** this class is fully thread-safe */
static class Flag {
  private boolean up;

  /** returns true if flag was down before */
  public synchronized boolean raise() {
    if (!up) {
      up = true;
      notifyAll();
      return true;
    } else
      return false;
  }

  public synchronized void waitUntilUp() {
    while (!up) {
      try {
        wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

  public synchronized void waitUntilUp(long timeout) {
    if (!up) {
      try {
        wait(timeout);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

  public synchronized boolean isUp() {
    return up;
  }

  public String toString() {
    return isUp() ? "up" : "down";
  }

  // currently does a semi-active wait with latency = 50 ms
  public void waitForThisOr(Flag otherFlag) { try {
    while (!isUp() && !otherFlag.isUp())
      Thread.sleep(50);
  } catch (Exception __e) { throw rethrow(__e); } }
}

static void onChange(JSpinner spinner, Object r) {
  spinner.addChangeListener(changeListener(r));
}

static <A extends AbstractButton> A onChange(A b, Object r) {
  b.addItemListener(itemListener(r));
  return b;
}

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

static void onChange(final JSlider slider, final Object r) {
  { swing(new Runnable() {  public void run() { try { 
    slider.addChangeListener(changeListener(r));
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "slider.addChangeListener(changeListener(r));"; }}); }
}

static void onChange(JComboBox cb, final Object r) {
  if (isEditableComboBox(cb))
    onChange(textFieldFromComboBox(cb), r);
  else
    onSelectedItem(cb, new VF1<String>() { public void get(String s) { try {  callF(r) ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "callF(r)"; }});
}


static ChangeListener changeListener(final Object r) {
  return new ChangeListener() {
    public void stateChanged(ChangeEvent e) {
      pcallF(r);
    }
  };
}
static ItemListener itemListener(final Object r) {
  return new ItemListener() {
    public void itemStateChanged(ItemEvent e) {
      pcallF(r);
    }
  };
}
// action = runnable or method name
static void onUpdate(JComponent c, final Object r) {
  if (c instanceof JTextComponent)
    ((JTextComponent) c).getDocument().addDocumentListener(new DocumentListener() {
      public void insertUpdate(DocumentEvent e) {
        call(r);
      }
      public void removeUpdate(DocumentEvent e) {
        call(r);
      }
      public void changedUpdate(DocumentEvent e) {
        call(r);
      }
    });
  else if (c instanceof ItemSelectable) // JCheckBox and others
    ((ItemSelectable) c).addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent e) {
        call(r);
      }
    });
  else
    print("Warning: onUpdate doesn't know " + getClassName(c));
}

static void onUpdate(List<? extends JComponent> l, Object r) {
  for (JComponent c : l)
    onUpdate(c, r);
}
static boolean isEditableComboBox(final JComboBox cb) {
  return cb != null && swing(new F0<Boolean>() { Boolean get() { try { return  cb.isEditable() ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "cb.isEditable()"; }});
}
static JTextField textFieldFromComboBox(JComboBox cb) {
  return (JTextField) cb.getEditor().getEditorComponent();
}
static JComboBox onSelectedItem(final JComboBox cb, final VF1<String> f) {
  addActionListener(cb, new Runnable() {  public void run() { try { 
    pcallF(f, selectedItem(cb))
  ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "pcallF(f, selectedItem(cb))"; }});
  return cb;
}


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

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

}