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 java.awt.dnd.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.DataFlavor;
import javax.swing.event.AncestorEvent;
import java.awt.datatransfer.*;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.datatransfer.StringSelection;
import java.awt.geom.AffineTransform;
import java.awt.datatransfer.Transferable;
import java.awt.geom.*;
import javax.swing.event.AncestorListener;
import javax.swing.Timer;
import java.awt.geom.*;
import java.awt.font.GlyphVector;
import java.awt.geom.*;
import javax.swing.Timer;
import javax.swing.undo.UndoManager;
class main {
public static void main(final String[] args) throws Exception {
  Map<String, String> map;
  pnl(map = diagramServer_IDsAndMD5s());
  String url = diagramServer_idToURL(first(keys(map)));
  String calStruct = loadPage(url);
  printIndent(calStruct);
  showCAL(calStruct);
}
static String diagramServer_idToURL(String id) {
  return "http://ai1.lol/1010474/raw/" + parseInt(id);
}
static Map<String, String> diagramServer_IDsAndMD5s() {
  return litorderedmap(toObjectArray(allToString((List) safeUnstructure(loadPage("http://ai1.lol/1010474/raw/ids-and-md5s")))));
}
static <A, B> Set<A> keys(Map<A, B> map) {
  return map.keySet();
}

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


static Canvas showCAL(CirclesAndLines cal) {
  return cal.show();
}

static Canvas showCAL(CirclesAndLines cal, int w, int h) {
  return cal.show(w, h);
}

static Canvas showCAL(CirclesAndLines cal, Canvas canvas) {
  if (canvas == null) return cal.show();
  Canvas c2 = cal.makeCanvas();
  awtReplaceComponent(canvas, c2);
  return c2;
}

static Canvas showCAL(String calStructure) {
  return showCAL(calFromStructure(calStructure));
}
static Map<Thread, Boolean> _registerThread_threads = Collections.synchronizedMap(new WeakHashMap());

static Thread _registerThread(Thread t) {
  _registerThread_threads.put(t, true);
  return t;
}

static void _registerThread() { _registerThread(Thread.currentThread()); }
static ThreadLocal<String> loadPage_charset = new ThreadLocal();
static boolean loadPage_allowGzip = true, loadPage_debug;
static boolean loadPage_anonymous; // don't send computer ID
static int loadPage_verboseness = 100000;
static int loadPage_retries = 1; //60; // seconds
static ThreadLocal<Boolean> loadPage_silent = new ThreadLocal();

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

public static String loadPageSilently(URL url) { try {
  IOException e = null;
  for (int tries = 0; tries < loadPage_retries; tries++)
    try {
      URLConnection con = openConnection(url);
      return loadPage(con, url);
    } catch (IOException _e) {
      e = _e;
      if (loadPageThroughProxy_enabled) {
        print("Trying proxy because of: " + e);
        try {
          return loadPageThroughProxy(str(url));
        } catch (Throwable e2) {
          print("  " + exceptionToStringShort(e2));
        }
      } else if (loadPage_debug)
        print(e);
      sleepSeconds(1);
    }
  throw e;
} catch (Exception __e) { throw rethrow(__e); } }

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

public static String loadPage(String url) { try {
  url = loadPage_preprocess(url);
  if (!isTrue(loadPage_silent.get()))
    print("Loading: " + hideCredentials(url));
  return loadPageSilently(new URL(url));
} catch (Exception __e) { throw rethrow(__e); } }

public static String loadPage(URL url) {
  print("Loading: " + hideCredentials(url.toExternalForm()));
  return loadPageSilently(url);
}

public static String loadPage(URLConnection con, URL url) throws IOException {
  try {
    if (!loadPage_anonymous)
      setHeaders(con);
    if (loadPage_allowGzip)
      con.setRequestProperty("Accept-Encoding", "gzip");
    con.setRequestProperty("X-No-Cookies", "1");
  } catch (Throwable e) {} // fails if within doPost
  String contentType = con.getContentType();
  if (contentType == null)
    throw new IOException("Page could not be read: " + url);
  //print("Content-Type: " + contentType);
  String charset = loadPage_charset == null ? null : loadPage_charset.get();
  if (charset == null) charset = loadPage_guessCharset(contentType);
  
  InputStream in = con.getInputStream();
  try {
    if ("gzip".equals(con.getContentEncoding())) {
      if (loadPage_debug)
        print("loadPage: Using gzip.");
      in = new GZIPInputStream(in);
    }
    Reader r = new InputStreamReader(in, charset);
    
    StringBuilder buf = new StringBuilder();
    int n = 0;
    while (true) {
      int ch = r.read();
      if (ch < 0)
        break;
      buf.append((char) ch);
      ++n;
      if ((n % loadPage_verboseness) == 0) print("  " + n + " chars read");
    }
    return buf.toString();
  } finally { in.close(); }
}

static String loadPage_guessCharset(String contentType) {
  Pattern p = Pattern.compile("text/[a-z]+;\\s*charset=([^\\s]+)\\s*");
  Matcher m = p.matcher(contentType);
  String match = m.matches() ? m.group(1) : null;
  if (loadPage_debug)
    print("loadPage: contentType=" + contentType + ", match: " + match);
  /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
  return or(match, "ISO-8859-1");
}

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 void printIndent(Object o) {
  print(indentx(str(o)));
}

static void printIndent(String indent, Object o) {
  print(indentx(indent, str(o)));
}

static void printIndent(int indent, Object o) {
  print(indentx(indent, str(o)));
}
static void pnl(Collection l) {
  printNumberedLines(l);
}

static void pnl(Map map) {
  printNumberedLines(map);
}


static LinkedHashMap litorderedmap(Object... x) {
  LinkedHashMap map = new LinkedHashMap();
  litmap_impl(map, x);
  return map;
}
static void sleepSeconds(double s) {
  if (s > 0) sleep(round(s*1000));
}
static <A> List<A> printNumberedLines(List<A> l) {
  printNumberedLines((Collection<A>) l);
  return l;
}

static void printNumberedLines(Map map) {
  printNumberedLines(mapToLines(map));
}

static <A> Collection<A> printNumberedLines(Collection<A> l) {
  int i = 0;
  if (l != null) for (A a : l) print((++i) + ". " + str(a));
  return l;
}

static void printNumberedLines(Object[] l) {
  printNumberedLines(asList(l));
}

static void printNumberedLines(Object o) {
  printNumberedLines(lines(str(o)));
}
static boolean empty(Collection c) { return c == null || c.isEmpty(); }
static boolean empty(String 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);
  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 Object[] toObjectArray(Collection c) {
  List l = asList(c);
  return l.toArray(new Object[l.size()]);
}

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

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

static String indentx(int n, String s) {
  return dropSuffix(repeat(' ', n), indent(n, s));
}

static String indentx(String indent, String s) {
  return dropSuffix(indent, indent(indent, s));
}
static List<String> allToString(Collection c) {
  List<String> l = new ArrayList();
  for (Object o : c) l.add(str(o));
  return l;
}
static RuntimeException rethrow(Throwable e) {
  throw asRuntimeException(e);
}
static void setHeaders(URLConnection con) throws IOException {
  String computerID = getComputerID_quick();
  if (computerID != null) try {
    con.setRequestProperty("X-ComputerID", computerID);
    con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version"));
  } catch (Throwable e) {
    //printShortException(e);
  }
}
static <A> A or(A a, A b) {
  return a != null ? a : b;
}
static URLConnection openConnection(URL url) { try {
  ping();
  callOpt(javax(), "recordOpenURLConnection", str(url));
  return url.openConnection();
} catch (Exception __e) { throw rethrow(__e); } }
// makeNewComponent: func(Component) -> Component
//                   or Component
static Component awtReplaceComponent(final Component c, final Object makeNewComponent) {
  return (Component) swing(new Object() { Object get() { try {  
    Container parent = c.getParent();
    if (parent == null) return null;
    Component[] l = parent.getComponents();
    LayoutManager layout = parent.getLayout();
    if (!(layout instanceof BorderLayout || layout instanceof ViewportLayout))
      warn("awtReplaceComponent only tested for BorderLayout/ViewportLayout. Have: " + layout);
    int idx = indexOf(l, c);
    if (idx < 0) throw fail("component not found in parent");
    //print("idx: " + idx);
    //print("Parent: " + parent);
    Object constraints = callOpt(layout, "getConstraints", c);
    //print("Constraints: " + constraints);
    
    // remove
    parent.remove(c);
  
    // add new component  
    Component newComponent = (Component) (makeNewComponent instanceof Component ? makeNewComponent :  callF(makeNewComponent, c));
    parent.add(newComponent, constraints, idx);
    validateFrame(parent);
    return newComponent;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "Container parent = c.getParent();\r\n    if (parent == null) null;\r\n    Component[..."; }});
}
static String exceptionToStringShort(Throwable e) {
  e = getInnerException(e);
  String msg = unnull(e.getMessage());
  if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
    return baseClassName(e) + ": " + msg;
  else
    return msg;
}
static String tb_mainServer_default = "http://tinybrain.de:8080";
static Object tb_mainServer_override; // func -> S

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

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

static boolean tb_mainServer_isDefault() {
  return eq(tb_mainServer(), tb_mainServer_default);
}
static Object safeUnstructure(String s) {
  return unstructure(s, true);
}
static int parseInt(String s) {
  return empty(s) ? 0 : Integer.parseInt(s);
}
static String str(Object o) {
  return o == null ? "null" : o.toString();
}

static String str(char[] c) {
  return new String(c);
}
static CirclesAndLines calFromStructure(String s) {
  return cal_unstructure(s);
}
static boolean isTrue(Object o) {
  if (o instanceof Boolean)
    return ((Boolean) o).booleanValue();
  if (o == null) return false;
  throw fail(getClassName(o));
}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile StringBuffer 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<F1<String, Boolean>> print_byThread; // special handling by thread

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

// 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) {
  if (print_byThread != null) {
    F1<String, Boolean> f = print_byThread.get();
    if (f != null)
      if (isFalse(f.get(s))) return;
  }

  print_raw(s);
}

static void print_raw(String s) {
  s = fixNewLines(s);
  // TODO if (print_maxLineLength != 0)
  StringBuffer loc = local_log;
  StringBuffer 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 void print(long l) {
  print(String.valueOf(l));
}

static void print(char c) {
  print(String.valueOf(c));
}

static void print_append(StringBuffer buf, String s, int max) {
  synchronized(buf) {
    buf.append(s);
    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);
    }
  }
}
static final boolean loadPageThroughProxy_enabled = false;

static String loadPageThroughProxy(String url) {
  return null;
}


static WeakHashMap<Class, ArrayList<Method>> callF_cache = new WeakHashMap();

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

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 methods.get(0).invoke(f, args);
  for (int i = 0; i < n; i++) {
    Method m = methods.get(i);
    if (call_checkArgs(m, args, false))
      return m.invoke(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 String getComputerID_quick() {
  return computerID();
}
static <A> ArrayList<A> asList(A[] a) {
  return 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 RuntimeException asRuntimeException(Throwable t) {
  return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static String trim(String s) { return s == null ? null : s.trim(); }
static String trim(StringBuilder buf) { return buf.toString().trim(); }
static String trim(StringBuffer buf) { return buf.toString().trim(); }
static Class javax() {
  return getJavaX();
}
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, 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;
}
static boolean isFalse(Object o) {
  return eq(false, o);
}
static boolean eq(Object a, Object b) {
  return a == null ? b == null : a == b || a.equals(b);
}
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(unnull(msg)); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }

static boolean warn_on = true;

static void warn(String s) {
  if (warn_on)
    print("Warning: " + s);
}

static void warn(String s, List<String> warnings) {
  warn(s);
  if (warnings != null)
    warnings.add(s);
}
static String getType(Object o) {
  return getClassName(o);
}
static String getClassName(Object o) {
  return o == null ? "null" : o.getClass().getName();
}
static String fixNewLines(String s) {
  return s.replace("\r\n", "\n").replace("\r", "\n");
}
static CirclesAndLines cal_unstructure(String s) {
  return (CirclesAndLines) unstructure(s);
}
static List<String> mapToLines(Map map) {
  List<String> l = new ArrayList();
  for (Object key : keys(map))
    l.add(str(key) + " = " + str(map.get(key)));
  return l;
}
static int indent_default = 2;

static String indent(int indent) {
  return repeat(' ', indent);
}

static String indent(int indent, String s) {
  return indent(repeat(' ', indent), s);
}

static String indent(String indent, String s) {
  return indent + s.replace("\n", "\n" + indent);
}

static String indent(String s) {
  return indent(indent_default, s);
}

static List<String> indent(String indent, List<String> lines) {
  List<String> l = new ArrayList();
  for (String s : lines)
    l.add(indent + s);
  return l;
}
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 = synchroMap(new WeakHashMap());

// always returns true
static boolean ping() {
  if (ping_pauseAll || ping_anyActions) ping_impl();
  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) {
    Object action;
    synchronized(ping_actions) {
      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 Object callOpt(Object o) {
  if (o == null) return null;
  return callF(o);
}

static Object callOpt(Object o, String method, Object... args) {
  try {
    if (o == null) return null;
    if (o instanceof Class) {
      Method m = callOpt_findStaticMethod((Class) o, method, args, false);
      if (m == null) return null;
      m.setAccessible(true);
      return m.invoke(null, args);
    } else {
      Method m = callOpt_findMethod(o, method, args, false);
      if (m == null) return null;
      m.setAccessible(true);
      return m.invoke(o, args);
    }
  } catch (Exception e) {
    //fail(e.getMessage() + " | Method: " + method + ", receiver: " + className(o) + ", args: (" + join(", ", map(f className, args) + ")");
    throw new RuntimeException(e);
  }
}

static Method callOpt_findStaticMethod(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 || !callOpt_checkArgs(m, args, debug))
        continue;

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

static Method callOpt_findMethod(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) && callOpt_checkArgs(m, args, debug))
        return m;
    }
    c = c.getSuperclass();
  }
  return null;
}

private static boolean callOpt_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 unnull(String s) {
  return s == null ? "" : s;
}

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

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

static Object[] unnull(Object[] a) {
  return a == null ? new Object[0] : a;
}

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


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

static Object unstructure(String text) {
  return unstructure(text, false);
}

static Object unstructure(String text, final boolean allDynamic) {
  return unstructure(text, allDynamic, null);
}

static int structure_internStringsLongerThan = 50;

static int unstructure_tokrefs; // stats

abstract static class unstructure_Receiver {
  abstract void set(Object o);
}

// classFinder: func(name) -> class (optional)
static Object unstructure(String text, boolean allDynamic,
  Object classFinder) {
  if (text == null) return null;
  return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder);
}

static Object unstructure_reader(BufferedReader reader) {
  return unstructure_tok(javaTokC_noMLS_onReader(reader), false, null);
}

static Object unstructure_tok(final Producer<String> tok, final boolean allDynamic, final Object classFinder) {
  final boolean debug = unstructure_debug;
  
  final class X {
    int i = -1;
    HashMap<Integer,Object> refs = new HashMap();
    HashMap<Integer,Object> tokrefs = new HashMap();
    HashSet<String> concepts = new HashSet();
    HashMap<String,Class> classesMap = new HashMap();
    List<Runnable> stack = new ArrayList();
    String curT;
    
    // look at current token
    String t() {
      return curT;
    }
    
    // get current token, move to next
    String tpp() {
      String t = curT;
      consume();
      return t;
    }
    
    void parse(final unstructure_Receiver out) {
      String t = t();
      
      int refID = 0;
      if (structure_isMarker(t, 0, l(t))) {
        refID = parseInt(t.substring(1));
        consume();
      }
      final int _refID = refID;
      
      // if (debug) print("parse: " + quote(t));
      
      final int tokIndex = i;  
      parse_inner(refID, tokIndex, new unstructure_Receiver() {
        void set(Object o) {
          if (_refID != 0)
            refs.put(_refID, o);
          if (o != null)
            tokrefs.put(tokIndex, o);
          out.set(o);
        }
      });
    }
    
    void parse_inner(int refID, int tokIndex, final unstructure_Receiver out) {
      String t = t();
      
      // if (debug) print("parse_inner: " + quote(t));
      
      Class c = classesMap.get(t);
      if (c == null) {
        if (t.startsWith("\"")) {
          String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan);
          out.set(s); return;
        }
        
        if (t.startsWith("'")) {
          out.set(unquoteCharacter(tpp())); return;
        }
        if (t.equals("bigint")) {
          out.set(parseBigInt()); return;
        }
        if (t.equals("d")) {
          out.set(parseDouble()); return;
        }
        if (t.equals("fl")) {
          out.set(parseFloat()); return;
        }
        if (t.equals("false") || t.equals("f")) {
          consume(); out.set(false); return;
        }
        if (t.equals("true") || t.equals("t")) {
          consume(); out.set(true); return;
        }
        if (t.equals("-")) {
          consume();
          t = tpp();
          out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t))); return;
        }
        if (isInteger(t) || isLongConstant(t)) {
          consume();
          //if (debug) print("isLongConstant " + quote(t) + " => " + isLongConstant(t));
          if (isLongConstant(t)) {
            out.set(parseLong(t)); return;
          }
          long l = parseLong(t);
          boolean isInt = l == (int) l;
          if (debug)
            print("l=" + l + ", isInt: " + isInt);
          out.set(isInt ? (Object) new Integer((int) l) : (Object) new Long(l)); return;
        }
        
        if (t.equals("File")) {
          consume();
          File f = new File(unquote(tpp()));
          out.set(f); return;
        }
        
        if (t.startsWith("r") && isInteger(t.substring(1))) {
          consume();
          int ref = Integer.parseInt(t.substring(1));
          Object o = refs.get(ref);
          if (o == null)
            print("Warning: unsatisfied back reference " + ref);
          out.set(o); return;
        }
      
        if (t.startsWith("t") && isInteger(t.substring(1))) {
          consume();
          int ref = Integer.parseInt(t.substring(1));
          Object o = tokrefs.get(ref);
          if (o == null)
            print("Warning: unsatisfied token reference " + ref);
          out.set(o); return;
        }
        
        if (t.equals("hashset")) {
          parseHashSet(out); return;
        }
        if (t.equals("treeset")) {
          parseTreeSet(out); return;
        }
        if (eqOneOf(t, "hashmap", "hm")) {
          consume();
          parseMap(new HashMap(), out);
          return;
        }
        if (t.equals("lhm")) {
          consume();
          parseMap(new LinkedHashMap(), out);
          return;
        }
        if (t.equals("{")) {
          parseMap(out); return;
        }
        if (t.equals("[")) {
          parseList(out); return;
        }
        if (t.equals("bitset")) {
          parseBitSet(out); return;
        }
        if (t.equals("array") || t.equals("intarray")) {
          parseArray(out); return;
        }
        if (t.equals("ba")) {
          consume();
          String hex = unquote(tpp());
          out.set(hexToBytes(hex)); return;
        }
        if (t.equals("boolarray")) {
          consume();
          int n = parseInt(tpp());
          String hex = unquote(tpp());
          out.set(boolArrayFromBytes(hexToBytes(hex), n)); return;
        }
        if (t.equals("class")) {
          out.set(parseClass()); return;
        }
        if (t.equals("l")) {
          parseLisp(out); return;
        }
        if (t.equals("null")) {
          consume(); out.set(null); return;
        }
        
        if (eq(t, "c")) {
          consume("c");
          t = t();
          assertTrue(isJavaIdentifier(t));
          concepts.add(t);
        }
      }
      
      if (eq(t, "j")) {
        consume("j");
        out.set(parseJava()); return;
      }

      if (c == null && !isJavaIdentifier(t))
        throw new RuntimeException("Unknown token " + (i+1) + ": " + t);
        
      // any other class name
      if (c == null) {
        // First, find class
        if (allDynamic) c = null;
        else c = classFinder != null ? (Class) callF(classFinder, t) : findClass(t);
        if (c != null)
          classesMap.put(t, c);
      }
          
      // Check if it has an outer reference
      consume();
      boolean hasBracket = eq(t(), "(");
      if (hasBracket) consume();
      boolean hasOuter = hasBracket && eq(t(), "this$1");
      
      DynamicObject dO = null;
      Object o = null;
      if (c != null) {
        o = hasOuter ? nuStubInnerObject(c) : nuEmptyObject(c);
        if (o instanceof DynamicObject) dO = (DynamicObject) o;
      } else {
        if (concepts.contains(t) && (c = findClass("Concept")) != null)
          o = dO = (DynamicObject) nuEmptyObject(c);
        else
          dO = new DynamicObject();
        dO.className = t;
        if (debug) print("Made dynamic object " + t + " " + shortClassName(dO));
      }
      
      // Save in references list early because contents of object
      // might link back to main object
      
      if (refID != 0)
        refs.put(refID, o != null ? o : dO);
      tokrefs.put(tokIndex, o != null ? o : dO);
      
      // NOW parse the fields!
      
      final LinkedHashMap<String,Object> fields = new LinkedHashMap(); // preserve order
      final Object _o = o;
      final DynamicObject _dO = dO;
      if (hasBracket) {
        stack.add(new Runnable() { public void run() { try { 
          if (eq(t(), ")")) {
            consume(")");
            objRead(_o, _dO, fields);
            out.set(_o != null ? _o : _dO);
          } else {
            final String key = unquote(tpp());
            consume("=");
            stack.add(this);
            parse(new unstructure_Receiver() {
              void set(Object value) {
                fields.put(key, value);
                if (eq(t(), ",")) consume();
              }
            });
          }
        
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (eq(t(), \")\")) {\r\n            consume(\")\");\r\n            objRead(_o, _dO, fie..."; }});
      } else {
        objRead(o, dO, fields);
        out.set(o != null ? o : dO);
      }
    }
    
    void objRead(Object o, DynamicObject dO, Map<String, Object> fields) {
      
      if (o != null)
        if (dO != null) {
          if (debug)
            printStructure("setOptAllDyn", fields);
          setOptAllDyn(dO, fields);
        } else {
          setOptAll(o, fields);
          
        }
      else for (String field : keys(fields))
        dO.fieldValues.put(field.intern(), fields.get(field));

      if (o != null)
        pcallOpt_noArgs(o, "_doneLoading");
    }
    
    void parseSet(final Set set, final unstructure_Receiver out) {
      parseList(new unstructure_Receiver() {
        void set(Object o) {
          set.addAll((List) o);
          out.set(set);
        }
      });
    }
    
    void parseLisp(final unstructure_Receiver out) {
      consume("l");
      consume("(");
      final ArrayList list = new ArrayList();
      stack.add(new Runnable() { public void run() { try { 
        if (eq(t(), ")")) {
          consume(")");
          out.set(newObject("main$Lisp", (String) list.get(0), subList(list, 1)));
        } else {
          stack.add(this);
          parse(new unstructure_Receiver() {
            void set(Object o) {
              list.add(o);
              if (eq(t(), ",")) consume();
            }
          });
        }
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (eq(t(), \")\")) {\r\n          consume(\")\");\r\n          out.set(newObject(\"main$..."; }});
    }
    
    void parseBitSet(final unstructure_Receiver out) {
      consume("bitset");
      consume("{");
      final BitSet bs = new BitSet();
      stack.add(new Runnable() { public void run() { try { 
        if (eq(t(), "}")) {
          consume("}");
          out.set(bs);
        } else {
          stack.add(this);
          parse(new unstructure_Receiver() {
            void set(Object o) {
              bs.set((Integer) o);
              if (eq(t(), ",")) consume();
            }
          });
        }
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (eq(t(), \"}\")) {\r\n          consume(\"}\");\r\n          out.set(bs);\r\n        } ..."; }});
    }
    
    void parseList(final unstructure_Receiver out) {
      consume("[");
      final ArrayList list = new ArrayList();
      stack.add(new Runnable() { public void run() { try { 
        if (eq(t(), "]")) {
          consume("]");
          out.set(list);
        } else {
          stack.add(this);
          parse(new unstructure_Receiver() {
            void set(Object o) {
              //if (debug) print("List element type: " + getClassName(o));
              list.add(o);
              if (eq(t(), ",")) consume();
            }
          });
        }
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (eq(t(), \"]\")) {\r\n          consume(\"]\");\r\n          out.set(list);\r\n        ..."; }});
    }
    
    void parseArray(final unstructure_Receiver out) {
      final String type = tpp();
      consume("{");
      final List list = new ArrayList();
      
      stack.add(new Runnable() { public void run() { try { 
        if (eq(t(), "}")) {
          consume("}");
          out.set(type.equals("intarray") ? toIntArray(list) : list.toArray());
        } else {
          stack.add(this);
          parse(new unstructure_Receiver() {
            void set(Object o) {
              list.add(o);
              if (eq(t(), ",")) consume();
            }
          });
        }
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (eq(t(), \"}\")) {\r\n          consume(\"}\");\r\n          out.set(type.equals(\"int..."; }});
    }
    
    Object parseClass() {
      consume("class");
      consume("(");
      String name = unquote(tpp());
      consume(")");
      name = dropPrefix("main$", name);
      Class c = allDynamic ? null : classFinder != null ? (Class) callF(classFinder, name) : findClass(name);
      if (c != null) return c;
      DynamicObject dO = new DynamicObject();
      dO.className = "java.lang.Class";
      dO.fieldValues.put("name", name);
      return dO;
    }
    
    Object parseBigInt() {
      consume("bigint");
      consume("(");
      String val = tpp();
      if (eq(val, "-"))
        val = "-" + tpp();
      consume(")");
      return new BigInteger(val);
    }
    
    Object parseDouble() {
      consume("d");
      consume("(");
      String val = unquote(tpp());
      consume(")");
      return Double.parseDouble(val);
    }
    
    Object parseFloat() {
      consume("fl");
      String val;
      if (eq(t(), "(")) {
        consume("(");
        val = unquote(tpp());
        consume(")");
      } else {
        val = unquote(tpp());
      }
      return Float.parseFloat(val);
    }
    
    void parseHashSet(unstructure_Receiver out) {
      consume("hashset");
      parseSet(new HashSet(), out);
    }
    
    void parseTreeSet(unstructure_Receiver out) {
      consume("treeset");
      parseSet(new TreeSet(), out);
    }
    
    void parseMap(unstructure_Receiver out) {
      parseMap(new TreeMap(), out);
    }
    
    Object parseJava() {
      String j = unquote(tpp());
      Matches m = new Matches();
      if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m))
        return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2)));
      else {
        warn("Unknown Java object: " + j);
        return null;
      }
    }
    
    void parseMap(final Map map, final unstructure_Receiver out) {
      consume("{");
      stack.add(new Runnable() {
        boolean v;
        Object key;
        
        public void run() { 
          if (v) {
            v = false;
            stack.add(this);
            consume("=");
            parse(new unstructure_Receiver() {
              void set(Object value) {
                map.put(key, value);
                if (debug)
                  print("parseMap: Got value " + getClassName(value) + ", next token: " + quote(t()));
                if (eq(t(), ",")) consume();
              }
            });
          } else {
            if (eq(t(), "}")) {
              consume("}");
              out.set(map);
            } else {
              v = true;
              stack.add(this);
              parse(new unstructure_Receiver() {
                void set(Object o) {
                  key = o;
                }
              });
            }
          } // if v else
        } // run()
      });
    }
    
    /*void parseSub(unstructure_Receiver out) {
      int n = l(stack);
      parse(out);
      while (l(stack) > n)
        stack
    }*/
    
    void consume() { curT = tok.next(); ++i; }
    
    void consume(String s) {
      if (!eq(t(), s)) {
        /*S prevToken = i-1 >= 0 ? tok.get(i-1) : "";
        S nextTokens = join(tok.subList(i, Math.min(i+2, tok.size())));
        fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")");*/
        throw fail(quote(s) + " expected, got " + quote(t()));
      }
      consume();
    }
    
    void parse_x(unstructure_Receiver out) {
      consume(); // get first token
      parse(out);
      while (nempty(stack))
        popLast(stack).run();
    }
  }
  
  final Var v = new Var();
  X x = new X();
  x.parse_x(new unstructure_Receiver() {
    void set(Object o) { v.set(o); }
  });
  unstructure_tokrefs = x.tokrefs.size();
  return v.get();
}

static boolean unstructure_debug;
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 String repeat(char c, int n) {
  n = Math.max(n, 0);
  char[] chars = new char[n];
  for (int i = 0; i < n; i++)
    chars[i] = c;
  return new String(chars);
}

static <A> List<A> repeat(A a, int n) {
  List<A> l = new ArrayList(n);
  for (int i = 0; i < n; i++)
    l.add(a);
  return l;
}

static <A> List<A> repeat(int n, A a) {
  return repeat(a, n);
}
// 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 instanceof Class) return get((Class) o, field);
    
    if (o instanceof Map)
      return ((Map) o).get(field);
      
    Field f = getOpt_findField(o.getClass(), field);
    if (f != null) {
      f.setAccessible(true);
      return f.get(o);
    }
      
    
      if (o instanceof DynamicObject)
        return ((DynamicObject) o).fieldValues.get(field);
    
  } catch (Exception e) {
    throw asRuntimeException(e);
  }
  throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}

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() & 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 String baseClassName(String className) {
  return substring(className, className.lastIndexOf('.')+1);
}

static String baseClassName(Object o) {
  return baseClassName(getClassName(o));
}
static String lines(Collection<String> lines) { return fromLines(lines); }
static List<String> lines(String s) { return toLines(s); }
static File getProgramFile(String progID, String fileName) {
  if (new File(fileName).isAbsolute())
    return new File(fileName);
  return new File(getProgramDir(progID), fileName);
}

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

  public static String loadTextFile(String fileName) {
    return loadTextFile(fileName, null);
  }
  
  public static String loadTextFile(File fileName, String defaultContents) {
    try {
      if (fileName == null || !fileName.exists())
        return defaultContents;
  
      FileInputStream fileInputStream = new FileInputStream(fileName);
      InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
      return loadTextFile(inputStreamReader);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  
  public static String loadTextFile(File fileName) {
    return loadTextFile(fileName, null);
  }

  public static String loadTextFile(String fileName, String defaultContents) {
    return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents);
  }
  
  public static String loadTextFile(Reader reader) throws IOException {
    StringBuilder builder = new StringBuilder();
    try {
      char[] buffer = new char[1024];
      int n;
      while (-1 != (n = reader.read(buffer)))
        builder.append(buffer, 0, n);
        
    } finally {
      reader.close();
    }
    return builder.toString();
  }
static String dropSuffix(String suffix, String s) {
  return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static Throwable getInnerException(Throwable e) {
  while (e.getCause() != null)
    e = e.getCause();
  return e;
}
static void validateFrame(Component c) {
  revalidateFrame(c);
}
static Object swing(Object f) {
  return swingAndWait(f);
}

static <A> A swing(F0<A> f) {
  return (A) swingAndWait(f);
}
static long round(double d) {
  return Math.round(d);
}
static Map litmap(Object... x) {
  TreeMap map = new TreeMap();
  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 final 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;
  synchronized(callMC_cache) {
    me = method == callMC_key ? callMC_value : null;
  }
  if (me != null) return callMC_value.invoke(null, args);

  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;
    }
    return me.invoke(null, args);
  }
  for (int i = 0; i < n; i++) {
    me = m.get(i);
    if (call_checkArgs(me, args, false))
      return me.invoke(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() & Modifier.STATIC) != 0) {
          m.setAccessible(true);
          multiMapPut(callMC_cache, m.getName(), m);
        }
      c = c.getSuperclass();
    }
  }
}
static boolean[] boolArrayFromBytes(byte[] a, int n) {
  boolean[] b = new boolean[n];
  int m = min(n, l(a)*8);
  for (int i = 0; i < m; i++)
    b[i] = (a[i/8] & 1 << (i & 7)) != 0;
  return b;
}
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
      out.append(c);
  }
  out.append('"');
}
// 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 String dropPrefix(String prefix, String s) {
  return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
static void swingAndWait(Runnable r) { try {
  if (isAWTThread())
    r.run();
  else
    EventQueue.invokeAndWait(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 Thread currentThread() {
  return Thread.currentThread();
}
static byte[] hexToBytes(String s) {
  int n = l(s) / 2;
  byte[] bytes = new byte[n];
  for (int i = 0; i < n; i++) {
    String hex = substring(s, i*2, i*2+2);
    try {
      bytes[i] = (byte) parseHexByte(hex);
    } catch (Throwable _e) {
      throw fail("Bad hex byte: " + quote(hex) + " at " + i*2 + "/" + l(s));
    }
  }
  return bytes;
}
static HashMap<String,Class> findClass_cache = new HashMap();

// currently finds only inner classes of class "main"
// returns null on not found
// this is the simple version that is not case-tolerant
static Class findClass(String name) {
  synchronized(findClass_cache) {
    if (findClass_cache.containsKey(name))
      return findClass_cache.get(name);
      
    if (!isJavaIdentifier(name)) return null;
    
    Class c;
    try {
      c = Class.forName("main$" + name);
    } catch (ClassNotFoundException e) {
      c = null;
    }
    findClass_cache.put(name, c);
    return c;
  }
}
static HashMap<Class,Constructor> nuEmptyObject_cache = new HashMap();

static <A> A nuEmptyObject(Class<A> c) { try {
  Constructor ctr;
  
  synchronized(nuEmptyObject_cache) {
    ctr = nuEmptyObject_cache.get(c);
    if (ctr == null) {
      nuEmptyObject_cache.put(c, ctr = nuEmptyObject_findConstructor(c));
      ctr.setAccessible(true);
    }
  }

  return (A) ctr.newInstance();
} catch (Exception __e) { throw rethrow(__e); } }

static Constructor nuEmptyObject_findConstructor(Class c) {
  for (Constructor m : c.getDeclaredConstructors())
    if (m.getParameterTypes().length == 0)
      return m;
  throw fail("No default constructor declared in " + c.getName());
}

static boolean setOptAllDyn_debug;

static void setOptAllDyn(DynamicObject o, Map<String, Object> fields) {
  if (fields == null) return;
  for (String field : keys(fields)) {
    Object val = fields.get(field);
    boolean has = hasField(o, field);
    if (has)
      setOpt(o, field, val);
    else {
      o.fieldValues.put(field.intern(), val);
      if (setOptAllDyn_debug) print("setOptAllDyn added dyn " + field + " to " + o + " [value: " + val + ", fieldValues = " + systemHashCode(o.fieldValues) + ", " + struct(keys(o.fieldValues)) + "]");
    }
  }
}
static boolean isJavaIdentifier(String s) {
  if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
    return false;
  for (int i = 1; i < s.length(); i++)
    if (!Character.isJavaIdentifierPart(s.charAt(i)))
      return false;
  return true;
}
static float parseFloat(String s) {
  return Float.parseFloat(s);
}
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 boolean structure_isMarker(String s, int i, int j) {
  if (i >= j) return false;
  if (s.charAt(i) != 'm') return false;
  ++i;
  while (i < j) {
    char c = s.charAt(i);
    if (c < '0' || c > '9') return false;
    ++i;
  }
  return true;
}
static void assertTrue(Object o) {
  assertEquals(true, 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 Object newObject(Class c, Object... args) {
  return nuObject(c, args);
}

static Object newObject(String className, Object... args) {
  return nuObject(className, args);
}

static boolean isLongConstant(String s) {
  if (!s.endsWith("L")) return false;
  s = s.substring(0, l(s)-1);
  return isInteger(s);
}
static List<String> toLines(File f) {
  return toLines(loadTextFile(f));
}

  public static List<String> toLines(String s) {
    List<String> lines = new ArrayList<String>();
    if (s == null) return lines;
    int start = 0;
    while (true) {
      int i = toLines_nextLineBreak(s, start);
      if (i < 0) {
        if (s.length() > start) lines.add(s.substring(start));
        break;
      }

      lines.add(s.substring(start, i));
      if (s.charAt(i) == '\r' && i+1 < s.length() && s.charAt(i+1) == '\n')
        i += 2;
      else
        ++i;

      start = i;
    }
    return lines;
  }

  private static int toLines_nextLineBreak(String s, int start) {
    for (int i = start; i < s.length(); i++) {
      char c = s.charAt(i);
      if (c == '\r' || c == '\n')
        return i;
    }
    return -1;
  }
static String internIfLongerThan(String s, int l) {
  return s == null ? null : l(s) >= l ? s.intern() : s;
}
static Class __javax;

static Class getJavaX() {
  return __javax;
}
static void pcallOpt_noArgs(Object o, String method) {
  try { callOpt_noArgs(o, method); } catch (Throwable __e) { printStackTrace2(__e); }
}
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) {
  startIndex = max(0, min(l(l), startIndex));
  endIndex = max(0, min(l(l), endIndex));
  if (startIndex > endIndex) return litlist();
  return l.subList(startIndex, endIndex);
}


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(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] 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 instanceof String ? l((String) o)
    : o instanceof Map ? l((Map) o)
    : l((Collection) o); // incomplete
}




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

static File getProgramDir(String snippetID) {
  return programDir(snippetID);
}
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 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 String _computerID;
public static String computerID() { try {
  if (_computerID == null) {
    File file = new File(userHome(), ".tinybrain/computer-id");
    _computerID = loadTextFile(file.getPath(), null);
    if (_computerID == null) {
      _computerID = makeRandomID(12);
      saveTextFile(file.getPath(), _computerID);
    }
  }
  return _computerID;
} catch (Exception __e) { throw rethrow(__e); } }
static boolean isInteger(String s) {
  if (s == null) return false;
  int n = l(s);
  if (n == 0) return false;
  int i = 0;
  if (s.charAt(0) == '-')
    if (++i >= n) return false;
  while (i < n) {
    char c = s.charAt(i);
    if (c < '0' || c > '9') return false;
    ++i;
  }
  return true;
}
static boolean jmatch(String pat, String s) {
  return jmatch(pat, s, null);
}

static boolean jmatch(String pat, String s, Matches matches) {
  if (s == null) return false;
  return jmatch(pat, javaTok(s), matches);
}

static boolean jmatch(String pat, List<String> toks) {
  return jmatch(pat, toks, null);
}

static boolean jmatch(String pat, List<String> toks, Matches matches) {
  List<String> tokpat = javaTok(pat);
  String[] m = match2(tokpat, toks);
  //print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m));
  if (m == null)
    return false;
  else {
    if (matches != null) matches.m = m;
    return true;
  }
}
static int[] toIntArray(List<Integer> l) {
  int[] a = new int[l(l)];
  for (int i = 0; i < a.length; i++)
    a[i] = l.get(i);
  return a;
}
static void printStructure(String prefix, Object o) {
  if (endsWithLetter(prefix)) prefix += ": ";
  print(prefix + structureForUser(o));
}

static void printStructure(Object o) {
  print(structureForUser(o));
}

// extended over Class.isInstance() to handle primitive types
static boolean isInstanceX(Class type, Object arg) {
  if (type == boolean.class) return arg instanceof Boolean;
  if (type == int.class) return arg instanceof Integer;
  if (type == long.class) return arg instanceof Long;
  if (type == float.class) return arg instanceof Float;
  if (type == short.class) return arg instanceof Short;
  if (type == char.class) return arg instanceof Character;
  if (type == byte.class) return arg instanceof Byte;
  if (type == double.class) return arg instanceof Double;
  return type.isInstance(arg);
}
static boolean eqOneOf(Object o, Object... l) {
  for (Object x : l) if (eq(o, x)) return true; return false;
}
static Producer<String> javaTokC_noMLS_iterator(final String s) {
  return new Producer<String>() {
    final int l = s.length();
    int i = 0;
    
    public String next() {
      if (i >= l) return null;
      
      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;
      }
      
      i = j;
      if (i >= l) return null;
      c = s.charAt(i);
      d = i+1 >= l ? '\0' : s.charAt(i+1);
  
      // scan for non-whitespace
      if (c == '\'' || c == '"') {
        char opener = c;
        ++j;
        while (j < l) {
          if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors
            ++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
        ++j;
        
      String t = quickSubstring(s, i, j);
      i = j;
      return t;
    }
  };
}

  static Object call(Object o) {
    return callFunction(o);
  }
  
  // varargs assignment fixer for a single string array argument
  static Object call(Object o, String method, String[] arg) {
    return call(o, method, new Object[] {arg});
  }
  
  static Object call(Object o, String method, Object... args) {
    try {
      if (o instanceof Class) {
        Method m = call_findStaticMethod((Class) o, method, args, false);
        m.setAccessible(true);
        return m.invoke(null, args);
      } else {
        Method m = call_findMethod(o, method, args, false);
        m.setAccessible(true);
        return m.invoke(o, args);
      }
    } catch (Exception e) {
      throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
    }
  }

  static Method call_findStaticMethod(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 || !call_checkArgs(m, args, debug))
          continue;

        return m;
      }
      c = c.getSuperclass();
    }
    throw new RuntimeException("Method '" + method + "' (static) with " + args.length + " parameter(s) not found in " + _c.getName());
  }

  static Method call_findMethod(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) && call_checkArgs(m, args, debug))
          return m;
      }
      c = c.getSuperclass();
    }
    throw new RuntimeException("Method '" + method + "' (non-static) with " + args.length + " parameter(s) not found in " + o.getClass().getName());
  }

  private 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 Object nuObject(String className, Object... args) { try {
  return nuObject(Class.forName(className), args);
} catch (Exception __e) { throw rethrow(__e); } }

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

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

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

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

static <A, B> Map<A, B> synchroMap(Map<A, B> map) {
  return Collections.synchronizedMap(map);
}
static File newFile(File base, String... names) {
  for (String name : names) base = new File(base, name);
  return base;
}

static File newFile(String name) {
  return name == null ? null : new File(name);
}
// usually L<S>
static String fromLines(Collection lines) {
  StringBuilder buf = new StringBuilder();
  if (lines != null)
    for (Object line : lines)
      buf.append(str(line)).append('\n');
  return buf.toString();
}

static String fromLines(String... lines) {
  return fromLines(asList(lines));
}
static 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 double parseDouble(String s) {
  return Double.parseDouble(s);
}
static List emptyList() {
  return new ArrayList();
  //ret Collections.emptyList();
}

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

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

static void sleepQuietly() { try {
  assertFalse(isAWTThread());
  synchronized(sleepQuietly_monitor) { sleepQuietly_monitor.wait(); }
} catch (Exception __e) { throw rethrow(__e); } }
static String shortClassName(Object o) {
  if (o == null) return null;
  Class c = o instanceof Class ? (Class) o : o.getClass();
  String name = c.getName();
  return shortenClassName(name);
}
static String unquote(String s) {
  if (s == null) return null;
  if (s.startsWith("[")) {
    int i = 1;
    while (i < s.length() && s.charAt(i) == '=') ++i;
    if (i < s.length() && s.charAt(i) == '[') {
      String m = s.substring(1, i);
      if (s.endsWith("]" + m + "]"))
        return s.substring(i+1, s.length()-i-1);
    }
  }
  
  if ((s.startsWith("\"") || s.startsWith("\'")) && s.length() > 1) {
    int l = s.endsWith(substring(s, 0, 1)) ? s.length()-1 : s.length();
    StringBuilder sb = new StringBuilder(l-1);

    for (int i = 1; i < l; i++) {
      char ch = s.charAt(i);
      if (ch == '\\') {
        char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
        // Octal escape?
        if (nextChar >= '0' && nextChar <= '7') {
            String code = "" + nextChar;
            i++;
            if ((i < l - 1) && s.charAt(i + 1) >= '0'
                    && s.charAt(i + 1) <= '7') {
                code += s.charAt(i + 1);
                i++;
                if ((i < l - 1) && s.charAt(i + 1) >= '0'
                        && s.charAt(i + 1) <= '7') {
                    code += s.charAt(i + 1);
                    i++;
                }
            }
            sb.append((char) Integer.parseInt(code, 8));
            continue;
        }
        switch (nextChar) {
        case '\\':
            ch = '\\';
            break;
        case 'b':
            ch = '\b';
            break;
        case 'f':
            ch = '\f';
            break;
        case 'n':
            ch = '\n';
            break;
        case 'r':
            ch = '\r';
            break;
        case 't':
            ch = '\t';
            break;
        case '\"':
            ch = '\"';
            break;
        case '\'':
            ch = '\'';
            break;
        // Hex Unicode: u????
        case 'u':
            if (i >= l - 5) {
                ch = 'u';
                break;
            }
            int code = Integer.parseInt(
                    "" + s.charAt(i + 2) + s.charAt(i + 3)
                       + s.charAt(i + 4) + s.charAt(i + 5), 16);
            sb.append(Character.toChars(code));
            i += 5;
            continue;
        default:
          ch = nextChar; // added by Stefan
        }
        i++;
      }
      sb.append(ch);
    }
    return sb.toString();   
  }
  
  return s; // not quoted - return original
}
static void setOptAll(Object o, Map<String, Object> fields) {
  if (fields == null) return;
  for (String field : keys(fields))
    setOpt(o, field, fields.get(field));
}

static void setOptAll(Object o, Object... values) {
  //values = expandParams(c.getClass(), values);
  warnIfOddCount(values);
  for (int i = 0; i+1 < l(values); i += 2) {
    String field = (String) values[i];
    Object value = values[i+1];
    setOpt(o, field, value);
  }
}
static boolean nempty(Collection c) {
  return !isEmpty(c);
}

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

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

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

static boolean nempty(Iterator i) {
  return i != null && i.hasNext();
}
static void revalidateFrame(Component c) {
  revalidate(getFrame(c));
}
static char unquoteCharacter(String s) {
  assertTrue(s.startsWith("'") && s.length() > 1);
  return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length()-1 : s.length()) + "\"").charAt(0);
}
static Producer<String> javaTokC_noMLS_onReader(final BufferedReader r) {
  final class X implements Producer<String> {
    StringBuilder buf = new StringBuilder(); // stores from "i"
    char c, d, e = 'x'; // just not '\0'
    
    X() {
      // fill c, d and e
      nc();
      nc();
      nc();
    }
    
    // get next character(s) into c, d and e
    void nc() { try {
      c = d;
      d = e;
      if (e == '\0') return;
      int i = r.read();
      e = i < 0 ? '\0' : (char) i;
    } catch (Exception __e) { throw rethrow(__e); } }
    
    void ncSave() {
      if (c != '\0') {
        buf.append(c);
        nc();
      }
    }
    
    public String next() {
      // scan for whitespace
      while (c != '\0') {
        if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
          nc();
        else if (c == '/' && d == '*') {
          do nc(); while (c != '\0' && !(c == '*' && d == '/'));
          nc(); nc();
        } else if (c == '/' && d == '/') {
          do nc(); while (c != '\0' && "\r\n".indexOf(c) < 0);
        } else
          break;
      }
      
      if (c == '\0') return null;

      // scan for non-whitespace
      if (c == '\'' || c == '"') {
        char opener = c;
        ncSave();
        while (c != '\0') {
          if (c == opener || c == '\n') { // end at \n to not propagate unclosed string literal errors
            ncSave();
            break;
          } else if (c == '\\') {
            ncSave();
            ncSave();
          } else
            ncSave();
        }
      } else if (Character.isJavaIdentifierStart(c))
        do ncSave(); while (Character.isJavaIdentifierPart(c) || c == '\''); // for stuff like "don't"
      else if (Character.isDigit(c)) {
        do ncSave(); while (Character.isDigit(c));
        if (c == 'L') ncSave(); // Long constants like 1L
      } else
        ncSave();
        
      String t = buf.toString();
      buf.setLength(0);
      return t;
    }
  }
  
  return new X();
}

static <A> A popLast(List<A> l) {
  return liftLast(l);
}
static <A> A nuStubInnerObject(Class<A> c) { try {
  Class outerType = getOuterClass(c);
  Constructor m = c.getDeclaredConstructor(outerType);
  m.setAccessible(true);
  return (A) m.newInstance(new Object[] {null});
} catch (Exception __e) { throw rethrow(__e); } }


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

static String struct(Object o, structure_Data data) {
  return structure(o, data);
}
static Object callFunction(Object f, Object... args) {
  return callF(f, args);
}
static Class getOuterClass(Class c) { try {
  String s = c.getName();
  int i = s.lastIndexOf('$');
  return Class.forName(substring(s, 0, i));
} catch (Exception __e) { throw rethrow(__e); } }
static String shortenClassName(String name) {
  if (name == null) return null;
  int i = lastIndexOf(name, "$");
  if (i < 0) i = lastIndexOf(name, ".");
  return i < 0 ? name : substring(name, i+1);
}
static String quickSubstring(String s, int i, int j) {
  if (i == j) return "";
  return s.substring(i, j);
}
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;
}
// replacement for class JavaTok
// maybe incomplete, might want to add floating point numbers
// todo also: extended multi-line strings

static int javaTok_n, javaTok_elements;
static boolean javaTok_opt;

static List<String> javaTok(String s) {
  return javaTok(s, null);
}

static List<String> javaTok(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 && javaTok_isCopyable(existing.get(n), s, i, j))
      tok.add(existing.get(n));
    else
      tok.add(quickSubstring(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 && javaTok_isCopyable(existing.get(n), s, i, j))
      tok.add(existing.get(n));
    else
      tok.add(quickSubstring(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 javaTok(join(tok), tok);
}

static boolean javaTok_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 String _userHome;
static String userHome() {
  if (_userHome == null) {
    if (isAndroid())
      _userHome = "/storage/sdcard0/";
    else
      _userHome = System.getProperty("user.home");
    //System.out.println("userHome: " + _userHome);
  }
  return _userHome;
}

static File userHome(String path) {
  return new File(userDir(), path);
}
static int min(int a, int b) {
  return Math.min(a, b);
}

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

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

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

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

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

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

static short min(short[] c) {
  short x = 0x7FFF;
  for (short d : c) if (d < x) x = d;
  return x;
}
static <A> ArrayList<A> litlist(A... a) {
  return new ArrayList<A>(Arrays.asList(a));
}
static List<Class> getClasses(Object[] array) {
  List<Class> l = new ArrayList();
  for (Object o : array) l.add(_getClass(o));
  return l;
}
static boolean endsWithLetter(String s) {
  return nempty(s) && isLetter(last(s));
}
static Class getMainClass() {
  return main.class;
}

static Class getMainClass(Object o) { try {
  return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) { throw rethrow(__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 <A> A assertEquals(Object x, A y) {
  return assertEquals(null, x, y);
}

static <A> A assertEquals(String msg, Object x, A y) {
  if (!(x == null ? y == null : x.equals(y)))
    throw fail((msg != null ? msg + ": " : "") + y + " != " + x);
  return y;
}
static boolean hasField(Object o, String field) {
  return findField2(o, field) != null;
}
// match2 matches multiple "*" (matches a single token) wildcards and zero or one "..." wildcards (matches multiple tokens)

static String[] match2(List<String> pat, List<String> tok) {
  // standard case (no ...)
  int i = pat.indexOf("...");
  if (i < 0) return match2_match(pat, tok);
  
  pat = new ArrayList<String>(pat); // We're modifying it, so copy first
  pat.set(i, "*");
  while (pat.size() < tok.size()) {
    pat.add(i, "*");
    pat.add(i+1, ""); // doesn't matter
  }
  
  return match2_match(pat, tok);
}

static String[] match2_match(List<String> pat, List<String> tok) {
  List<String> result = new ArrayList<String>();
  if (pat.size() != tok.size()) {
    
    return null;
  }
  for (int i = 1; i < pat.size(); i += 2) {
    String p = pat.get(i), t = tok.get(i);
    
    if (eq(p, "*"))
      result.add(t);
    else if (!equalsIgnoreCase(unquote(p), unquote(t))) // bold change - match quoted and unquoted now
      return null;
  }
  return result.toArray(new String[result.size()]);
}

static Boolean isHeadless_cache;

static boolean isHeadless() {
  if (isHeadless_cache != null) return isHeadless_cache;
  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 WeakHashMap<Class, HashMap<String, Method>> callOpt_noArgs_cache = new WeakHashMap();

static Object callOpt_noArgs(Object o, String method) { try {
  if (o == null) return null;
  if (o instanceof Class)
    return callOpt(o, method); // not optimized
  
  Class c = o.getClass();
  HashMap<String, Method> map;
  synchronized(callOpt_noArgs_cache) {
    map = callOpt_noArgs_cache.get(c);
    if (map == null)
      map = callOpt_noArgs_makeCache(c);
  }

  Method m = map.get(method);
  return m != null ? m.invoke(o) : null;
} catch (Exception __e) { throw rethrow(__e); } }

// used internally - we are in synchronized block
static HashMap<String, Method> callOpt_noArgs_makeCache(Class c) {
  HashMap<String,Method> map = new HashMap();
  Class _c = c;
  do {
    for (Method m : c.getDeclaredMethods())
      if (m.getParameterTypes().length == 0) {
        m.setAccessible(true);
        String name = m.getName();
        if (!map.containsKey(name))
          map.put(name, m);
      }
    _c = _c.getSuperclass();
  } while (_c != null);
  callOpt_noArgs_cache.put(c, map);
  return map;
}
static Class mc() {
  return main.class;
}
static File programDir_mine; // set this to relocate program's data

static File programDir() {
  return programDir(getProgramID());
}

static File programDir(String snippetID) {
  boolean me = sameSnippetID(snippetID, programID());
  if (programDir_mine != null && me)
    return programDir_mine;
  File dir = new File(javaxDataDir(), formatSnippetID(snippetID));
  if (me) {
    String c = caseID();
    if (nempty(c)) dir = newFile(dir, c);
  }
  return dir;
}

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 String formatSnippetID(String id) {
  return "#" + parseSnippetID(id);
}

static String formatSnippetID(long id) {
  return "#" + id;
}
static int systemHashCode(Object o) {
  return identityHashCode(o);
}
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.repa..."; }}); }
}
/** writes safely (to temp file, then rename) */
static File saveTextFile(String fileName, String contents) throws IOException {
  CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
  try {
    File file = new File(fileName);
    File parentFile = file.getParentFile();
    if (parentFile != null)
      parentFile.mkdirs();
    String tempFileName = fileName + "_temp";
    File tempFile = new File(tempFileName);
    if (contents != null) {
      if (tempFile.exists()) try {
        String saveName = tempFileName + ".saved." + now();
        copyFile(tempFile, new File(saveName));
      } catch (Throwable e) { printStackTrace(e); }
      FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
      OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
      PrintWriter printWriter = new PrintWriter(outputStreamWriter);
      printWriter.print(contents);
      printWriter.close();
    }
    
    if (file.exists() && !file.delete())
      throw new IOException("Can't delete " + fileName);
  
    if (contents != null)
      if (!tempFile.renameTo(file))
        throw new IOException("Can't rename " + tempFile + " to " + file);
        
    return file;
  } finally {
    action.done();
  }
}

static File saveTextFile(File fileName, String contents) { try {
  saveTextFile(fileName.getPath(), contents);
  return fileName;
} catch (Exception __e) { throw rethrow(__e); } }
static void assertFalse(Object o) {
  assertEquals(false, 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 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((ButtonGro..."; }});
}
static void warnIfOddCount(Object... list) {
  if (odd(l(list)))
    printStackTrace("Odd list size: " + list);
}
static String structureForUser(Object o) {
  return beautifyStructure(struct_noStringSharing(o));
}
static String formatSnippetIDOpt(String s) {
  return isSnippetID(s) ? formatSnippetID(s) : s;
}
static String makeRandomID(int length) {
  Random random = new Random();
  char[] id = new char[length];
  for (int i = 0; i < id.length; i++)
    id[i] = (char) ((int) 'a' + random.nextInt(26));
  return new String(id);
}
static boolean isEmpty(Collection c) {
  return c == null || c.isEmpty();
}

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

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

static boolean isEmpty(Map map) {
  return map == null || map.isEmpty();
}
static int parseHexByte(String s) {
  return Integer.parseInt(s, 16);
}
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;
  
  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() & Modifier.STATIC) != 0)
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  return null;
}
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);
  }
}

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() & Modifier.STATIC) != 0)
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  return null;
}

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 void printStackTrace2(S indent, Throwable e) {
  if (endsWithLetter(indent)) indent += " ";
  printIndent(indent, getStackTrace2(e));
}*/
static Map synchroHashMap() {
  return Collections.synchronizedMap(new HashMap());
}

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 List<CriticalAction> beginCriticalAction_inFlight = synchroList();

static class CriticalAction {
  String description;
  
  CriticalAction() {}
  CriticalAction(String description) {
  this.description = description;}
  
  void done() {
    beginCriticalAction_inFlight.remove(this);
  }
}

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

static void cleanMeUp_beginCriticalAction() {
  int n = 0;
  while (nempty(beginCriticalAction_inFlight)) {
    int m = l(beginCriticalAction_inFlight);
    if (m != n) {
      n = m;
      try {
        print("Waiting for " + n(n, "critical actions") + ": " + join(", ", collect(beginCriticalAction_inFlight, "description")));
      } catch (Throwable __e) { printStackTrace2(__e); }
    }
    sleepInCleanUp(10);
  }
}
static boolean equalsIgnoreCase(String a, String b) {
  return a == null ? b == null : a.equalsIgnoreCase(b);
}

static boolean equalsIgnoreCase(char a, char b) {
  if (a == b) return true;
  char u1 = Character.toUpperCase(a);
  char u2 = Character.toUpperCase(b);
  if (u1 == u2) return true;
  return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static 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 void printStackTrace(S indent, Throwable e) {
  if (endsWithLetter(indent)) indent += " ";
  printIndent(indent, getStackTrace(e));
}*/
static volatile String caseID_caseID;

static String caseID() { return caseID_caseID; }

static void caseID(String id) {
  caseID_caseID = id;
}
static List<AbstractButton> buttonsInGroup(ButtonGroup g) {
  if (g == null) return ll();
  return asList(g.getElements());
}
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 (Exception __e) { throw rethrow(__e); } }
static <A> A last(List<A> l) {
  return l.isEmpty() ? null : l.get(l.size()-1);
}

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

static int last(int[] a) {
  return l(a) != 0 ? a[l(a)-1] : 0;
}
static String beautifyStructure(String s) {
  return structure_addTokenMarkers(s);
}
static long now_virtualTime;
static long now() {
  return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}

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

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

static FileOutputStream newFileOutputStream(String path, boolean append) throws IOException {
  FileOutputStream f = new // Line break for ancient translator
    FileOutputStream(path, append);
  callJavaX("registerIO", f, path, true);
  return f;
}
static String programID() {
  return getProgramID();
}
static int lastIndexOf(String a, String b) {
  return a == null || b == null ? -1 : a.lastIndexOf(b);
}
static Field findField2(Object o, String field) {
  if (o instanceof Class) return findField2_findStaticField((Class) o, field);
  return findField2_findField(o.getClass(), field);
}

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

static Field findField2_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 String struct_noStringSharing(Object o) {
  structure_Data d = new structure_Data();
  d.noStringSharing = true;
  return structure(o, d);
}
static int identityHashCode(Object o) {
  return System.identityHashCode(o);
}
static void setOpt_raw(Object o, String field, Object value) {
  if (o == null) return;
  if (o instanceof Class) setOpt_raw((Class) o, field, value);
  else try {
    Field f = setOpt_raw_findField(o.getClass(), field);
    if (f != null)
      smartSet(f, o, value);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

static void setOpt_raw(Class c, String field, Object value) {
  if (c == null) return;
  try {
    Field f = setOpt_raw_findStaticField(c, field);
    if (f != null)
      smartSet(f, null, value);
  } catch (Exception e) {
    throw new RuntimeException(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() & 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;
}
public static String join(String glue, Iterable<String> strings) {
  if (strings == null) return "";
  StringBuilder buf = new StringBuilder();
  Iterator<String> 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 String join(Iterable<String> strings) {
  return join("", strings);
}

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

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

static String getStackTrace2(Throwable throwable) {
  return getStackTrace(throwable) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ",
    str(getInnerException(throwable))) + "\n";
}
static boolean odd(int i) {
  return (i & 1) != 0;
}

static boolean odd(long i) {
  return (i & 1) != 0;
}
public static void copyFile(File src, File dest) { try {
  mkdirsForFile(dest);
  FileInputStream inputStream = new FileInputStream(src.getPath());
  FileOutputStream outputStream = newFileOutputStream(dest.getPath());
  try {
    copyStream(inputStream, outputStream);
    inputStream.close();
  } finally {
    outputStream.close();
  }
} catch (Exception __e) { throw rethrow(__e); } }
  public static boolean isSnippetID(String s) {
    try {
      parseSnippetID(s);
      return true;
    } catch (RuntimeException e) {
      return false;
    }
  }
static boolean sameSnippetID(String a, String b) {
  return a != null && b != null && parseSnippetID(a) == parseSnippetID(b);
}
static File javaxDataDir_dir; // can be set to work on different base dir

static File javaxDataDir() {
  return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
}
static boolean isLetter(char c) {
  return Character.isLetter(c);
}
static final WeakHashMap<Class, HashMap<String, Field>> getOpt_cache = new WeakHashMap();
static final HashMap getOpt_special = new HashMap(); // just a marker

static {
  getOpt_cache.put(Class.class, getOpt_special);
  getOpt_cache.put(String.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);
  
    if (o instanceof DynamicObject)
      return ((DynamicObject) o).fieldValues.get(field);
  
  return null;
} catch (Exception __e) { throw rethrow(__e); } }

// used internally - we are in synchronized block
static HashMap<String, Field> getOpt_makeCache(Class c) {
  HashMap<String, Field> map;
  if (isSubtypeOf(c, Map.class))
    map = getOpt_special;
  else {
    map = new HashMap();
    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);
  }
  getOpt_cache.put(c, map);
  return map;
}
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 void smartSet(Field f, Object o, Object value) throws Exception {
  f.setAccessible(true);
  
  // take care of common case (long to int)
  if (f.getType() == int.class && value instanceof Long)
    value = ((Long) value).intValue();
    
  try {
    f.set(o, value);
  } catch (Exception e) {
    
    throw e;
  }
}
static boolean structure_showTiming, structure_checkTokenCount;

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

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

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

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

// leave to false, unless unstructure() breaks
static boolean structure_allowShortening = false;

static class structure_Data {
  PrintWriter out;
  int stringSizeLimit;
  int shareStringsLongerThan = 20;
  boolean noStringSharing;

  IdentityHashMap<Object,Integer> seen = new IdentityHashMap();
  //new BitSet refd;
  HashMap<String,Integer> strings = new HashMap();
  HashSet<String> concepts = new HashSet();
  HashMap<Class, List<Field>> fieldsByClass = new HashMap();
  int n; // token count
  List<Runnable> stack = new ArrayList();
  
  // append single token
  structure_Data append(String token) { out.print(token); ++n; return this; }
  structure_Data append(int i) { out.print(i); ++n; return this; }
  
  // append multiple tokens
  structure_Data append(String token, int tokCount) { out.print(token); n += tokCount; return this; }
  
  // extend last token
  structure_Data app(String token) { out.print(token); return this; }
  structure_Data app(int i) { out.print(i); return this; }
}

static void structure_1(final Object o, final structure_Data d) {
  if (o == null) { d.append("null"); return; }
  
  Class c = o.getClass();
  boolean concept = false;
  
  List<Field> lFields = d.fieldsByClass.get(c);
  
  if (lFields == null) {
    // these are never back-referenced (for readability)
    
    if (o instanceof Number) {
      PrintWriter out = d.out;
if (o instanceof Integer) { int i = ((Integer) o).intValue(); out.print(i); d.n += i < 0 ? 2 : 1; return; }
      if (o instanceof Long) { long l = ((Long) o).longValue(); out.print(l); out.print("L"); d.n += l < 0 ? 2 : 1; return; }
      if (o instanceof Float) { d.append("fl ", 2); quoteToPrintWriter(str(o), out); return; }
      if (o instanceof Double) { d.append("d(", 3); quoteToPrintWriter(str(o), out); d.append(")"); return; }
      if (o instanceof BigInteger) { out.print("bigint("); out.print(o); out.print(")"); d.n += ((BigInteger) o).signum() < 0 ? 5 : 4; return; }
    }
  
    if (o instanceof Boolean) {
      d.append(((Boolean) o).booleanValue() ? "t" : "f"); return;
    }
      
    if (o instanceof Character) {
      d.append(quoteCharacter((Character) o)); return;
    }
      
    if (o instanceof File) {
      d.append("File ").append(quote(((File) o).getPath())); return;
    }
      
    // referencable objects follow
    
    Integer ref = d.seen.get(o);
    if (o instanceof String && ref == null) ref = d.strings.get((String) o);
    if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); return; }

    if (!(o instanceof String))
      d.seen.put(o, d.n); // record token number
    else {
      String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o;
      if (!d.noStringSharing) {
        if (d.shareStringsLongerThan == Integer.MAX_VALUE)
          d.seen.put(o, d.n);
        if (l(s) >= d.shareStringsLongerThan)
          d.strings.put(s, d.n);
      }
      quoteToPrintWriter(s, d.out); d.n++; return;
    }
      
    if (o instanceof HashSet) {
      d.append("hashset ");
      structure_1(new ArrayList((Set) o), d);
      return;
    }
  
    if (o instanceof TreeSet) {
      d.append("treeset ");
      structure_1(new ArrayList((Set) o), d);
      return;
    }
    
    String name = c.getName();
    if (o instanceof Collection
      && !startsWith(name, "main$")
      /* && neq(name, "main$Concept$RefL") */) {
      d.append("[");
      final int l = d.n;
      final Iterator it = ((Collection) o).iterator();
      d.stack.add(new Runnable() { public void run() { try { 
        if (!it.hasNext())
          d.append("]");
        else {
          d.stack.add(this);
          if (d.n != l) d.append(", ");
          structure_1(it.next(), d);
        }
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (!it.hasNext())\r\n          d.append(\"]\");\r\n        else {\r\n          d.stack...."; }});
      return;
    }
    
    if (o instanceof Map && !startsWith(name, "main$")) {
      if (o instanceof LinkedHashMap) d.append("lhm");
      else if (o instanceof HashMap) d.append("hm");
      d.append("{");
      final int l = d.n;
      final Iterator it = ((Map) o).entrySet().iterator();
      
      d.stack.add(new Runnable() {
        boolean v;
        Map.Entry e;
        
        public void run() {
          if (v) {
            d.append("=");
            v = false;
            d.stack.add(this);
            structure_1(e.getValue(), d);
          } else {
            if (!it.hasNext())
              d.append("}");
            else {
              e = (Map.Entry) it.next();
              v = true;
              d.stack.add(this);
              if (d.n != l) d.append(", ");
              structure_1(e.getKey(), d);
            }
          }
        }
      });
      return;
    }
    
    if (c.isArray()) {
      if (o instanceof byte[]) {
        d.append("ba ").append(quote(bytesToHex((byte[]) o))); return;
      }
  
      final int n = Array.getLength(o);
  
      if (o instanceof boolean[]) {
        String hex = boolArrayToHex((boolean[]) o);
        int i = l(hex);
        while (i > 0 && hex.charAt(i-1) == '0' && hex.charAt(i-2) == '0') i -= 2;
        d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i))); return;
      }
      
      String atype = "array", sep = ", ";
  
      if (o instanceof int[]) {
        //ret "intarray " + quote(intArrayToHex((int[]) o));
        atype = "intarray";
        sep = " ";
      }
      
      d.append(atype).append("{");
      d.stack.add(new Runnable() {
        int i;
        public void run() {
          if (i >= n)
            d.append("}");
          else {
            d.stack.add(this);
            if (i > 0) d.append(", ");
            structure_1(Array.get(o, i++), d);
          }
        }
      });
      return;
    }
  
    if (o instanceof Class) {
      d.append("class(", 2).append(quote(((Class) o).getName())).append(")"); return;
    }
      
    if (o instanceof Throwable) {
      d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")"); return;
    }
      
    if (o instanceof BitSet) {
      BitSet bs = (BitSet) o;
      d.append("bitset{", 2);
      int l = d.n;
      for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
        if (d.n != l) d.append(", ");
        d.append(i);
      }
      d.append("}"); return;
    }
      
    // Need more cases? This should cover all library classes...
    if (name.startsWith("java.") || name.startsWith("javax.")) {
      d.append("j ").append(quote(str(o))); return; // Hm. this is not unstructure-able
    }
    
    
      
    /*if (name.equals("main$Lisp")) {
      fail("lisp not supported right now");
    }*/
    
    String dynName = shortDynamicClassName(o);
    if (concept && !d.concepts.contains(dynName)) {
      d.concepts.add(dynName);
      d.append("c ");
    }
    
    // serialize an object with fields.
    // first, collect all fields and values in fv.
    
    TreeSet<Field> fields = new TreeSet<Field>(new Comparator<Field>() {
      public int compare(Field a, Field b) {
        return stdcompare(a.getName(), b.getName());
      }
    });
    
    Class cc = c;
    while (cc != Object.class) {
      for (Field field : getDeclaredFields_cached(cc)) {
        if ((field.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) != 0)
          continue;
        String fieldName = field.getName();
        
        fields.add(field);
        
        // put special cases here...
      }
        
      cc = cc.getSuperclass();
    }
    
    lFields = asList(fields);
    
    // Render this$1 first because unstructure needs it for constructor call.
    
    for (int i = 0; i < l(lFields); i++) {
      Field f = lFields.get(i);
      if (f.getName().equals("this$1")) {
        lFields.remove(i);
        lFields.add(0, f);
        break;
      }
    }
  
    
    d.fieldsByClass.put(c, lFields);
  } // << if (lFields == null)
  else { // ref handling for lFields != null
    Integer ref = d.seen.get(o);
    if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); return; }
    d.seen.put(o, d.n); // record token number
  }

  LinkedHashMap<String,Object> fv = new LinkedHashMap();
  for (Field f : lFields) {
    Object value;
    try {
      value = f.get(o);
    } catch (Exception e) {
      value = "?";
    }
      
    if (value != null)
      fv.put(f.getName(), value);
    
  }
  
  String name = c.getName();
  String shortName = dropPrefix("main$", name);
    
  // Now we have fields & values. Process fieldValues if it's a DynamicObject.
  
  // omit field "className" if equal to class's name
  if (concept && eq(fv.get("className"), shortName))
    fv.remove("className");
          
  if (o instanceof DynamicObject) {
    fv.putAll((Map) fv.get("fieldValues"));
    fv.remove("fieldValues");
    shortName = shortDynamicClassName(o);
    fv.remove("className");
  }
  
  String singleField = fv.size() == 1 ? first(fv.keySet()) : null;
  
  d.append(shortName);
  
  
  final int l = d.n;
  final Iterator it = fv.entrySet().iterator();
  
  d.stack.add(new Runnable() { public void run() { try { 
    if (!it.hasNext()) {
      if (d.n != l)
        d.append(")");
    } else {
      Map.Entry e = (Map.Entry) it.next();
      d.append(d.n == l ? "(" : ", ");
      d.append((String) e.getKey()).append("=");
      d.stack.add(this);
      structure_1(e.getValue(), d);
    }
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (!it.hasNext()) {\r\n      if (d.n != l)\r\n        d.append(\")\");\r\n    } else {\r..."; }});
}

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

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


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

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 String shortDynamicClassName(Object o) {
 if (o instanceof DynamicObject && ((DynamicObject) o).className != null)
    return ((DynamicObject) o).className;
  return shortClassName(o);
}
static String replacePrefix(String prefix, String replacement, String s) {
  if (!startsWith(s, prefix)) return s;
  return replacement + substring(s, l(prefix));
}
static String n(long l, String name) {
  return l + " " + trim(l == 1 ? singular(name) : getPlural(name));
}

static String n(Collection l, String name) {
  return n(l(l), name);
}

static String n(Map m, String name) {
  return n(l(m), name);
}

static String n(Object[] a, String name) {
  return n(l(a), name);
}


static HashMap<Class, Field[]> getDeclaredFields_cache = new HashMap();

static Field[] getDeclaredFields_cached(Class c) {
  Field[] fields;
  synchronized(getDeclaredFields_cache) {
    fields = getDeclaredFields_cache.get(c);
    if (fields == null) {
      getDeclaredFields_cache.put(c, fields = c.getDeclaredFields());
      for (Field f : fields)
        f.setAccessible(true);
    }
  }
  return fields;
}
static String boolArrayToHex(boolean[] a) {
  return bytesToHex(boolArrayToBytes(a));
}
  public static String bytesToHex(byte[] bytes) {
    return bytesToHex(bytes, 0, bytes.length);
  }

  public static String bytesToHex(byte[] bytes, int ofs, int len) {
    StringBuilder stringBuilder = new StringBuilder(len*2);
    for (int i = 0; i < len; i++) {
      String s = "0" + Integer.toHexString(bytes[ofs+i]);
      stringBuilder.append(s.substring(s.length()-2, s.length()));
    }
    return stringBuilder.toString();
  }

static String getStackTrace(Throwable throwable) {
  StringWriter writer = new StringWriter();
  throwable.printStackTrace(new PrintWriter(writer));
  return writer.toString();
}
static String structure_addTokenMarkers(String s) {
  List<String> tok = javaTok(s);
  
  // find references
  
  TreeSet<Integer> refs = new TreeSet();
  for (int i = 1; i < l(tok); i += 2) {
    String t = tok.get(i);
    if (t.startsWith("t") && isInteger(t.substring(1)))
      refs.add(parseInt(t.substring(1)));
  }
  
  if (empty(refs)) return s;
  
  // add markers
  for (int i : refs) {
    int idx = i*2+1;
    String t = "";
    if (endsWithLetterOrDigit(tok.get(idx-1))) t = " ";
    tok.set(idx, t + "m" + i + " " + tok.get(idx));
  }
  
  return join(tok);
}
static String classNameToVM(String name) {
  return name.replace(".", "$");
}
public static File mkdirsForFile(File file) {
  File dir = file.getParentFile();
  if (dir != null) // is null if file is in current dir
    dir.mkdirs();
  return file;
}

static Object callJavaX(String method, Object... args) {
  return callOpt(getJavaX(), method, args);
}
static <A> List<A> synchroList() {
  return Collections.synchronizedList(new ArrayList<A>());
}

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

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

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

static String shorten(String s, int max) {
  if (s == null) return "";
  if (max < 0) return s;
  return s.length() <= max ? s : s.substring(0, Math.min(s.length(), max)) + "...";
}

static String shorten(int max, String s) { return shorten(s, max); }
static void sleepInCleanUp(long ms) { try {
  if (ms < 0) return;
  Thread.sleep(ms);
} catch (Exception __e) { throw rethrow(__e); } }
static boolean isSubtypeOf(Class a, Class b) {
  return b.isAssignableFrom(a); // << always hated that method, let's replace it!
}
static List<String> javaTokC(String s) {
  int l = s.length();
  ArrayList<String> tok = new ArrayList();
  
  int i = 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;
    }
    
    i = j;
    if (i >= l) break;
    c = s.charAt(i);
    d = i+1 >= l ? '\0' : s.charAt(i+1);

    // scan for non-whitespace
    if (c == '\'' || c == '"') {
      char opener = c;
      ++j;
      while (j < l) {
        if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors
          ++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;
      
    tok.add(quickSubstring(s, i, j));
    i = j;
  }
  
  return tok;
}

static <A> List<A> ll(A... a) {
  return litlist(a);
}
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 void quoteToPrintWriter(String s, PrintWriter out) {
  if (s == null) { out.print("null"); return; }
  out.print('"');
  int l = s.length();
  for (int i = 0; i < l; i++) {
    char c = s.charAt(i);
    if (c == '\\' || c == '"') {
      out.print('\\'); out.print(c);
    } else if (c == '\r')
      out.print("\\r");
    else if (c == '\n')
      out.print("\\n");
    else
      out.print(c);
  }
  out.print('"');
}
static List collect(Collection c, String field) {
  return collectField(c, field);
}

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


static int stdcompare(Number a, Number b) {
  return cmp(a, b);
}

static int stdcompare(String a, String b) {
  return cmp(a, b);
}

static int stdcompare(long a, long b) {
  return a < b ? -1 : a > b ? 1 : 0;
}

static int stdcompare(Object a, Object b) {
  return cmp(a, b);
}

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


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


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 List<String> getPlural_specials = ll("sheep", "fish");

static String getPlural(String s) {
  if (containsIgnoreCase(getPlural_specials, s)) return s;
  if (ewic(s, "y")) return dropSuffixIgnoreCase("y", s) + "ies";
  if (ewic(s, "ss")) return s + "es";
  if (ewic(s, "s")) return s;
  return s + "s";
}
static Map<String, String> singular_specials = litmap(
  "children", "child", "images", "image", "chess", "chess");
  
static Set<String> singular_specials2 = litset("time", "machine");

static String singular(String s) {
  if (s == null) return null;
  { String _a_691 = singular_specials.get(s); if (!empty(_a_691)) return _a_691; }
  if (singular_specials2.contains(dropSuffix("s", s)))
    return dropSuffix("s", s);
  if (s.endsWith("ness")) return s;
  if (s.endsWith("ges")) return dropSuffix("s", s);
  s = dropSuffix("es", s);
  s = dropSuffix("s", s);
  return s;
}
static List collectField(Collection c, String field) {
  List l = new ArrayList();
  for (Object a : c)
    l.add(getOpt(a, field));
  return l;
}
static <A> ArrayList<A> list(A[] a) {
  return asList(a);
}

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

static <A> ArrayList<A> list(Set<A> s) {
  return asList(s);
}
static byte[] boolArrayToBytes(boolean[] a) {
  byte[] b = new byte[(l(a)+7)/8];
  for (int i = 0; i < l(a); i++)
    if (a[i])
      b[i/8] |= 1 << (i & 7);
  return b;
}
static int cmp(Number a, Number b) {
  return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue());
}

static int cmp(double a, double b) {
  return a < b ? -1 : a == b ? 0 : 1;
}

static int cmp(String a, String b) {
  return a == null ? b == null ? 0 : -1 : a.compareTo(b);
}

static int cmp(Object a, Object b) {
  if (a == null) return b == null ? 0 : -1;
  if (b == null) return 1;
  return ((Comparable) a).compareTo(b);
}
static boolean endsWithLetterOrDigit(String s) {
  return nempty(s) && isLetterOrDigit(lastCharacter(s));
}
static boolean neq(Object a, Object b) {
  return !eq(a, b);
}


static <A> HashSet<A> litset(A... items) {
  return lithashset(items);
}
static String dropSuffixIgnoreCase(String suffix, String s) {
  return ewic(s, suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static boolean containsIgnoreCase(List<String> l, String s) {
  for (String x : l)
    if (eqic(x, s))
      return true;
  return false;
}

static boolean containsIgnoreCase(String[] l, String s) {
  for (String x : l)
    if (eqic(x, s))
      return true;
  return false;
}

static boolean containsIgnoreCase(String s, char c) {
  return indexOfIgnoreCase(s, String.valueOf(c)) >= 0;
}

static boolean containsIgnoreCase(String a, String b) {
  return indexOfIgnoreCase(a, b) >= 0;
}
static boolean ewic(String a, String b) {
  return endsWithIgnoreCase(a, b);
}
static char lastCharacter(String s) {
  return empty(s) ? 0 : s.charAt(l(s)-1);
}
static boolean isLetterOrDigit(char c) {
  return Character.isLetterOrDigit(c);
}


static <A> HashSet<A> lithashset(A... items) {
  HashSet<A> set = new HashSet();
  for (A a : items) set.add(a);
  return set;
}
static boolean eqic(String a, String b) {
  if ((a == null) != (b == null)) return false;
  if (a == null) return true;
  return a.equalsIgnoreCase(b);
}
static boolean endsWithIgnoreCase(String a, String b) {
  return a != null && l(a) >= l(b) && a.regionMatches(true, l(a)-l(b), b, 0, l(b));
}
// works on lists and strings and null

static int indexOfIgnoreCase(Object a, Object b) {
  if (a == null) return -1;
  if (a instanceof String) {
     Matcher m = Pattern.compile((String) b, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher((String) a);
     if (m.find()) return m.start(); else return -1;
  }
  if (a instanceof List) {
    for (int i = 0; i < ((List) a).size(); i++) {
      Object o = ((List) a).get(i);
      if (o != null && ((String) o).equalsIgnoreCase((String) b))
        return i;
    }
    return -1;
  }
  throw fail("Unknown type: " + a);
}


static abstract class F0<A> {
  abstract A get();
}

static abstract class F1<A, B> {
  abstract B get(A a);
}

static class BaseBase {
  String text;
  String textForRender() { return text; }
}

static boolean traits_multiLine = true;

static class Base extends BaseBase {
  List<String> traits = new ArrayList();
  boolean hasTrait(String t) { return containsIC(traits(), t); }
  List<String> traits() { if (nempty(text) && neq(first(traits), text)) traits.add(0, text); return traits; }
  void addTraits(List<String> l) { setAddAll(traits(), l); }
  void addTrait(String t) { if (nempty(t)) setAdd(traits(), t); }
  
  String textForRender() {
    List<String> traits = traits();
    if (traits_multiLine) return lines(traits);
    if (l(traits) <= 1) return first(traits);
    return first(traits) + " [" + join(", ", dropFirst(traits)) + "]";
  }
  
  void setText(String text) {
    this.text = text;
    traits = ll(text);
  }
}

static class CirclesAndLines {
  List<Circle> circles = new ArrayList();
  List<Line> lines = new ArrayList();
  Class<? extends Arrow> arrowClass = Arrow.class;
  Class<? extends Circle> circleClass = Circle.class;
  String title;
  transient Lock lock = fairLock();
  transient String defaultImageID = "#1007372";
  transient double imgZoom = 1;
  transient Pt translate;
  Circle hoverCircle; // which one we are hovering over
  transient Object onUserMadeArrow, onUserMadeCircle, onLayoutChange;
  transient Object onFullLayoutChange, onDeleteCircle, onDeleteLine;
  transient Object onRenameCircle, onRenameLine, onStructureChange;
  transient BufferedImage imageForUserMadeNodes;
  static int maxDistanceToLine = 20; // for clicking
  transient String backgroundImageID = defaultBackgroundImageID;
  static String defaultBackgroundImageID = "#1007195";
  static Color defaultLineColor = Color.white;
  static boolean debugRender;

  // auto-visualize
  Circle circle_autoVis(String text, String visualizationText, double x, double y) {
    return addAndReturn(circles,
      nu(circleClass, "x", x, "y", y, "text", text,
        "quickvis" , visualizationText,
        "img" , processImage(quickVisualizeOr(visualizationText, defaultImageID))));
  }
  
  String makeVisualizationText(String text) {
    return possibleGlobalID(text) ? "" : text;
  }

  Circle circle_autoVis(String text, double x, double y) {
    return circle_autoVis(text, makeVisualizationText(text), x, y);
  }
  
  Circle circle(BufferedImage img, double x, double y, String text) {
    return addAndReturn(circles, nu(circleClass, "x", x, "y", y, "text", text, "img" , processImage(img)));
  }
  
  Circle circle(String text, BufferedImage img, double x, double y) {
    return circle(img, x, y, text);
  }
  
  Circle circle(String text, double x, double y) {
    return addAndReturn(circles, nu(circleClass, "x", x, "y", y, "text", text, "img" , processImage(imageForUserMadeNodes())));
  }
  
  Circle addCircle(String imageID, double x, double y) {
    return addCircle(imageID, x, y, "");
  }
  
  Circle addCircle(String imageID, double x, double y, String text) {
    return addAndReturn(circles, nu(circleClass, "x", x, "y", y, "text", text, "img" , processImage(loadImage2(imageID))));
  }
  
  Arrow findArrow(Circle a, Circle b) {
    for (Line l : getWhere(lines, "a", a, "b", b))
      if (l instanceof Arrow)
        return (Arrow) l;
    return null;
  }
  
  Line addLine(Circle a, Circle b) {
    Line line = findWhere(lines, "a", a, "b", b);
    if (line == null)
      lines.add(line = nu(Line.class, "a", a, "b", b));
    return line;
  }
  
  Arrow arrow(Circle a, String text, Circle b) {
    return addArrow(a, b, text);
  }
  
  Arrow addArrow(Circle a, Circle b) {
    return addArrow(a, b, "");
  }
  
  Arrow addArrow(Circle a, Circle b, String text) {
    return addAndReturn(lines, nu(arrowClass, "a", a, "b", b, "text", text));
  }
  
  BufferedImage makeImage(int w, int h) {
    BufferedImage bg = renderTiledBackground(backgroundImageID, w, h, ptX(translate), ptY(translate));
    if (!lock.tryLock()) return null;
    try {
      // Lines
      
      if (debugRender)
        print("Have " + n(lines, "line"));
      
      HashMap<Pair<Circle, Circle>, Line> hasLine = new HashMap();
      HashMap<Line,Boolean> flipMap = new HashMap();
      for (Line l : lines) {
        hasLine.put(pair(l.a, l.b), l);
        Line x = hasLine.get(pair(l.b, l.a));
        if (x != null) {
          if (debugRender)
            print("flipMap " + l.a.text + " / " + l.b.text);
          flipMap.put(x, false);
          flipMap.put(l, false);
        }
      }

      for (Line l : lines) {
        DoublePt a = translateDoublePt(translate, l.a.doublePt(w, h));
        DoublePt b = translateDoublePt(translate, l.b.doublePt(w, h));
        if (debugRender)
          print("Line " + a + " " + b);
        if (l instanceof Arrow)
          drawThoughtArrow(bg, l.a.img(this), iround(a.x), iround(a.y), l.b.img(this), iround(b.x), iround(b.y), l.color);
        else
          drawThoughtLine(bg, l.a.img(this), iround(a.x), iround(a.y), l.b.img(this), iround(b.x), iround(b.y), l.color);
        String text = l.textForRender();
        if (nempty(text)) {
          drawOutlineTextAlongLine_flip.set(flipMap.get(l));
          drawThoughtLineText(bg, l.a.img(this), iround(a.x), iround(a.y), l.b.img(this), iround(b.x), iround(b.y), text, Color.white /*l.color*/);
        }
      }
      
      // Circles
      
      for (Circle c : circles) {
        DoublePt p = translateDoublePt(translate, c.doublePt(w, h));
        drawThoughtCircle(bg, c.img(this), p.x, p.y);
      }
      
      for (Circle c : circles) {
        DoublePt p = translateDoublePt(translate, c.doublePt(w, h));
        String text = c.textForRender();
        if (nempty(text))
          drawThoughtCircleText(bg, c.img(this), p, text);
          
        if (c == hoverCircle)
          drawThoughtCirclePlus(bg, c.img(this), p.x, p.y);
      }
    } finally {
      lock.unlock();
    }
    return bg;
  }
  
  Canvas showAsFrame(int w, int h) {
    Canvas canvas = showAsFrame();
    frameInnerSize(canvas, w, h);
    centerFrame(getFrame(canvas));
    return canvas;
  }
  
  Canvas showAsFrame() {
    return (Canvas) swing(new Object() { Object get() { try { 
      Canvas canvas = makeCanvas();
      showCenterFrame(canvas);
      return canvas;
     } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "Canvas canvas = makeCanvas();\r\n      showCenterFrame(canvas);\r\n      ret canvas;"; }});
  }
  
  Canvas makeCanvas() {
    final Object makeImg = new Object() { Object get(int w, int h) { try { return  makeImage(w, h) ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "makeImage(w, h)"; }};
    final Canvas canvas = jcanvas(makeImg);
    disableImageSurfaceSelector(canvas);
    new CircleDragger(this, canvas, new Runnable() { public void run() { try {  updateCanvas(canvas, makeImg) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "updateCanvas(canvas, makeImg)"; }});
    
    componentPopupMenu(canvas, new Object() { void get(JPopupMenu menu) { try { 
      // POPUP MENU START
      Pt p = canvas.pointFromEvent(componentPopupMenu_mouseEvent.get());
      final Line l = findLine(canvas, p);
      if (l != null) {
        addMenuItem(menu, "Rename Relation...", new Runnable() { public void run() { try { 
          renameLine(canvas, l)
        ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "renameLine(canvas, l)"; }});
        
        addMenuItem(menu, "Delete Relation", new Runnable() { public void run() { try { 
          deleteLine(l);
          canvas.update();
        
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "deleteLine(l);\r\n          canvas.update();"; }});
      }
      
      final Circle c = findCircle(canvas, p);
      if (c != null) {
        addMenuItem(menu, "Rename Circle...", new Runnable() { public void run() { try {  renameCircle(canvas, c) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "renameCircle(canvas, c)"; }});
        addMenuItem(menu, "Delete Circle", new Runnable() { public void run() { try { 
          deleteCircle(c);
          canvas.update();
        
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "deleteCircle(c);\r\n          canvas.update();"; }});
        
        if (c.img != null || c.quickvis != null)
          addMenuItem(menu, "Delete Image", new Runnable() { public void run() { try { 
            c.img = null;
            c.quickvis = null;
            canvas.update();
          
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "c.img = null;\r\n            c.quickvis = null;\r\n            canvas.update();"; }});
          
        if (neqic(c.text, c.quickvis))
          addMenuItem(menu, "Visualize", new Runnable() { public void run() { try { 
            { Thread _t_0 = new Thread("Visualizing") {
public void run() { try {
  
              quickVisualize(c.text);
              print("Quickvis done");
              { swing(new Runnable() { public void run() { try { 
                c.img = null;
                c.quickvis = c.text;
                canvas.update();
                pcallF(onRenameCircle, c); schange();
              
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "c.img = null;\r\n                c.quickvis = c.text;\r\n                canvas.upda..."; }}); }
            } catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_0); }
          
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "thread \"Visualizing\" {\r\n              quickVisualize(c.text);\r\n              pri..."; }});
      }
      
      addMenuItem(menu, "Copy structure to clipboard", new Runnable() { public void run() { try { 
        copyTextToClipboard(cal_simplifiedStructure(CirclesAndLines.this))
      ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "copyTextToClipboard(cal_simplifiedStructure(CirclesAndLines.this))"; }});

      addMenuItem(menu, "Paste structure", new Runnable() { public void run() { try { 
        String text = getTextFromClipboard();
        if (nempty(text)) {
          copyCAL(cal_unstructure(text), CirclesAndLines.this);
          canvas.update();
          schange();
        }
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "String text = getTextFromClipboard();\r\n        if (nempty(text)) {\r\n          co..."; }});

      // POPUP MENU END
     } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "// POPUP MENU START\r\n      Pt p = canvas.pointFromEvent(componentPopupMenu_mouse..."; }});
    
    return canvas;
  }
  
  Canvas show() { return showAsFrame(); }
  Canvas show(int w, int h) { return showAsFrame(w, h); }
  
  Circle findCircle(String text) {
    for (Circle c : circles) if (eq(c.text, text)) return c;
    for (Circle c : circles) if (eqic(c.text, text)) return c;
    return null;
  }
  
  void renameCircle(final Canvas canvas, final Circle c) {
    final JTextField tf = jtextfield(c.text);
    showFormTitled("Rename circle",
      "Old name", jlabel(c.text),
      "New name", tf,
      new Runnable() { public void run() { try { 
        c.setText(getTextTrim(tf));
        canvas.update();
        pcallF(onRenameCircle, c); schange();
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "c.setText(getTextTrim(tf));\r\n        canvas.update();\r\n        pcallF(onRenameCi..."; }});
  }
  
  void renameLine(final Canvas canvas, final Line l) {
    final JTextField tf = jtextfield(l.text);
    showFormTitled("Rename relation",
      "Old name", jlabel(l.text),
      "New name", tf,
      new Runnable() { public void run() { try { 
        l.setText(getTextTrim(tf));
        canvas.update();
        pcallF(onRenameLine, l); schange();
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "l.setText(getTextTrim(tf));\r\n        canvas.update();\r\n        pcallF(onRenameLi..."; }});
  }
  
  void clear() {
    clearAll(circles, lines);
  }
  
  // only finds actually containing circles
  Circle findCircle(ImageSurface canvas, Pt p) {
    p = untranslatePt(translate, p);
    Lowest<Circle> best = new Lowest();
    for (Circle c : circles)
      if (c.contains(this, canvas, p))
        best.put(c, pointDistance(p, c.pt(canvas)));
    return best.get();
  }
  
  Circle findNearestCircle(ImageSurface canvas, Pt p) {
    Lowest<Circle> best = new Lowest();
    for (Circle c : circles)
      if (c.contains(this, canvas, p))
        best.put(c, pointDistance(p, c.pt(canvas)));
    return best.get();
  }
  
  BufferedImage processImage(BufferedImage img) {
    return scaleImage(img, imgZoom);
  }
  
  void deleteCircle(Circle c) {
    for (Line l : cloneList(lines))
      if (l.a == c || l.b == c) deleteLine(l);
    circles.remove(c);
    pcallF(onDeleteCircle, c); schange();
  }
  
  void deleteLine(Line l) {
    lines.remove(l);
    pcallF(onDeleteLine, l); schange();
  }
  
  void openPlusDialog(final Circle c, final ImageSurface canvas) {
    if (c == null) return;
    
    final JTextField tfFrom = jtextfield(c.text);
    final JTextField tfRel = jtextfield(web_defaultRelationName());
    final JComboBox tfTo = autoComboBox(collect(circles, "text"));
    
    showFormTitled("Add connection",
      "From node", tfFrom,
      "Connection name", tfRel,
      "To node", tfTo,
      new Object() { Object get() { try { 
        String sA = getTextTrim(tfFrom);
        Circle a = eq(sA, c.text) ? c : findOrMakeCircle(sA);
        if (a == null) { messageBox("Not found: " + getTextTrim(tfFrom)); return false; }
        Circle b = findOrMakeCircle(getTextTrim(tfTo));
        if (b == null) { messageBox("Not found: " + getTextTrim(tfTo)); return false; }
        if (a == b) { infoBox("Can't connect circle to itself for now"); return false; }
        Arrow arrow = arrow(a, getTextTrim(tfRel), b);
        ((Canvas) canvas).update();
        pcallF(onUserMadeArrow, arrow); schange();
        return null;
       } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "S sA = getTextTrim(tfFrom);\r\n        Circle a = eq(sA, c.text) ? c : findOrMakeC..."; }});
    awtLater(tfRel, 100, new Runnable() { public void run() { try {  requestFocus(tfRel) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "requestFocus(tfRel)"; }});
  }
  
  void schange() {
    pcallF(onStructureChange);
  }
  
  Circle findOrMakeCircle(String text) {
    Circle c = findCircle(text);
    if (c == null) {
      c = circle(imageForUserMadeNodes(), random(0.1, 0.9), random(0.1, 0.9), text);
      pcallF(onUserMadeCircle, c); schange();
    }
    return c;
  }

  BufferedImage imageForUserMadeNodes() {  
    if (imageForUserMadeNodes == null)
      imageForUserMadeNodes = whiteImage(20, 20);
    return imageForUserMadeNodes;
  }
  
  Line findLine(Canvas is, Pt p) {
    p = untranslatePt(translate, p);
    Lowest<Line> best = new Lowest();
    for (Line line : lines) {
      double d = distancePointToLineSegment(line.a.pt(is), line.b.pt(is), p);
      if (d <= maxDistanceToLine)
        best.put(line, d);
    }
    return best.get();
  }
} // end of class CirclesAndLines

static class Circle extends Base {
  transient BufferedImage img;
  double x, y;
  //static BufferedImage defaultImage;
  String quickvis;
  
  BufferedImage img(CirclesAndLines cal) {
    if (img != null) return img;
    if (nempty(quickvis)) img = quickVisualize(quickvis);
    //if (defaultImage == null) defaultImage = loadImage2(#1007372);
    return cal.imageForUserMadeNodes();
  }
  
  Pt pt(ImageSurface is) {
    return pt(is.getWidth(), is.getHeight());
  }
  
  Pt pt(int w, int h) {
    return new Pt(iround(x*w), iround(y*h));
  }
  
  DoublePt doublePt(int w, int h) {
    return new DoublePt(x*w, y*h);
  }
  
  boolean contains(CirclesAndLines cal, ImageSurface is, Pt p) {
    return pointDistance(p, pt(is)) <= thoughtCircleSize(img(cal))/2+1;
  }
}

static class Line extends Base {
  Circle a, b;
  transient Color color = CirclesAndLines.defaultLineColor;
  
  Line setColor(Color color) {
    this.color = color;
    return this;
  }
}

static class Arrow extends Line {}

static class CircleDragger extends MouseAdapter {
  CirclesAndLines cal;
  ImageSurface is;
  Object update;
  int dx, dy;
  Circle circle;
  Pt startPoint;
  
  CircleDragger(CirclesAndLines cal, ImageSurface is, Object update) {
  this.update = update;
  this.is = is;
  this.cal = cal;
    if (containsInstance(is.tools, CircleDragger.class)) return;
    is.tools.add(this);
    is.addMouseListener(this);
    is.addMouseMotionListener(this);
  }

  public void mouseMoved(MouseEvent e) {
    Pt p = is.pointFromEvent(e);
    Circle c = cal.findCircle(is, p);
    if (c != cal.hoverCircle) {
      cal.hoverCircle = c;
      callF(update);
    }
  }
  
  public void mousePressed(MouseEvent e) {
    if (e.getButton() == MouseEvent.BUTTON1) {
      Pt p = is.pointFromEvent(e);
      startPoint = p;
      circle = cal.findCircle(is, p);
      if (circle != null) {
        dx = p.x-iround(circle.x*is.getWidth());
        dy = p.y-iround(circle.y*is.getHeight());
      } else { 
        Pt t = unnull(cal.translate);
        dx = p.x-t.x;
        dy = p.y-t.y;
      }
    }
  }

  public void mouseDragged(MouseEvent e) {
    if (startPoint == null) return;
    Pt p = is.pointFromEvent(e);
    if (circle != null) {
      circle.x = (p.x-dx)/(double) is.getWidth();
      circle.y = (p.y-dy)/(double) is.getHeight();
      pcallF(cal.onLayoutChange, circle);
      callF(update);
    } else {
      cal.translate = new Pt(p.x-dx, p.y-dy);
      callF(update);
    }
  }

  public void mouseReleased(MouseEvent e) {
    mouseDragged(e);
    if (eq(is.pointFromEvent(e), startPoint))
      cal.openPlusDialog(circle, is);
    circle = null;
    startPoint = null;
  }
}

static interface Producer<A> {
  public A next();
}

static ThreadLocal<Boolean> DynamicObject_loading = new ThreadLocal();

static class DynamicObject {
  String className; // just the name, without the "main$"
  LinkedHashMap<String,Object> fieldValues = new LinkedHashMap();
  
  DynamicObject() {}
  // className = just the name, without the "main$"
  DynamicObject(String className) {
  this.className = className;}
}

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 Matches {
  String[] m;
  
  Matches() {}
  Matches(String... m) {
  this.m = m;}
  
  String get(int i) { return i < m.length ? m[i] : null; }
  String unq(int i) { return unquote(get(i)); }
  String fsi(int i) { return formatSnippetID(unq(i)); }
  String fsi() { return fsi(0); }
  String tlc(int i) { return unq(i).toLowerCase(); }
  boolean bool(int i) { return "true".equals(unq(i)); }
  String rest() { return m[m.length-1]; } // for matchStart
  int psi(int i) { return Integer.parseInt(unq(i)); }
}


static Pt pt(int x, int y) {
  return new Pt(x, y);
}
static boolean neqic(String a, String b) {
  return !eqic(a, b);
}
static String quickVisualize_progID = "#1007145";
static Lock quickVisualize_lock = lock();

static BufferedImage quickVisualize_fromCache(String query) {
  File f = quickVisualize_imageFile(query);
  if (f.length() != 0) try { return loadPNG(f); } catch (Throwable __e) { printStackTrace2(__e); }
  return null;
}

static String quickVisualize_preprocess(String query) {
  return toUpper(shorten(trim(query), 200));
}

static BufferedImage quickVisualize(String query) {
  query = quickVisualize_preprocess(query);
  if (empty(query)) return null;
  BufferedImage img = quickVisualize_fromCache(query);
  if (img != null) return img;
  File f = quickVisualize_imageFile(query);
  /*L<S> urls = googleImageSearch_multi(query);
  saveTextFile(quickVisualize_urlsFile(query), joinLines(urls));
  if (empty(urls)) null;
  img = loadBufferedImage(first(urls));*/
  Lock _lock_31 = quickVisualize_lock; lock(_lock_31); try {
  img = googleImageSearchFirst(query);
  if (img == null) return null;
  savePNG(f, img);
  return img;
} finally { _lock_31.unlock(); } }

static String quickVisualize_imagePath(String query) {
  query = quickVisualize_preprocess(query);
  return fsI(quickVisualize_progID) + "/" + urlencode(query) + ".png";
}

static File quickVisualize_imageFile(String query) {
  query = quickVisualize_preprocess(query);
  return prepareProgramFile(quickVisualize_progID, urlencode(query) + ".png");
}

static File quickVisualize_urlsFile(String query) {
  query = quickVisualize_preprocess(query);
  return prepareProgramFile(quickVisualize_progID, "urls-" + urlencode(query) + ".txt");
}
static int updateCanvas_retryInterval = 50;

// if makeImg returns null, it is recalled after a delay
static void updateCanvas(final Canvas canvas, final Object makeImg) {
  swingNowOrLater(new Runnable() { public void run() { try { 
    if (canvas.updating || canvas.getWidth() == 0) return;
    canvas.updating = true;
    try {
      BufferedImage img = asBufferedImage(callF(makeImg, canvas.getWidth(), canvas.getHeight()));
      if (img != null) {
        canvas.setImage(img);
        canvas.updating = false;
      } else
        awtLater(updateCanvas_retryInterval, new Runnable() { public void run() { try { 
          canvas.updating = false;
          updateCanvas(canvas, makeImg);
        
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "canvas.updating = false;\r\n          updateCanvas(canvas, makeImg);"; }});
    } catch (Throwable e) {
      canvas.updating = false;
      throw rethrow(e);
    }
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (canvas.updating || canvas.getWidth() == 0) return;\r\n    canvas.updating = tr..."; }});
}

static void updateCanvas(final Canvas canvas) {
  if (canvas != null) canvas.update();
}
static JTextField jtextfield() {
  return jTextField();
}

static JTextField jtextfield(String text) {
  return jTextField(text);
}

static JTextField jtextfield(Object o) {
  return jTextField(o);
}

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 int thoughtCircleSize(BufferedImage img) {
  return min(img.getWidth(), img.getHeight()) + 20;
}
static boolean containsInstance(Iterable i, Class c) {
  if (i != null) for (Object o : i)
    if (isInstanceX(c, o))
      return true;
  return false;
}
static JFrame centerFrame(Component c) {
  Window w = getWindow(c);
  if (w != null)
    w.setLocationRelativeTo(null); // magic trick
  return castOpt(w, JFrame.class);
}

static JFrame centerFrame(int w, int h, Component c) {
  return centerFrame(setFrameSize(w, h, c));
}

static class componentPopupMenu_Maker {
  List menuMakers = new ArrayList();
}

static Map<JComponent, componentPopupMenu_Maker> componentPopupMenu_map = new WeakHashMap();

static ThreadLocal<MouseEvent> componentPopupMenu_mouseEvent = new ThreadLocal();

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

static class componentPopupMenu_Adapter extends MouseAdapter {
  componentPopupMenu_Maker maker;
  
  componentPopupMenu_Adapter(componentPopupMenu_Maker 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.menuMakers)
      pcallF(menuMaker, menu);
    
    // show menu if any items in it
    if (menu.getComponentCount() != emptyCount)
      menu.show(e.getComponent(), e.getX(), e.getY());
  }
}
//please include function withMargin.

static int showForm_defaultGap = 4;

static JPanel showFormTitled(final String title, final Object... _parts) {
  return swing(new F0<JPanel>() { JPanel get() { try { 
    final Var<JFrame> frame = new Var();
    JPanel panel = showForm_makePanel(frame, _parts);
    frame.set(handleEscapeKey(minFrameWidth(showPackedFrame(title, withMargin(panel)), 400)));
    return panel;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "final new Var<JFrame> frame;\r\n    JPanel panel = showForm_makePanel(frame, _part..."; }});
}

static JPanel showForm_makePanel(final Var<JFrame> frame, Object... _parts) {
  List<List> l = new ArrayList();
  List parts = asList(_parts);
  Runnable submit = null;
  for (int i = 0; i < l(parts); i++) {
    final Object o = parts.get(i), next = get(parts, i+1);
    if (o instanceof Component || o instanceof String || next instanceof Component) { // smartAdd accepts strings
      l.add(ll(o == null ? new JPanel() : o, next));
      if (next instanceof JButton && submit == null)
        submit = new Runnable() { public void run() { try {  ((JButton) next).doClick() ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "((JButton) next).doClick()"; }};
      i++;
    } else if (isRunnable(o))
      l.add(ll(null, jbutton(showFormSubmitButtonName(), submit = new Runnable() { public void run() { try { 
        Object result = call(o);
        if (neq(Boolean.FALSE, result))
          disposeFrame(frame.get());
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "Object result = call(o);\r\n        if (neq(Boolean.FALSE, result))\r\n          dis..."; }})));
    else print("showForm: Unknown element type: " + getClassName(o));
  }
  JPanel panel = hvgrid((List) l, showForm_defaultGap);
  if (submit != null)
    for (JTextField textField : childrenOfType(panel, JTextField.class))
      onEnter(textField, submit);
  return panel;
}
static double distancePointToLineSegment(Pt a, Pt b, Pt p) {
  int x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y, x3 = p.x, y3 = p.y;
  
  float px=x2-x1;
  float py=y2-y1;
  float temp=(px*px)+(py*py);
  float u=((x3 - x1) * px + (y3 - y1) * py) / (temp);
  if (u>1) u=1; else if(u<0) u=0;
  float x = x1 + u * px;
  float y = y1 + u * py;
  float dx = x - x3;
  float dy = y - y3;
  return sqrt(dx*dx + dy*dy);
}
static <B, A extends B> A addAndReturn(Collection<B> c, A a) {
  if (c != null) c.add(a);
  return a;
}
static <A> List<A> getWhere(Collection<A> c, Object... data) {
  List l = new ArrayList();
  for (A x : c)
    if (checkFields(x, data))
      l.add(x);
  return l;
}
static String getTextTrim(JTextComponent c) {
  return trim(getText(c));
}

// tested for editable combo box - returns the contents of text field
static String getTextTrim(JComboBox cb) {
  return trim(getText(cb));
}
static Color drawThoughtCircle_defaultColor = Color.white;

static void drawThoughtCircle(BufferedImage bg, BufferedImage img, double x, double y) {
  // TODO: crop to certain size
  BufferedImage circle = cutImageToCircle(img_addBorder(cutImageToCircle(img), drawThoughtCircle_defaultColor, 10));
  x -= circle.getWidth()/2;
  y -= circle.getHeight()/2;
  drawImageOnImage(circle, bg, iround(x), iround(y));
}


static String copyTextToClipboard(String text) {
  StringSelection selection = new StringSelection(text);
  Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
  return text;
}
static BufferedImage whiteImage(int w, int h) {
  return newBufferedImage(w, h, Color.white);
}
static void disableImageSurfaceSelector(ImageSurface is) {
  ImageSurfaceSelector s = firstInstance(is.tools, ImageSurfaceSelector.class);
  if (s == null) return;
  is.removeMouseListener(s);
  is.removeMouseMotionListener(s);
  is.tools.add(s);
}

static void copyCAL(CirclesAndLines cal1, CirclesAndLines cal2) {
  if (cal1 == cal2) return;
  copyList(cal1.circles, cal2.circles);
  copyList(cal1.lines, cal2.lines);
  copyFields(cal1, cal2, "defaultImageID",  "arrowClass", "circleClass", "imgZoom", "imageForUserMadeNodes");
  copyListeners(cal1, cal2);
}
static Random random_random = new Random();

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

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

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

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

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

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

static <A> A random(Collection<A> c) {
  return oneOf(asList(c));
}
static int ptY(Pt p) {
  return p == null ? 0 : p.y;
}
static int ptX(Pt p) {
  return p == null ? 0 : p.x;
}
static Thread startThread(Object runnable) {
  return startThread(defaultThreadName(), runnable);
}

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

static Thread startThread(Thread t) {
  _registerThread(t);
  t.start();
  return t;
}
static <A> boolean setAdd(Collection<A> c, A a) {
  if (c.contains(a)) return false;
  c.add(a);
  return true;
}
static ReentrantLock fairLock() {
  return new ReentrantLock(true);
}
static boolean possibleGlobalID(String s) {
  return l(s) == 16 && allLowerCaseCharacters(s);
}
static <A, B> Pair<A, B> pair(A a, B b) {
  return new Pair(a, b);
}
static BufferedImage renderTiledBackground(String tileImageID, int w, int h) {
  return renderTiledBackground(tileImageID, w, h, 0, 0);
}

static BufferedImage renderTiledBackground(String tileImageID, int w, int h, int shiftX, int shiftY) {
  BufferedImage tileImage = loadImage2(tileImageID);
  BufferedImage img = newBufferedImage(w, h, Color.black);
  Graphics2D g = img.createGraphics();
  int tw = tileImage.getWidth(), th = tileImage.getHeight();
  for (int x = mod(shiftX-1, tw)-tw+1; x < w; x += tw)
    for (int y = mod(shiftY-1, th)-th+1; y < h; y += th)
      g.drawImage(tileImage, x, y, null);  
  g.dispose();
  return img;
} 
static String[] dropFirst(int n, String[] a) {
  return drop(n, a);
}

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

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

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

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

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

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

static String dropFirst(int n, String s) { return substring(s, n); }
static String dropFirst(String s) { return substring(s, 1); }
static int drawThoughtLine_width = 10;

static void drawThoughtLine(BufferedImage bg,
  BufferedImage img1, int x1, int y1,
  BufferedImage img2, int x2, int y2, Color color) {
  Graphics2D g = imageGraphics(bg);
  g.setColor(color);
  g.setStroke(new BasicStroke(drawThoughtLine_width));
  g.drawLine(x1, y1, x2, y2);
  g.dispose();
}
static void clearAll(Object... l) {
  for (Object o : l) callOpt(o, "clear");
}
static AutoComboBox autoComboBox(final Collection<String> items) {
  return swing(new F0<AutoComboBox>() { AutoComboBox get() { try { 
    AutoComboBox cb = new AutoComboBox();
    cb.setKeyWord(items);
    return cb;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "new AutoComboBox cb;\r\n    cb.setKeyWord(items);\r\n    ret cb;"; }});
}

static AutoComboBox autoComboBox(String value, Collection<String> items) {
  return setText(autoComboBox(items), value);
}
static BufferedImage loadImage2(String snippetIDOrURL) {
  return loadBufferedImage(snippetIDOrURL);
}

static BufferedImage loadImage2(File file) {
  return loadBufferedImage(file);
}
static int drawThoughtArrow_size = 15;

static void drawThoughtArrow(BufferedImage bg,
  BufferedImage img1, double x1, double y1,
  BufferedImage img2, double x2, double y2, Color color) {
  double cs = thoughtCircleSize(img2)/2-1;
  double dist = pointDistance(x1, y1, x2, y2);
  double arrowLen = drawThoughtArrow_size*drawArrowHead_length-1;
  DoublePt v = blendDoublePts(new DoublePt(x2, y2), new DoublePt(x1, y1), (cs+arrowLen)/dist);
  DoublePt p = blendDoublePts(new DoublePt(x2, y2), new DoublePt(x1, y1), cs/dist);
  Graphics2D g = imageGraphics(bg);
  g.setColor(color);
  g.setStroke(new BasicStroke(drawThoughtLine_width));
  g.draw(new Line2D.Double(x1, y1, v.x, v.y));
  drawArrowHead(g, x1, y1, p.x, p.y, drawThoughtArrow_size);
  g.dispose();
}
static JFrame showCenterFrame(String title, int w, int h) {
  return showCenterFrame(title, w, h, null);
}

static JFrame showCenterFrame(String title, int w, int h, Component content) {
  JFrame frame = makeFrame(title, content);
  frame.setSize(w, h);
  return centerFrame(frame);
}

static JFrame showCenterFrame(String title, Component content) {
  return centerFrame(makeFrame(title, content));
}


static JFrame showCenterFrame(Component content) {
  return centerFrame(makeFrame(content));
}
static <A> List<A> cloneList(Collection<A> l) {
  if (l == null) return new ArrayList();
  // assume collection's mutex is equal to collection, which will be true unless you explicitly pass a mutex to synchronizedList() which no one ever does.
  synchronized(l) {
    return new ArrayList<A>(l);
  }
}
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(JMenu menu, JMenuItem menuItem) {
  menu.add(menuItem);
}

static Pt untranslatePt(Pt a, Pt b) {
  if (a == null) return b;
  return new Pt(b.x-a.x, b.y-a.y);
}
static String fsi(String id) {
  return formatSnippetID(id);
}


// uses bilinear interpolation
static BufferedImage scaleImage(BufferedImage before, double scale) {
  if (scale == 1) return before;
  int w = before.getWidth();
  int h = before.getHeight();
  int neww = max(1, iround(w*scale)), newh = max(1, iround(h*scale));
  BufferedImage after = new BufferedImage(neww, newh, BufferedImage.TYPE_INT_ARGB);
  AffineTransform at = new AffineTransform();
  at.scale(scale, scale);
  AffineTransformOp scaleOp = 
     new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
  return scaleOp.filter(before, after);
}
static BufferedImage drawThoughtCirclePlus_img;
static int drawThoughtCirclePlus_size = 24;

static void drawThoughtCirclePlus(BufferedImage bg, BufferedImage img, double x, double y) {
  if (drawThoughtCirclePlus_img == null)
    drawThoughtCirclePlus_img = resizeImage(loadImage2("#1009864"), drawThoughtCirclePlus_size);
  x -= drawThoughtCirclePlus_img.getWidth()/2;
  y -= drawThoughtCirclePlus_img.getHeight()/2;
  drawImageOnImage(drawThoughtCirclePlus_img, bg, iround(x), iround(y));
}



static String getTextFromClipboard() { try {
  Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
  if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.stringFlavor))
    return (String) transferable.getTransferData(DataFlavor.stringFlavor);
  return null;
} catch (Exception __e) { throw rethrow(__e); } }
static BufferedImage quickVisualizeOr(String query, String defaultImageID) {
  BufferedImage img = quickVisualize(query);
  return img != null ? img : loadImage2(defaultImageID);
}
static int iround(double d) {
  return (int) Math.round(d);
}
static double pointDistance(Pt a, Pt b) {
  return sqrt(sqr(a.x-b.x) + sqr(a.y-b.y));
}

static double pointDistance(double x1, double y1, double x2, double y2) {
  return sqrt(sqr(x1-x2) + sqr(y1-y2));
}
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_MESSAG..."; }}); }
}

static void messageBox(Throwable e) {
  showConsole();
  printStackTrace(e);
  messageBox(str(innerException(e)));
}
static <A> A findWhere(Collection<A> c, Object... data) {
  for (A x : c)
    if (checkFields(x, data))
      return x;
  return null;
}
static String cal_simplifiedStructure(CirclesAndLines cal) {
  return cal_simplifiedStructure(structure(cal));
}

static String cal_simplifiedStructure(String structure) {
  CirclesAndLines cal = (CirclesAndLines) ( unstructure(structure));
  for (Circle c : cal.circles) {
    c.x = roundToOneHundredth(c.x);
    c.y = roundToOneHundredth(c.y);
  }
  return cal_structure_impl(cal);
}
static Object pcallF(Object f, Object... args) {
  return pcallFunction(f, args);
}


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

// independent timer
static void awtLater(int delay, final Object r) {
  swingLater(delay, r);
}

static void awtLater(Object r) {
  swingLater(r);
}

// dependent timer (runs only when component is visible)
static void awtLater(JComponent component, int delay, Object r) {
  installTimer(component, r, delay, delay, false);
}

static void awtLater(JFrame frame, int delay, Object r) {
  awtLater(frame.getRootPane(), delay, r);
}
static class Canvas extends ImageSurface {
  Object makeImg;
  boolean updating;
  
  Canvas() {}
  Canvas(Object makeImg) {
  this.makeImg = makeImg;}
  
  void update() { updateCanvas(this, makeImg); }
}

// f: (int w, int h) -> BufferedImage
static Canvas jcanvas(Object f) {
  return jcanvas(f, 0); // 100
}

static Canvas jcanvas(final Object f, final int updateDelay) {
  return (Canvas) swing(new Object() { Object get() { try { 
    final Canvas is = new Canvas(f);
    is.specialPurposed = true;
    final Runnable update = new Runnable() {
      boolean first = true;
      public void run() {
        BufferedImage img = is.getImage();
        int w = is.getWidth(), h = is.getHeight();
        if (first || img.getWidth() != w || img.getHeight() != h) {
          updateCanvas(is, f);
          first = false;
        }
      }
    };
    onResize(is, new Runnable() { public void run() { try {  awtLater(is, updateDelay, update) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "awtLater(is, updateDelay, update)"; }});
    bindToComponent(is, update); // first update
    return is;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "final Canvas is = new Canvas(f);\r\n    is.specialPurposed = true;\r\n    final Runn..."; }});
}
static <A> void setAddAll(List<A> a, Collection<A> b) {
  for (A x : b)
    setAdd(a, x);
}
static void requestFocus(final JComponent c) { focus(c); }
static <A> A nu(Class<A> c, Object... values) {
  A a = nuObject(c);
  setAll(a, values);
  return a;
}
static JWindow infoBox(String text) {
  return infoMessage(text);
}

static JWindow infoBox(String text, double seconds) {
  return infoMessage(text, seconds);
}

static JWindow infoBox(Throwable e) {
  return infoMessage(e);
}
static JLabel jlabel(final String text) {
  return swing(new F0<JLabel>() { JLabel get() { try { 
    final JLabel l = new JLabel(text) {
      @Override
      public void setText(String text) {
        super.setText(text);
        setToolTipText(text);
      }
    };
    componentPopupMenu(l, new Object() { void get(JPopupMenu menu) { try { 
      addMenuItem(menu, "Copy text to clipboard", new Runnable() { public void run() { try { 
        copyTextToClipboard(l.getText());
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "copyTextToClipboard(l.getText());"; }});
     } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "addMenuItem(menu, \"Copy text to clipboard\", r {\r\n        copyTextToClipboard(l.g..."; }});
    return l;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "final JLabel l = new JLabel(text) {\r\n      @Override\r\n      public void setText(..."; }});
}

static JLabel jlabel() {
  return jlabel(" ");
}
static String web_defaultRelationName = "";

static String web_defaultRelationName() {
  return web_defaultRelationName;
}
static int drawThoughtLineText_shift = 10;

static void drawThoughtLineText(BufferedImage bg,
  BufferedImage img1, int x1, int y1,
  BufferedImage img2, int x2, int y2,
  String text, Color color) {
  
  Graphics2D g = imageGraphics(bg);
  g.setColor(color);
  g.setFont(sansSerif(20));
  
  int w1 = img_minOfWidthAndHeight(img1);
  int w2 = img_minOfWidthAndHeight(img2);
  int sideShift = (w1-w2)/4;
  int len = vectorLength(x2-x1, y2-y1);
  int dx = iround(sideShift*(x2-x1)/len), dy = iround(sideShift*(y2-y1)/len);
  x1 += dx; x2 += dx;
  y1 += dy; y2 += dy;
  
  drawOutlineTextAlongLine(g, text, x1, y1, x2, y2, drawThoughtLine_width/2+drawThoughtLineText_shift, color, Color.black);
  g.dispose();
}
static JFrame frameInnerSize(final Component c, final double w, final double h) {
  final JFrame frame = getFrame(c);
  if (frame != null) { swing(new Runnable() { public void run() { try { 
    Container cp = frame.getContentPane();
    Dimension oldSize = cp.getPreferredSize();
    cp.setPreferredSize(new Dimension(iround(w), iround(h)));
    frame.pack();
    cp.setPreferredSize(oldSize);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "Container cp = frame.getContentPane();\r\n    Dimension oldSize = cp.getPreferredS..."; }}); }
  return frame;
}

static void frameInnerSize(JFrame frame, Dimension d) {
  frameInnerSize(frame, d.width, d.height);
}

static JFrame frameInnerSize(Pt p, JFrame frame) {
  frameInnerSize(frame, p.x, p.y);
  return frame;
}
static boolean containsIC(List<String> l, String s) {
  return containsIgnoreCase(l, s);
}

static boolean containsIC(String[] l, String s) {
  return containsIgnoreCase(l, s);
}

static boolean containsIC(String s, char c) {
  return containsIgnoreCase(s, c);
}

static boolean containsIC(String a, String b) {
  return containsIgnoreCase(a, b);
}
static DoublePt translateDoublePt(Pt a, DoublePt b) {
  return a == null ? b : b == null ? new DoublePt(a.x, a.y) : new DoublePt(a.x+b.x, a.y+b.y);
}
static int drawThoughtCircleText_margin = 5;
static Color drawThoughtCircleText_color = Color.yellow;

static void drawThoughtCircleText(BufferedImage bg, BufferedImage img, DoublePt p, String text) {
  Graphics2D g = imageGraphics(bg);
  g.setFont(sansSerifBold(20));
  FontMetrics fm = g.getFontMetrics();
  int h = fm.getHeight();
  double y = p.y+thoughtCircleSize(img)/2+drawThoughtCircleText_margin;
  for (String s : lines(text)) {
    drawTextWithOutline(g, s, (float) (p.x-fm.stringWidth(s)/2), (float) (y+fm.getLeading()+fm.getMaxAscent()), drawThoughtCircleText_color, Color.black);
    y += h;
  }
  g.dispose();
}


static String cal_structure(CirclesAndLines cal) {
  return cal_structure_impl(restructure(cal));
}

static String cal_structure_impl(CirclesAndLines cal) {
  if (cal.arrowClass == Arrow.class) cal.arrowClass = null;
  if (cal.circleClass == Circle.class) cal.circleClass = null;
  for (Circle c : cal.circles) cal_structure_simplifyElement(c);
  for (Line l : cal.lines) cal_structure_simplifyElement(l);
  return structure(cal);
}

static void cal_structure_simplifyElement(Base b) {
  if (eq(b.traits, ll(b.text))) b.traits = null;
}
static JFrame handleEscapeKey(final JFrame frame) {
  KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
  frame.getRootPane().registerKeyboardAction(new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
      frame.dispose();
    }
  }, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
  return frame;
}

static WeakHashMap<JFrame,Boolean> makeFrame_myFrames = new WeakHashMap();

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

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

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

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

static JFrame makeFrame(final String title, final Object content, final boolean showIt) {
  return swing(new F0<JFrame>() { JFrame get() { try { 
    if (getFrame(content) != null)
      return getFrame(setFrameTitle((Component) content, title));
    final JFrame frame = new JFrame(title);
    makeFrame_myFrames.put(frame, Boolean.TRUE);
    JComponent wrapped = wrap(content);
    if (wrapped != null)
      frame.getContentPane().add(wrapped);
    frame.setBounds(300, 100, 500, 400);
    if (showIt)
      frame.setVisible(true);
    //callOpt(content, "requestFocus");
    //exitOnFrameClose(frame);
    
    standardTitlePopupMenu(frame);
    return frame;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "if (getFrame(content) != null)\r\n      ret getFrame(setFrameTitle((Component) con..."; }});
}
static void copyListeners(Object a, Object b) {
  for (String f : fieldNames(a))
    if (l(f) > 2 && startsWith(f, "on") && isUpperCase(f.charAt(2)))
      setOpt(b, f, getOpt(a, f));
}
static void disposeFrame(final Component c) {
  disposeWindow(c);
}
static JTextField jTextField() {
  return jTextField("");
}

static JTextField jTextField(final String text) {
  return swing(new F0<JTextField>() { JTextField get() { try { 
    JTextField tf = new JTextField(unnull(text));
    jenableUndoRedo(tf);
    tf.selectAll();
    return tf;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "JTextField tf = new JTextField(unnull(text));\r\n    jenableUndoRedo(tf);\r\n    tf...."; }});
}

static JTextField jTextField(Object o) {
  return jTextField(strOrEmpty(o));
}

static boolean infoMessage_alwaysOnTop = true;
static double infoMessage_defaultTime = 5.0;

// automatically switches to AWT thread for you
static JWindow infoMessage(String text) {
  return infoMessage(text, infoMessage_defaultTime);
}

static JWindow infoMessage(final String text, final double seconds) {
  print(text);
  return infoMessage_noprint(text, seconds);
}

static JWindow infoMessage_noprint(String text) {
  return infoMessage_noprint(text, infoMessage_defaultTime);
}

static JWindow infoMessage_noprint(final String text, final double seconds) {
  if (isHeadless()) return null;
  return (JWindow) swingAndWait(new Object() { Object get() { try { 
    JTextArea ta = wrappedTextArea(text);
    int size = 14;
    if (l(text) <= 50) size *= 2;
    else if (l(text) < 100) size = iround(size*1.5);
    ta.setFont(typeWriterFont(size));
    JScrollPane sp = jscroll(ta);
    final JWindow window = showWindow(withMargin(sp));
    window.setSize(300, 150);
    moveToTopRightCorner(window);
    onClick(ta, new Runnable() { public void run() { try {  window.dispose() ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "window.dispose()"; }});
    if (infoMessage_alwaysOnTop)
      window.setAlwaysOnTop(true);
    window.setVisible(true);
    disposeWindowAfter(iround(seconds*1000), window);
    return window;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "JTextArea ta = wrappedTextArea(text);\r\n    int size = 14;\r\n    if (l(text) <= 50..."; }});
}

static JWindow infoMessage(Throwable e) {
  showConsole();
  printStackTrace(e);
  return infoMessage(str(e));
}
static String getText(final JTextComponent c) {
  return c == null ? "" : (String) swingAndWait(new Object() { Object get() { try { return  c.getText() ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "c.getText()"; }});
}

static String getText(final JLabel l) {
  return l == null ? "" : (String) swingAndWait(new Object() { Object get() { try { return  l.getText() ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "l.getText()"; }});
}

// returns the contents of text field for editable combo box
static String getText(final JComboBox cb) {
  if (cb.isEditable())
    return unnull((String) cb.getEditor().getItem());
  else
    return str(cb.getSelectedItem());
}
static int vectorLength(int x, int y) {
  return isqrt(sqr((long) x)+sqr((long) y));
}
static void onResize(Component c, final Object r) {
  c.addComponentListener(new ComponentAdapter() {
    public void componentResized(ComponentEvent e) {
      pcallF(r);
    }
  });
}
static BufferedImage resizeImage(BufferedImage img, int newW, int newH) {
  return resizeImage(img, newW, newH, Image.SCALE_SMOOTH);
}

static BufferedImage resizeImage(BufferedImage img, int newW, int newH, int scaleType) {
  Image tmp = img.getScaledInstance(newW, newH, scaleType);
  BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
  Graphics2D g2d = dimg.createGraphics();
  g2d.drawImage(tmp, 0, 0, null);
  g2d.dispose();
  return dimg;
}

static BufferedImage resizeImage(BufferedImage img, int newW) {
  int newH = iround(img.getHeight()*(double) newW/img.getWidth());
  return resizeImage(img, newW, newH);
}
static boolean isRunnable(Object o) {
  return o instanceof Runnable || hasMethod(o, "get");
}
// runnable = Runnable or String (method name)
static Thread newThread(Object runnable) {
  return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
}

static Thread newThread(Object runnable, String name) {
  return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
static void showConsole() {
  showFrame(consoleFrame());
}
static <A> List<A> childrenOfType(Component c, Class<A> theClass) {
  List<A> l = new ArrayList();
  scanForComponents(c, theClass, l);
  return l;
}
static Font sansSerif(int fontSize) {
  return new Font(Font.SANS_SERIF, Font.PLAIN, fontSize);
}
// undefined color, seems to be all black in practice
static BufferedImage newBufferedImage(int w, int h) {
  return new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
}

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


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

// It's the super precise version!
static double roundToOneHundredth(double d) {
  return new BigDecimal(d).setScale(2, RoundingMode.HALF_UP).doubleValue();
}
static void copyFields(Object x, Object y, String... fields) {
  if (empty(fields)) { // assume we should copy all fields
    Map<String, Object> map = objectToMap(x);
    for (String field : map.keySet())
      setOpt(y, field, map.get(field));
  } else 
    for (String field : fields) {
      Object o = getOpt(x, field);
      if (o != null)
        setOpt(y, field, o);
    }
}
static <A> void copyList(Collection<? extends A> a, Collection<A> b) {
  if (a == null || b == null) return;
  b.clear();
  b.addAll(a);
}


static ThreadLocal<Boolean> drawOutlineTextAlongLine_flip = new ThreadLocal();

static void drawOutlineTextAlongLine(Graphics2D g, String text, int x1, int y1, int x2, int y2, int shift, Color fillColor, Color outlineColor) {
  Boolean flip = optPar(drawOutlineTextAlongLine_flip);
  if (y2 == y1 && x2 == x1) ++x2;
  
  AffineTransform tx = new AffineTransform();
  double angle = Math.atan2(y2-y1, x2-x1);
  if (flip == null)
    flip = abs(angle) > pi()/2;
  if (flip) angle -= pi();
  tx.translate((x1+x2)/2.0, (y1+y2)/2.0);
  tx.rotate(angle);

  FontMetrics fm = g.getFontMetrics();
  // int y = shift+fm.getLeading()+fm.getMaxAscent(); // below
  int y = -shift-fm.getMaxDescent(); // above
  //print("drawText y=" + y + ", shift=" + shift);
  
  AffineTransform old = g.getTransform();
  g.setTransform(tx);

  drawTextWithOutline(g, text, -fm.stringWidth(text)/2.0f, y, fillColor, outlineColor);
  g.setTransform(old);
}
static JFrame minFrameWidth(JFrame frame, int w) {
  if (frame != null && frame.getWidth() < w)
    frame.setSize(w, frame.getHeight());
  return frame;
}

static JFrame minFrameWidth(int w, JFrame frame) {
  return minFrameWidth(frame, w);
}

static ThreadLocal<Boolean> imageGraphics_antiAlias = new ThreadLocal();

static Graphics2D imageGraphics(BufferedImage img) {
  return !isFalse(imageGraphics_antiAlias.get()) ? antiAliasGraphics(img) : img.createGraphics();
}
static boolean loadBufferedImage_useImageCache = true;

static BufferedImage loadBufferedImage(String snippetIDOrURL) { try {
  if (snippetIDOrURL == null) return null;
  if (isURL(snippetIDOrURL))
    return ImageIO.read(new URL(snippetIDOrURL));

  if (!isSnippetID(snippetIDOrURL)) throw fail("Not a URL or snippet ID: " + snippetIDOrURL);
  String snippetID = "" + parseSnippetID(snippetIDOrURL);
  
try {
  File dir = getCacheProgramDir("Image-Snippets");
  if (loadBufferedImage_useImageCache) {
    dir.mkdirs();
    File file = new File(dir, snippetID + ".png");
    if (file.exists() && file.length() != 0)
      try {
        return ImageIO.read(file);
      } catch (Throwable e) {
        e.printStackTrace();
        // fall back to loading from sourceforge
      }
  }

  String imageURL = snippetImageURL(snippetID);
  System.err.println("Loading image: " + imageURL);
  BufferedImage image = ImageIO.read(new URL(imageURL));

  if (loadBufferedImage_useImageCache) {
    File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis());
    ImageIO.write(image, "png", tempFile);
    tempFile.renameTo(new File(dir, snippetID + ".png"));
    //Log.info("Cached image.");
  }

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

static BufferedImage loadBufferedImage(File file) { try {
  return file.isFile() ? ImageIO.read(file) : null;
} catch (Exception __e) { throw rethrow(__e); } }
static String toUpper(String s) {
  return s == null ? null : s.toUpperCase();
}
static File prepareProgramFile(String name) {
  return mkdirsForFile(getProgramFile(name));
}

static File prepareProgramFile(String progID, String name) {
  return mkdirsForFile(getProgramFile(progID, name));
}
static <A extends JComponent> A setToolTipText(final A c, final Object toolTip) {
  if (c == null) return null;
  { swing(new Runnable() { public void run() { try { 
    String s = nullIfEmpty(str(toolTip));
    if (neq(s, c.getToolTipText()))
      c.setToolTipText(s);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "String s = nullIfEmpty(str(toolTip));\r\n    if (neq(s, c.getToolTipText()))\r\n    ..."; }}); }
  return c;
}
static 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 <A> A oneOf(List<A> l) {
  return l.isEmpty() ? null : l.get(new Random().nextInt(l.size()));
}

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

static String oneOf(String... l) {
  return oneOf(asList(l));
}
static int withMargin_defaultWidth = 6;

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

static JPanel withMargin(final int w, final Component c) {
  return swing(new F0<JPanel>() { JPanel get() { try { 
    JPanel p = new JPanel(new BorderLayout());
    p.setBorder(BorderFactory.createEmptyBorder(w, w, w, w));
    p.add(c);
    return p;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n    p.setBorder(BorderFactory.createEm..."; }});
}
static BufferedImage asBufferedImage(Object o) {
  BufferedImage bi = toBufferedImageOpt(o);
  if (bi == null) throw fail(getClassName(o));
  return bi;
}
static String[] drop(int n, String[] a) {
  n = Math.min(n, a.length);
  String[] b = new String[a.length-n];
  System.arraycopy(a, n, b, 0, b.length);
  return b;
}

static Object[] drop(int n, Object[] a) {
  n = Math.min(n, a.length);
  Object[] b = new Object[a.length-n];
  System.arraycopy(a, n, b, 0, b.length);
  return b;
}
static String googleImageSearch(String q) {
  return (String) call(hotwireOnce("#1010230"), "googleImageSearch", q);
}

static List<String> googleImageSearch_multi(String q) {
  return (List<String>) call(hotwireOnce("#1010230"), "googleImageSearch_multi", q);
}

static BufferedImage googleImageSearchFirst(String q) {
  return (BufferedImage) call(hotwireOnce("#1010230"), "googleImageSearchFirst", q);
}
static Window getWindow(Object o) {
  if (!(o instanceof Component)) return null;
  Component c = (Component) o;
  while (c != null) {
    if (c instanceof Window) return (Window) c;
    c = c.getParent();
  }
  return null;
}
static void savePNG(BufferedImage img, File file) { try {
  File tempFile = new File(file.getPath() + "_temp");
  CriticalAction ca = beginCriticalAction("Save " + f2s(file));
  try {
    ImageIO.write(img, "png", mkdirsFor(tempFile));
    file.delete();
    tempFile.renameTo(file);
  } finally {
    ca.done();
  }
} catch (Exception __e) { throw rethrow(__e); } }

// gotta love convenience & program-smartness
static void savePNG(File file, BufferedImage img) {
  savePNG(img, file);
}
static <A extends JComponent> A bindToComponent(A component, final Runnable onShow, final Runnable onUnShow) {
  component.addAncestorListener(new AncestorListener() {
    public void ancestorAdded(AncestorEvent event) {
      pcallF(onShow);
    }

    public void ancestorRemoved(AncestorEvent event) {
      pcallF(onUnShow);
    }

    public void ancestorMoved(AncestorEvent event) {
    }
  });
  return component;
}

static <A extends JComponent> A bindToComponent(A component, Runnable onShow) {
  return bindToComponent(component, onShow, null);
}
static BufferedImage img_addBorder(BufferedImage img, Color color, int border) {
  int top = border, bottom = border, left = border, right = border;
  int w = img.getWidth(), h = img.getHeight();
  BufferedImage img2 = createBufferedImage(left+w+right, top+h+bottom, color);
  Graphics2D g = img2.createGraphics();
  g.drawImage(img, left, top, null);
  g.dispose();
  return img2;
}




// 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) {
  return (Timer) swingAndWait(new Object() { Object get() { try { 
    Timer timer = new Timer(toInt(delay), new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) {
      try {
        if (!allPaused())
          callF(r);
      } catch (Throwable __e) { printStackTrace2(__e); }
    }});
    timer.setInitialDelay(toInt(firstDelay));
    timer.setRepeats(repeats);
    bindTimerToComponent(timer, component);
    return timer;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "Timer timer = new Timer(toInt(delay), actionListener {\r\n      pcall {\r\n        i..."; }});
}

static Timer installTimer(JFrame frame, long delay, long firstDelay, Object r) {
  return installTimer(frame.getRootPane(), r, delay, firstDelay);
}

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

static JFrame showPackedFrame(Component contents) {
  return packFrame(showFrame(contents));
}
static boolean checkFields(Object x, Object... data) {
  for (int i = 0; i < l(data); i += 2)
    if (neq(getOpt(x, (String) data[i]), data[i+1]))
      return false;
  return true;
}


static BufferedImage cutImageToCircle(String imageID) {
  return cutImageToCircle(loadImage2(imageID));
}

static BufferedImage cutImageToCircle(BufferedImage image) {
  int w = min(image.getWidth(), image.getHeight());
  return cutImageToCircle(image, w);
}

static BufferedImage cutImageToCircle(BufferedImage image, int w) {
  int h = w;
  image = img_getCenterPortion(image, w, w);
  BufferedImage output = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
  Graphics2D g2 = output.createGraphics();

  g2.setComposite(AlphaComposite.Src);
  g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  g2.setColor(Color.WHITE);
  g2.fill(new Ellipse2D.Float(0, 0, w, h));

  g2.setComposite(AlphaComposite.SrcAtop);
  g2.drawImage(image, 0, 0, null);
  g2.dispose();
  return output;
}
static boolean headless() {
  return isHeadless();
}
static <A extends Component> A setFrameSize(A c, int w, int h) {
  JFrame f = getFrame(c);
  if (f != null)
    f.setSize(w, h);
  return c;
}

static <A extends Component> A setFrameSize(int w, int h, A c) {
  return setFrameSize(c, w, h);
}
static boolean allLowerCaseCharacters(String s) {
  for (int i = 0; i < l(s); i++)
    if (Character.getType(s.charAt(i)) != Character.LOWERCASE_LETTER) return false;
  return true;
}
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 = str(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, text);
  return c;
}

static <A> A setText(final A c, Object text) {
  if (c == null) return null;
  final String s = str(text);
  swingAndWait(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;
}
// better modulo that gives positive numbers always
static int mod(int n, int m) {
  return (n % m + m) % m;
}
static String urlencode(String x) {
  try {
    return URLEncoder.encode(unnull(x), "UTF-8");
  } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); }
}
static <A extends JComponent> A focus(final A a) {
  swingLater(new Runnable() { public void run() { try {  a.requestFocus(); 
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "a.requestFocus();"; }});
  return a;
}
static double sqrt(double x) {
  return Math.sqrt(x);
}
static void swingLater(long delay, final Object r) {
  javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(r));
  timer.setRepeats(false);
  timer.start();
}

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

static void lock(Lock lock) { try {
  lock.lockInterruptibly();
} catch (Exception __e) { throw rethrow(__e); } }

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

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

static ReentrantLock lock() {
  return fairLock();
}
static String fsI(String id) {
  return formatSnippetID(id);
}

static String fsI(long id) {
  return formatSnippetID(id);
}
static JMenuItem jmenuItem(String text, final Object r) {
  JMenuItem mi = new JMenuItem(text);
  mi.addActionListener(actionListener(r));
  return mi;
}
static String defaultThreadName_name;

static String defaultThreadName() {
  if (defaultThreadName_name == null)
    defaultThreadName_name = "A thread by " + programID();
  return defaultThreadName_name;
}
static JButton jbutton(String text, Object action) {
  return newButton(text, action);
}

// button without action
static JButton jbutton(String text) {
  return newButton(text, null);
}

static JButton jbutton(BufferedImage img, Object action) {
  return setButtonImage(img, jbutton("", action));
}

static JButton jbutton(Action action) {
  return new JButton(action);
}
static int img_minOfWidthAndHeight(BufferedImage image) {
  return image == null ? 0 : min(image.getWidth(), image.getHeight());
}
static void swingNowOrLater(Runnable r) {
  if (isAWTThread())
    r.run();
  else
    swingLater(r);
}
static BufferedImage loadPNG(File file) {
  return loadBufferedImage(file);
}
// TODO: all the fringe cases (?)
static <A> JPanel hvgrid(List<List<A>> components) {
  if (empty(components)) return new JPanel();
  int h = l(components), w = l(first(components));
  JPanel panel = new JPanel();
  panel.setLayout(new GridLayout(h, w));
  for (List<A> row : components)
    smartAdd(panel, row);
  return panel;  
}

static <A> JPanel hvgrid(List<List<A>> components, int gap) {
  JPanel panel = hvgrid(components);
  GridLayout g = (GridLayout) ( panel.getLayout());
  g.setHgap(gap);
  g.setVgap(gap);
  return panel;
}
static Object pcallFunction(Object f, Object... args) {
  try { return callFunction(f, args); } catch (Throwable __e) { printStackTrace2(__e); }
  return null;
}
static <A> ArrayList<A> toList(A[] a) { return asList(a); }
static ArrayList<Integer> toList(int[] a) { return asList(a); }
static <A> ArrayList<A> toList(Set<A> s) { return asList(s); }
static <A> ArrayList<A> toList(Iterable<A> s) { return asList(s); }
// changes & returns canvas
static BufferedImage drawImageOnImage(BufferedImage img, BufferedImage canvas, int x, int y) {
  Graphics2D g = canvas.createGraphics();
  g.drawImage(img, x, y, null);
  g.dispose();
  return canvas;
}
static DoublePt blendDoublePts(DoublePt x, DoublePt y, double yish) {
  double xish = 1-yish;
  return new DoublePt(x.x*xish+y.x*yish, x.y*xish+y.y*yish);
}

static Font sansSerifBold(int fontSize) {
  return new Font(Font.SANS_SERIF, Font.BOLD, fontSize);
}
static JTextField onEnter(JTextField tf, final Object action) {
  if (action == null || tf == null) return tf;
  tf.addActionListener(actionListener(action));
  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(action));
  return list;
}

// editable only
static JComboBox onEnter(final JComboBox cb, final Object action) {
  JTextField text = (JTextField) cb.getEditor().getEditorComponent();
  /*onEnter(text, r {
    cb.hidePopup();
    pcallF(action);
  });*/
  onEnter(text, action);
  return cb;
}
static <A> A firstInstance(Collection c, Class<A> type) {
  return firstOfType(c, type);
}
static Throwable innerException(Throwable e) {
  return getInnerException(e);
}
static long sqr(long l) {
  return l*l;
}

static double sqr(double d) {
  return d*d;
}
static void setAll(Object o, Map<String, Object> fields) {
  if (fields == null) return;
  for (String field : keys(fields))
    set(o, field, fields.get(field));
}

static void setAll(Object o, Object... values) {
  //values = expandParams(c.getClass(), values);
  failIfOddCount(values);
  for (int i = 0; i+1 < l(values); i += 2) {
    String field = (String) values[i];
    Object value = values[i+1];
    set(o, field, value);
  }
}
static <A> A castOpt(Object o, Class<A> c) {
  return isInstance(c, o) ? (A) o : null;
}


static void drawTextWithOutline(Graphics2D g2, String text, float x, float y, Color fillColor, Color outlineColor) {
  BasicStroke outlineStroke = new BasicStroke(2.0f);

  g2.translate(x, y);

  // remember original settings
  Stroke originalStroke = g2.getStroke();
  RenderingHints originalHints = g2.getRenderingHints();

  // create a glyph vector from your text
  GlyphVector glyphVector = g2.getFont().createGlyphVector(g2.getFontRenderContext(), text);
  // get the shape object
  Shape textShape = glyphVector.getOutline();

  g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

  g2.setColor(outlineColor);
  g2.setStroke(outlineStroke);
  g2.draw(textShape); // draw outline

  g2.setColor(fillColor);
  g2.fill(textShape); // fill the shape

  // reset to original settings after painting
  g2.setStroke(originalStroke);
  g2.setRenderingHints(originalHints);
  
  g2.translate(-x, -y);
}


static float drawArrowHead_length = 2f;

static void drawArrowHead(Graphics2D g, double x1, double y1, double x2, double y2, double size) {
  if (y2 == y1 && x2 == x1) return;
  
  Path2D.Double arrowHead = new Path2D.Double();
  arrowHead.moveTo(0, 0);
  double l = drawArrowHead_length*size;
  arrowHead.lineTo(-size, -l);
  arrowHead.lineTo(size, -l);
  arrowHead.closePath();

  AffineTransform tx = new AffineTransform();
  double angle = Math.atan2(y2-y1, x2-x1);
  tx.translate(x2, y2);
  tx.rotate(angle-Math.PI/2d);

  AffineTransform old = g.getTransform();
  g.setTransform(tx);
  g.fill(arrowHead);
  g.setTransform(old);
}


static Font typeWriterFont() {
  return typeWriterFont(14);
}
  
static Font typeWriterFont(int size) {
  return new Font("Courier", Font.PLAIN, size);
}
static <A extends Window> A disposeWindowAfter(int delay, final A w) {
  if (w != null)
    swingLater(delay, new Runnable() { public void run() { try { 
      w.dispose();
    
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "w.dispose();"; }});
  return w;
}
static JTextArea wrappedTextArea(JTextArea ta) {
  ta.setLineWrap(true);
  ta.setWrapStyleWord(true);
  return ta;
}

static JTextArea wrappedTextArea() {
  return wrappedTextArea(jtextarea());
}

static JTextArea wrappedTextArea(String text) {
  JTextArea ta = wrappedTextArea();
  ta.setText(text);
  return ta;
}
static ActionListener actionListener(final Object runnable) {
  if (runnable instanceof ActionListener) return (ActionListener) runnable;
  return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { pcallF(runnable); }};
}
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);
    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);
    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() & 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 Graphics2D antiAliasGraphics(BufferedImage img) {
  Graphics2D g = (Graphics2D) ( img.getGraphics());
  g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
  g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  return g;
}
static float abs(float f) { return Math.abs(f); }
static int abs(int i) { return Math.abs(i); }
static double abs(double d) { return Math.abs(d); }
// c = JComponent or something implementing swing()
static JComponent wrap(Object swingable) {
  if (swingable == null) return null;
  JComponent c = (JComponent) ( swingable instanceof JComponent ? swingable : callOpt(swingable, "swing"));
  if (c instanceof JTable || c instanceof JList
    || c instanceof JTextArea || c instanceof JEditorPane
    || c instanceof JTextPane || c instanceof JTree)
    return jscroll(c);
  return c;
}

static boolean hasMethod(Object o, String method, Object... args) {
  return findMethod(o, method, args) != null;
}
static KeyListener enterKeyListener(final Object action) {
  return new KeyAdapter() {
    public void keyReleased(KeyEvent ke) {
      if (ke.getKeyCode() == KeyEvent.VK_ENTER)
        pcallF(action);
    }
  };
}
static int isqrt(double x) {
  return iround(Math.sqrt(x));
}
static Runnable _topLevelErrorHandling(final Runnable runnable) {
  return new Runnable() { public void run() { try {  try { runnable.run(); } catch (Throwable __e) { printStackTrace2(__e); } 
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "pcall { runnable.run(); }"; }};
}
static JFrame consoleFrame() {
  return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
}


static void bindTimerToComponent(final Timer timer, JFrame f) {
  bindTimerToComponent(timer, f.getRootPane());
}

static void bindTimerToComponent(final Timer timer, JComponent c) {
  if (c.isShowing())
    timer.start();
  
  c.addAncestorListener(new AncestorListener() {
    public void ancestorAdded(AncestorEvent event) {
      timer.start();
    }

    public void ancestorRemoved(AncestorEvent event) {
      timer.stop();
    }

    public void ancestorMoved(AncestorEvent event) {
    }
  });
}
static <A extends Component> A setFrameTitle(A c, String title) {
  JFrame f = getFrame(c);
  if (f == null)
    showFrame(title, c);
  else
    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 JFrame showFrame() {
  return makeFrame();
}

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

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

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

static JFrame showFrame(final JFrame frame) {
  if (frame != null) { swing(new Runnable() { public void run() { try { 
    if (frameTooSmall(frame)) frameStandardSize(frame);
    frame.setVisible(true);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (frameTooSmall(frame)) frameStandardSize(frame);\r\n    frame.setVisible(true);"; }}); }
  return frame;
}

// make or update frame
static JFrame showFrame(String title, Object content, JFrame frame) {
  if (frame == null)
    return showFrame(title, content);
  else {
    frame.setTitle(title);
    setFrameContents(frame, content);
    return frame;
  }
}
static String f2s(File f) {
  return f == null ? null : f.getAbsolutePath();
}
static String programTitle() {
  return getProgramName();
}
static void onClick(JComponent c, final Object runnable) {
  c.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
      callF(runnable, e);
    }
  });
}

// re-interpreted for buttons
static void onClick(JButton btn, final Object runnable) {
  onEnter(btn, runnable);
}


static <A extends JTextComponent> A jenableUndoRedo(A textcomp) {
  final UndoManager undo = new UndoManager();
  textcomp.getDocument().addUndoableEditListener(new UndoableEditListener() {
    public void undoableEditHappened(UndoableEditEvent evt) {
      undo.addEdit(evt.getEdit());
    }
  });
  
  textcomp.getActionMap().put("Undo", abstractAction("Undo", new Runnable() { public void run() { try { 
    if (undo.canUndo()) undo.undo()
  ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (undo.canUndo()) undo.undo()"; }}));
  textcomp.getActionMap().put("Redo", abstractAction("Redo", new Runnable() { public void run() { try { 
    if (undo.canRedo()) undo.redo()
  ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (undo.canRedo()) undo.redo()"; }}));
  textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
  textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
  return textcomp;
}
static JButton setButtonImage(BufferedImage img, JButton btn) {
  btn.setIcon(imageIcon(img));
  return btn;
}
static JWindow showWindow(Component c) {
  JWindow w = new JWindow();
  w.add(wrap(c));
  return w;
}
static <A> void scanForComponents(Component c, Class<A> theClass, List<A> l) {
  if (theClass.isInstance(c))
    l.add((A) c);
  if (c instanceof Container)
  for (Component comp : ((Container) c).getComponents())
    scanForComponents(comp, theClass, l);
}
static String nullIfEmpty(String s) {
  return isEmpty(s) ? null : s;
}
public static File mkdirsFor(File file) {
  return mkdirsForFile(file);
}

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;
}
// can probably be merged with next variant
static void disposeWindow(final Window window) {
  if (window != null) { swing(new Runnable() { public void run() { try { 
    window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); // call listeners
    window.dispose();
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); // ca..."; }}); }
}

static void disposeWindow(final Component c) {
  disposeWindow(getWindow(c));
}

static void disposeWindow(Object o) {
  if (o != null) disposeWindow((Component) o);
}
static double pi() {
  return Math.PI;
}
static int moveToTopRightCorner_inset = 20;

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

static boolean isInstance(Class type, Object arg) {
  return type.isInstance(arg);
}
static boolean isURL(String s) {
  return s.startsWith("http://") || s.startsWith("https://");
}
static JPanel smartAdd(JPanel panel, List parts) {
  for (Object o : parts)
    addToContainer(panel, wrapForSmartAdd(o));
  return panel;
}

static JPanel smartAdd(JPanel panel, Object... parts) {
  return smartAdd(panel, asList(parts));
}

static boolean allPaused() {
  return ping_pauseAll;
}
static BufferedImage createBufferedImage(int w, int h, Color color) {
  return newBufferedImage(w, h, color);
}
static <A> A firstOfType(Collection c, Class<A> type) {
  for (Object x : c)
    if (isInstanceX(type, x))
      return (A) x;
  return null;
}
static String strOrEmpty(Object o) {
  return o == null ? "" : str(o);
}
static void lockOrFail(Lock lock, long timeout) { try {
  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);
  }
} catch (Exception __e) { throw rethrow(__e); } }
static JScrollPane jscroll(final Component c) {
  return swing(new F0<JScrollPane>() { JScrollPane get() { try { return  new JScrollPane(c) ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "new JScrollPane(c)"; }});
}
static void failIfOddCount(Object... list) {
  if (odd(l(list)))
    throw fail("Odd list size: " + list);
}
static String snippetImageURL(String snippetID) {
  return snippetImageURL(snippetID, "png");
}

static String snippetImageURL(String snippetID, String contentType) {
  long id = parseSnippetID(snippetID);
  String url;
  if (id == 1000010 || id == 1000012)
    url = "http://tinybrain.de:8080/tb/show-blobimage.php?id=" + id;
  else if (isImageServerSnippet(id))
    url = "http://ai1.lol/images/raw/" + id;
  else
    url = "http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + id
      + "&contentType=image/" + contentType;
  return url;
}
static void standardTitlePopupMenu(final JFrame frame) {
  // standard right-click behavior on titles
  if (isSubstanceLAF())
    titlePopupMenu(frame,
      new Object() { void get(JPopupMenu menu) { try { 
        boolean alwaysOnTop = frame.isAlwaysOnTop();
        menu.add(jmenuItem("Restart Program", "restart"));
        menu.add(jmenuItem("Duplicate Program", "duplicateThisProgram"));
        menu.add(jmenuItem("Show Console", "showConsole"));
        menu.add(jCheckBoxMenuItem("Always On Top", alwaysOnTop, new Runnable() { public void run() { try { 
          toggleAlwaysOnTop(frame) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "toggleAlwaysOnTop(frame)"; }}));
        menu.add(jMenuItem("Shoot Window", new Runnable() { public void run() { try {  shootWindowGUI_external(frame, 500) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "shootWindowGUI_external(frame, 500)"; }}));
       } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "bool alwaysOnTop = frame.isAlwaysOnTop();\r\n        menu.add(jmenuItem(\"Restart P..."; }});
}

static Set<String> fieldNames(Object o) {
  return allFields(o);
}
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 int packFrame_minw = 150, packFrame_minh = 50;

static <A extends Component> A packFrame(final A c) {
  { swing(new Runnable() { public void run() { try { 
    JFrame frame = getFrame(c);
    if (frame != null) {
      frame.pack();
      int maxW = getScreenWidth()-50, maxH = getScreenHeight()-50;
      frame.setSize(
        min(maxW, max(frame.getWidth(), packFrame_minw)),
        min(maxH, max(frame.getHeight(), packFrame_minh)));
    }
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "JFrame frame = getFrame(c);\r\n    if (frame != null) {\r\n      frame.pack();\r\n    ..."; }}); }
  return c;
}

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

static File getCacheProgramDir(String snippetID) {
  return new File(userHome(), "JavaX-Caches/" + formatSnippetIDOpt(snippetID));
}
static boolean isUpperCase(char c) {
  return Character.isUpperCase(c);
}
static BufferedImage img_getCenterPortion(BufferedImage img, int w, int h) {
  int iw = img.getWidth(), ih = img.getHeight();
  if (iw < w || ih < h) throw fail("Too small");
  int x = (iw-w)/2, y = (ih-h)/2;
  return clipBufferedImage(img, x, y, w, h);
}
// action can be Runnable or a function name
static JButton newButton(final String text, final Object action) {
  return swing(new F0<JButton>() { JButton get() { try { 
    JButton btn = new JButton(text);
    if (action != null)
      btn.addActionListener(actionListener(action));
    return btn;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "JButton btn = new JButton(text);\r\n    if (action != null)\r\n      btn.addActionLi..."; }});
}
static BufferedImage toBufferedImageOpt(Object o) {
  if (o instanceof BufferedImage) return (BufferedImage) o;
  String c = getClassName(o);
  if (eqOneOf(c, "main$BWImage", "main$RGBImage"))
    return (BufferedImage) call(o, "getBufferedImage");
  if (eq(c, "main$PNGFile"))
    return (BufferedImage) call(o, "getImage");
  return null;
}
// o is either a map already (string->object) or an arbitrary object,
// in which case its fields are converted into a map.
static Map<String, Object> objectToMap(Object o) { try {
  if (o instanceof Map) return (Map) o;
  
  TreeMap<String,Object> map = new TreeMap();
  Class c = o.getClass();
  while (c != Object.class) {
    Field[] fields = c.getDeclaredFields();
    for (final Field field : fields) {
      if ((field.getModifiers() & Modifier.STATIC) != 0)
        continue;
      field.setAccessible(true);
      final Object value = field.get(o);
      if (value != null)
        map.put(field.getName(), value);
    }
    c = c.getSuperclass();
  }
  return map;
} catch (Exception __e) { throw rethrow(__e); } }

// same for a collection (convert each element)
static List<Map<String, Object>> objectToMap(Collection l) {
  List x = new ArrayList();
  for (Object o : l)
    x.add(objectToMap(o));
  return x;
}
static <A> A restructure(A a) {
  return (A) unstructure(structure(a));
}
static Class hotwireOnce(String programID) {
  return hotwireCached(programID, false);
}


static TreeMap<String,Class> hotwireCached_cache = new TreeMap();
static Lock hotwireCached_lock = lock();

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

static Class hotwireCached(String programID, boolean runMain) {
  Lock _lock_1032 = hotwireCached_lock; lock(_lock_1032); try {
  
  programID = formatSnippetID(programID);
  Class c = hotwireCached_cache.get(programID);
  if (c == null) {
    c = hotwire(programID);
    if (runMain)
      callMain(c);
    hotwireCached_cache.put(programID, c);
  }
  return c;
} finally { _lock_1032.unlock(); } }
static boolean isImageServerSnippet(long id) {
  return id >= 1100000 && id < 1200000;
}
// menuMaker = voidfunc(JPopupMenu)
static void titlePopupMenu(final Component c, final Object menuMaker) {
  swingNowOrLater(new Runnable() { public void run() { try { 
    if (!isSubstanceLAF())
      print("Can't add title right click!");
    else {
      JComponent titleBar = getTitlePaneComponent(getFrame(c));
      componentPopupMenu(titleBar, menuMaker);
    }
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (!isSubstanceLAF())\r\n      print(\"Can't add title right click!\");\r\n    else {..."; }});
}
static void duplicateThisProgram() {
  nohupJavax(trim(programID() + " " + smartJoin((String[]) get(getJavaX(), "fullArgs"))));
}
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 void frameStandardSize(JFrame frame) {
  frame.setBounds(300, 100, 500, 400);
}
  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 boolean isSubstanceLAF() {
  return substanceLookAndFeelEnabled();
}
static JTextArea jtextarea() {
  return jTextArea();
}

static JTextArea jtextarea(String text) {
  return jTextArea(text);
}
static int getScreenWidth() {
  return getScreenSize().width;
}
static JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, final Object r) {
  JCheckBoxMenuItem mi = new JCheckBoxMenuItem(text, checked);
  mi.addActionListener(actionListener(r));
  return mi;
}
static void shootWindowGUI_external(JFrame frame) {
  call(hotwireOnce("#1007178"), "shootWindowGUI", frame);
}

static void shootWindowGUI_external(final JFrame frame, int delay) {
  call(hotwireOnce("#1007178"), "shootWindowGUI", frame, delay);
}

static void setFrameContents(Component c, Object contents) {
  JFrame frame = getFrame(c);
  frame.getContentPane().removeAll();
  frame.getContentPane().add(wrap(contents));
  revalidate(frame);
}
static int getScreenHeight() {
  return getScreenSize().height;
}
static boolean frameTooSmall(JFrame frame) {
  return frame.getWidth() < 100 || frame.getHeight() < 50;
}
static BufferedImage clipBufferedImage(BufferedImage src, Rectangle clip) {
  return src.getSubimage(clip.x, clip.y, clip.width, clip.height);
}

static BufferedImage clipBufferedImage(BufferedImage src, Rect clip) {
  return clipBufferedImage(src, clip.getRectangle());
}

static BufferedImage clipBufferedImage(BufferedImage src, int x, int y, int w, int h) {
  return src.getSubimage(x, y, w, h);
}

static Component wrapForSmartAdd(Object o) {
  if (o == null) return new JPanel();
  if (o instanceof String) return jlabel((String) o);
  return wrap(o);
}
static void restart() {
  Object j = getJavaX();
  call(j, "cleanRestart", get(j, "fullArgs"));
}
static void addToContainer(Container a, Component b) {
  if (a != null && b != null) a.add(b);
}
static JMenuItem jMenuItem(String text, Object r) {
  return jmenuItem(text, r);
}
static AbstractAction abstractAction(String name, final Object runnable) {
  return new AbstractAction(name) {
    public void actionPerformed(ActionEvent evt) {
      pcallF(runnable);
    }
  };
}
static void toggleAlwaysOnTop(JFrame frame) {
  frame.setAlwaysOnTop(!frame.isAlwaysOnTop());
}
static ImageIcon imageIcon(String imageID) { try {
  return new ImageIcon(loadBinarySnippet(imageID).toURI().toURL());
} catch (Exception __e) { throw rethrow(__e); } }

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


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

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

static synchronized String getProgramName() {
  if (getProgramName_cache == null)
    getProgramName_cache = getSnippetTitleOpt(programID());
  return getProgramName_cache;
}


static JComponent getTitlePaneComponent(Window window) {
  if (!substanceLookAndFeelEnabled()) return null;
  
	JRootPane rootPane = null;
	if (window instanceof JFrame)
		rootPane = ((JFrame) window).getRootPane();
	if (window instanceof JDialog)
		rootPane = ((JDialog) window).getRootPane();
	if (rootPane != null) {
		Object /*SubstanceRootPaneUI*/ ui = rootPane.getUI();
		return (JComponent) call(ui, "getTitlePane");
	}
	return null;
}

static <A> A callMain(A c, String... args) {
  callOpt(c, "main", new Object[] {args});
  return c;
}

static void callMain() {
  callMain(mc());
}
static void nohupJavax(final String javaxargs) {
  { Thread _t_0 = new Thread() {
public void run() { try { call(hotwireOnce("#1008562"), "nohupJavax", javaxargs); } catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_0); }
}

static void nohupJavax(final String javaxargs, final String vmArgs) {
  { Thread _t_1 = new Thread() {
public void run() { try { call(hotwireOnce("#1008562"), "nohupJavax", javaxargs, vmArgs); } catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_1); }
}
static JTextArea jTextArea() {
  return jTextArea("");
}

static JTextArea jTextArea(final String text) {
  return swing(new F0<JTextArea>() { JTextArea get() { try { return  new JTextArea(text) ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "new JTextArea(text)"; }});
}
static File loadBinarySnippet(String snippetID) { try {
  long id = parseSnippetID(snippetID);
  File f = DiskSnippetCache_getLibrary(id);
  if (fileSize(f) == 0)
    f = loadDataSnippetToFile(snippetID);
  return f;
} catch (Exception __e) { throw rethrow(__e); } }
static String getSnippetTitleOpt(String s) {
  return isSnippetID(s) ? getSnippetTitle(s) : s;
}
static boolean substanceLookAndFeelEnabled() {
  return startsWith(getLookAndFeel(), "org.pushingpixels.");
}
// Try to get the quoting right...

static String smartJoin(String[] args) {
  if (args.length == 1) return args[0];
  
  String[] a = new String[args.length];
  for (int i = 0; i < a.length; i++)
    a[i] = !isJavaIdentifier(args[i]) && !isQuoted(args[i]) ? quote(args[i]) : args[i];
  return join(" ", a);
}

static String smartJoin(List<String> args) {
  return smartJoin(toStringArray(args));
}
static 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 {
    // ret hotwire_overInternalBot(src);
    Class c = (Class) ( call(j, "hotwire", src));
    hotwire_copyOver(c);
    return c;
  }
}


// supports the usual quotings (', ", variable length double brackets)
static boolean isQuoted(String s) {
  if (startsWith(s, "'") || startsWith(s, "\"")) return true;
  return isMultilineQuoted(s);
}
static boolean _inCore() {
  return false;
}
static String getSnippetTitle(String id) { try {
  if (id == null) return null;
  if (!isSnippetID(id)) return "?";
  long parsedID = parseSnippetID(id);
  String url;
  if (isImageServerSnippet(parsedID))
    url = "http://ai1.lol/images/raw/title/" + parsedID;
  else
    url = tb_mainServer() + "/tb-int/getfield.php?id=" + parsedID + "&field=title" + standardCredentials();
  return trim(loadPageSilently(url));
} catch (Exception __e) { throw rethrow(__e); } }

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

static String getLookAndFeel() {
  return getClassName(UIManager.getLookAndFeel());
}
static String[] toStringArray(Collection<String> c) {
  String[] a = new String[l(c)];
  Iterator<String> it = c.iterator();
  for (int i = 0; i < l(a); i++)
    a[i] = it.next();
  return a;
}

static String[] toStringArray(Object o) {
  if (o instanceof String[])
    return (String[]) o;
  else if (o instanceof Collection)
    return toStringArray((Collection<String>) o);
  else
    throw fail("Not a collection or array: " + getClassName(o));
}

static File loadDataSnippetToFile(String snippetID) { try {
  File f = DiskSnippetCache_file(parseSnippetID(snippetID));
  try {
    URL url = new URL(dataSnippetLink(snippetID));
    System.err.println("Loading library: " + hideCredentials(url));
    try {
      loadBinaryPageToFile(openConnection(url), f);
      if (fileSize(f) == 0) throw fail();
    } catch (Throwable _e) {
      url = new URL("http://data.tinybrain.de/blobs/"
        + parseSnippetID(snippetID));
      loadBinaryPageToFile(openConnection(url), f);
    }
    // TODO: check if we hit the "LOADING" message
    if (fileSize(f) == 0) throw fail();
    System.err.println("Bytes loaded: " + fileSize(f));
  } catch (Throwable e) {
    printStackTrace(e);
    throw fail("Binary snippet #" + snippetID + " not found or not public");
  }
  return f;
} catch (Exception __e) { throw rethrow(__e); } }
static File DiskSnippetCache_file(long snippetID) {
  return new File(getGlobalCache(), "data_" + snippetID + ".jar");
}
  
  // Data files are immutable, use centralized cache
public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
  File file = DiskSnippetCache_file(snippetID);
  return file.exists() ? file : null;
}

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

static byte[] loadDataSnippetImpl(String snippetID) throws IOException {
  byte[] data;
  try {
    URL url = new URL("http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_"
      + parseSnippetID(snippetID) + "&contentType=application/binary");
    System.err.println("Loading library: " + url);
    try {
      data = loadBinaryPage(url.openConnection());
    } catch (RuntimeException e) {
      data = null;
    }
    
    if (data == null || data.length == 0) {
      url = new URL("http://data.tinybrain.de/blobs/"
        + parseSnippetID(snippetID));
      System.err.println("Loading library: " + url);
      data = loadBinaryPage(url.openConnection());
    }
    System.err.println("Bytes loaded: " + data.length);
  } catch (FileNotFoundException e) {
    throw new IOException("Binary snippet #" + snippetID + " not found or not public");
  }
  return data;
}
static void hotwire_copyOver(Class c) {
  synchronized(StringBuffer.class) {
    for (String field : litlist("print_log", "print_silent", "androidContext")) {
      Object o = getOpt(mc(), field);
      if (o != null)
        setOpt(c, field, o);
    }
      
    Object mainBot = getMainBot();
    if (mainBot != null)
      setOpt(c, "mainBot", mainBot);

    setOpt(c, "creator_class", new WeakReference(mc()));
  }
}
static long fileSize(String path) { return getFileSize(path); }
static long fileSize(File f) { return getFileSize(f); }



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

    if (!new File(tempFileName).renameTo(file))
      throw new IOException("Can't rename " + tempFileName + " to " + fileName);
  }

  static void saveBinaryFile(File fileName, byte[] contents) {
    try {
      saveBinaryFile(fileName.getPath(), contents);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
static String dataSnippetLink(String snippetID) {
  long id = parseSnippetID(snippetID);
  if (id >= 1200000 && id < 1300000) {
    String pw = muricaPassword();
    if (empty(pw)) throw fail("Please set 'murica password by running #1008829");
    return "http://ai1.lol/1008823/raw/" + id + "?_pass=" + pw; // XXX, although it typically gets hidden when printing
  } else
    return "http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_"
      + id + "&contentType=application/binary";
}
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 void loadBinaryPageToFile(String url, File file) { try {
  print("Loading " + url);
  loadBinaryPageToFile(openConnection(new URL(url)), file);
} catch (Exception __e) { throw rethrow(__e); } }

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

static void loadBinaryPageToFile_noHeaders(URLConnection con, File file) { try {
  File ftemp = new File(f2s(file) + "_temp");
  FileOutputStream buf = newFileOutputStream(mkdirsFor(ftemp));
  InputStream inputStream = con.getInputStream();
  try {
    long len = 0;
    try { len = con.getContentLengthLong(); } catch (Throwable e) { printStackTrace(e); }
    int n = 0;
    while (true) {
      int ch = inputStream.read();
      if (ch < 0)
        break;
      buf.write(ch);
      if (++n % 100000 == 0)
        println("  " + n + (len != 0 ? "/" + len : "") + " bytes loaded.");
    }
    buf.close();
    buf = null;
    file.delete();
    ftemp.renameTo(file);
    inputStream.close();
  } finally {
    if (buf != null) buf.close();
  }
} catch (Exception __e) { throw rethrow(__e); } }

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

static byte[] loadBinaryPage(URLConnection con) { try {
  setHeaders(con);
  return loadBinaryPage_noHeaders(con);
} catch (Exception __e) { throw rethrow(__e); } }

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

static String standardCredentials() {
  String user = standardCredentialsUser();
  String pass = standardCredentialsPass();
  if (nempty(user) && nempty(pass))
    return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
  return "";
}
static Object mainBot;

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

static boolean isMultilineQuoted(String s) {
  if (!startsWith(s, "[")) return false;
  int i = 1;
  while (i < s.length() && s.charAt(i) == '=') ++i;
  return i < s.length() && s.charAt(i) == '[';
}


static <A> A println(A a) {
  return print(a);
}
static String muricaPassword() {
  return trim(loadTextFile(muricaPasswordFile()));
}
static String standardCredentialsUser() {
  return trim(loadTextFile(new File(userHome(), ".tinybrain/username")));
}
static File javaxCachesDir_dir; // can be set to work on different base dir

static File javaxCachesDir() {
  return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches");
}
static String standardCredentialsPass() {
  return trim(loadTextFile(new File(userHome(), ".tinybrain/userpass")));
}


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


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

static File javaxSecretDir() {
  return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret");
}


static interface IVar<A> {
  void set(A a);
  A get();
  boolean has();
  void clear();
}

static class DoublePt {
  double x, y;
  
  DoublePt() {}
  DoublePt(Point p) {
    x = p.x;
    y = p.y;
  }
  DoublePt(double x, double y) {
  this.y = y;
  this.x = x;}
  
  public boolean equals(Object o) { return stdEq2(this, o); }
public int hashCode() { return stdHash2(this); }
  
  public String toString() {
    return x + ", " + y;
  }
}

static class AutoComboBox extends JComboBox<Object> {
  String keyWord[] = {"item1", "item2", "item3"};
  Vector myVector = new Vector();
  
  public AutoComboBox() {
      setModel(new DefaultComboBoxModel(myVector));
      setSelectedIndex(-1);
      setEditable(true);
      JTextField text = (JTextField) this.getEditor().getEditorComponent();
      text.setFocusable(true);
      text.setText("");
      text.addKeyListener(new ComboListener(this, myVector));
      setMyVector();
  }
  
  /**
   * set the item list of the AutoComboBox
   * @param keyWord an String array
   */
  void setKeyWord(String[] keyWord) {
      this.keyWord = keyWord;
      setMyVector();
  }
  
  void setKeyWord(Collection<String> keyWord) {
    setKeyWord(toStringArray(keyWord));
  }
  
  private void setMyVector() {
    copyArrayToVector(keyWord, myVector);
  }
}

static class ComboListener extends KeyAdapter {
  JComboBox cbListener;
  Vector vector;
  
  public ComboListener(JComboBox cbListenerParam, Vector vectorParam)
  {
      cbListener = cbListenerParam;
      vector = vectorParam;
  }
  
  public void keyReleased(KeyEvent key)
  {
    if (key.getKeyCode() == KeyEvent.VK_ENTER) return;
    
    JTextField tf = (JTextField) ( cbListener.getEditor().getEditorComponent());
    
    if (tf.getCaretPosition() != l(tf.getText())) return;
    
    String text = ((JTextField)key.getSource()).getText();

    cbListener.setModel(new DefaultComboBoxModel(getFilteredList(text)));
    cbListener.setSelectedIndex(-1);
    tf.setText(text);
    cbListener.showPopup();
  }
  
  
  public Vector getFilteredList(String text)
  {
      return new Vector(scoredSearch(text, vector));
  }
}

static class Lowest<A> {
  A best;
  double score;
  transient Object onChange;
  
  boolean isNewBest(double score) {
    return best == null || score < this.score;
  }
  
  double bestScore() {
    return best == null ? Double.NaN : score;
  }
  
  float floatScore() {
    return best == null ? Float.NaN : (float) score;
  }
  
  float floatScoreOr(float defaultValue) {
    return best == null ? defaultValue : (float) score;
  }
  
  boolean put(A a, double score) {
    if (a != null && isNewBest(score)) {
      best = a;
      this.score = score;
      pcallF(onChange);
      return true;
    }
    return false;
  }
  
  A get() { return best; }
  boolean has() { return best != null; }
}

static class Pt {
  int x, y;
  
  Pt() {}
  Pt(Point p) {
    x = p.x;
    y = p.y;
  }
  Pt(int x, int y) {
  this.y = y;
  this.x = x;}
  
  Point getPoint() {
    return new Point(x, y);
  }
  
  public boolean equals(Object o) { return stdEq2(this, o); }
public int hashCode() { return stdHash2(this); }
  
  public String toString() {
    return x + ", " + y;
  }
}

static class ImageSurfaceSelector extends MouseAdapter {
  ImageSurface is;
  Point startingPoint;
  boolean enabled = true;
  static boolean verbose = false;

  ImageSurfaceSelector(ImageSurface is) {
  this.is = is;
    if (containsInstance(is.tools, ImageSurfaceSelector.class)) return;
    is.tools.add(this);
    is.addMouseListener(this);
    is.addMouseMotionListener(this);
  }

  public void mousePressed(MouseEvent evt) {
    if (verbose) print("mousePressed");
    if (evt.getButton() != MouseEvent.BUTTON1) return;
    if (enabled)
      startingPoint = getPoint(evt);
  }

  public void mouseDragged(MouseEvent e) {
    if (verbose) print("mouseDragged");
    if (startingPoint != null) {
      Point endPoint = getPoint(e);
      Rectangle r = new Rectangle(startingPoint, new Dimension(endPoint.x-startingPoint.x+1, endPoint.y-startingPoint.y+1));
      normalize(r);
      r.width = min(r.width, is.getImage().getWidth()-r.x);
      r.height = min(r.height, is.getImage().getHeight()-r.y);
      is.setSelection(r);
    }
    if (verbose) print("mouseDragged done");
  }

  public static void normalize(Rectangle r) {
    if (r.width < 0) {
      r.x += r.width;
      r.width = -r.width;
    }
    if (r.height < 0) {
      r.y += r.height;
      r.height = -r.height;
    }
  }

  public void mouseReleased(MouseEvent e) {
    if (verbose) print("mouseReleased");
    mouseDragged(e);
    if (getPoint(e).equals(startingPoint))
      is.setSelection(null);
    startingPoint = null;
  }
  
  Point getPoint(MouseEvent e) {
    return new Point((int) (e.getX()/is.getZoomX()), (int) (e.getY()/is.getZoomY()));
  }
}

static class Rect {
  int x, y, w, h;
  
  Rect() {}
  Rect(Rectangle r) {
    x = r.x;
    y = r.y;
    w = r.width;
    h = r.height;
  }
  Rect(int x, int y, int w, int h) {
  this.h = h;
  this.w = w;
  this.y = y;
  this.x = x;}
  
  Rectangle getRectangle() {
    return new Rectangle(x, y, w, h);
  }
  
  public boolean equals(Object o) { return stdEq2(this, o); }
public int hashCode() { return stdHash2(this); }
  
  public String toString() {
    return x + "," + y + " / " + w + "," + h;
  }
  
  int x2() { return x + w; }
  int y2() { return y + h; }
  
  boolean contains(Pt p) {
    return contains(p.x, p.y);
  }
  
  boolean contains(int _x, int _y) {
    return _x >= x && _y >= y && _x < x+w && _y < y+h;
  }
  
  boolean empty() { return w <= 0 || h <= 0; }
}

static class ImageSurface extends Surface {
  private BufferedImage image;
  private double zoomX = 1, zoomY = 1;
  private Rectangle selection;
  List tools = new ArrayList();
  Object overlay; // voidfunc(Graphics2D)
  Runnable onSelectionChange;
  static boolean verbose;
  boolean noMinimumSize = true;
  String titleForUpload;
  Object onZoom;
  boolean specialPurposed; // true = don't show image changing commands in popup menu

  public ImageSurface() {
    this(dummyImage());
  }
  
  static BufferedImage dummyImage() {
    return new RGBImage(1, 1, new int[] { 0xFFFFFF }).getBufferedImage();
  }

  public ImageSurface(RGBImage image) {
    this(image != null ? image.getBufferedImage() : dummyImage());
  }

  public ImageSurface(BufferedImage image) {
    setImage(image);
    clearSurface = false;

    componentPopupMenu(this, new Object() { void get(JPopupMenu menu) { try { 
      Point p = pointFromEvent(componentPopupMenu_mouseEvent.get()).getPoint();
      fillPopupMenu(menu, p);
     } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "Point p = pointFromEvent(componentPopupMenu_mouseEvent.get()).getPoint();\r\n     ..."; }});
    
    new ImageSurfaceSelector(this);
    
    jHandleFileDrop(this, new Object() { void get(File f) { try {  setImage(loadBufferedImage(f)) ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "setImage(loadBufferedImage(f))"; }});
  }

  public ImageSurface(RGBImage image, double zoom) {
    this(image);
    setZoom(zoom);
  }

  // point is already in image coordinates
  protected void fillPopupMenu(JPopupMenu menu, final Point point) {
    JMenuItem miZoomReset = new JMenuItem("Zoom 100%");
    miZoomReset.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        setZoom(1.0);
        centerPoint(point);
      }
    });
    menu.add(miZoomReset);

    JMenuItem miZoomIn = new JMenuItem("Zoom in");
    miZoomIn.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        zoomIn(2.0);
        centerPoint(point);
      }
    });
    menu.add(miZoomIn);

    JMenuItem miZoomOut = new JMenuItem("Zoom out");
    miZoomOut.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        zoomOut(2.0);
        centerPoint(point);
      }
    });
    menu.add(miZoomOut);

    JMenuItem miZoomToWindow = new JMenuItem("Zoom to window");
    miZoomToWindow.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        zoomToDisplaySize();
      }
    });
    menu.add(miZoomToWindow);
    addMenuItem(menu, "Show full screen", new Runnable() { public void run() { try {  showFullScreen() ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "showFullScreen()"; }});
    
    addMenuItem(menu, "Point: " + point.x + "," + point.y + " (image: " + image.getWidth() + "*" + image.getHeight() + ")", null);

    menu.addSeparator();

    addMenuItem(menu, "Save image...", new Runnable() { public void run() { try {  saveImage() ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "saveImage()"; }});
    addMenuItem(menu, "Upload image...", new Runnable() { public void run() { try {  uploadTheImage() ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "uploadTheImage()"; }});
    addMenuItem(menu, "Copy image to clipboard", new Runnable() { public void run() { try {  copyImageToClipboard(getImage()) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "copyImageToClipboard(getImage())"; }});
    if (!specialPurposed)
      addMenuItem(menu, "Paste image from clipboard", new Runnable() { public void run() { try {  loadFromClipboard() ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "loadFromClipboard()"; }});
    if (selection != null)
      addMenuItem(menu, "Crop", new Runnable() { public void run() { try {  crop() ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "crop()"; }});
    if (!specialPurposed)
      addMenuItem(menu, "No image", new Runnable() { public void run() { try {  noImage() ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "noImage()"; }});
  }
  
  void noImage() { setImage((BufferedImage) null); }
  
  void crop() {
    if (selection == null) return;
    BufferedImage img = clipBufferedImage(getImage(), selection);
    selection = null;
    setImage(img);
  }
  
  void loadFromClipboard() {
    BufferedImage img = getImageFromClipboard();
    if (img != null)
      setImage(img);
  }

  void saveImage() {
    RGBImage image = new RGBImage(getImage(), null);
    JFileChooser fileChooser = new JFileChooser(getProgramDir());
    if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
      try {
        image.save(fileChooser.getSelectedFile());
      } catch (IOException e) {
        popup(e);
      }
    }
  }

  public void render(int w, int h, Graphics2D g) {
    if (verbose) main.print("render");
    g.setColor(Color.white);
    if (image == null)
      g.fillRect(0, 0, w, h);
    else {
      int iw = getZoomedWidth(), ih = getZoomedHeight();
      boolean alpha = hasTransparency(image);
      if (alpha) g.fillRect(0, 0, w, h);
      g.drawImage(image, 0, 0, iw, ih, null);
      if (!alpha) {
        g.fillRect(iw, 0, w-iw, h);
        g.fillRect(0, ih, iw, h-ih);
      }
    }

    if (verbose) main.print("render overlay");
    if (overlay != null) pcallF(overlay, g);

    if (verbose) main.print("render selection");
    if (selection != null) {
      // drawRect is inclusive, selection is exclusive, so... whatever, tests show it's cool.
      drawSelectionRect(g, selection, Color.green, Color.white);
    }
  }

  public void drawSelectionRect(Graphics2D g, Rectangle selection, Color green, Color white) {
    g.setColor(green);
    int top = (int) (selection.y * zoomY);
    int bottom = (int) ((selection.y+selection.height) * zoomY);
    int left = (int) (selection.x * zoomX);
    int right = (int) ((selection.x+selection.width) * zoomX);
    g.drawRect(left-1, top-1, right-left+1, bottom-top+1);
    g.setColor(white);
    g.drawRect(left - 2, top - 2, right - left + 3, bottom - top + 3);
  }

  public void setZoom(double zoom) {
    setZoom(zoom, zoom);
  }

  public void setZoom(double zoomX, double zoomY) {
    this.zoomX = zoomX;
    this.zoomY = zoomY;
    revalidate();
    repaint();
    centerPoint(new Point(getImage().getWidth()/2, getImage().getHeight()/2));

    pcallF(onZoom);
  }

  public Dimension getMinimumSize() {
    if (noMinimumSize) return new Dimension(1, 1);
    int w = getZoomedWidth();
    int h = getZoomedHeight();
    Dimension min = super.getMinimumSize();
    return new Dimension(Math.max(w, min.width), Math.max(h, min.height));
  }

  private int getZoomedHeight() {
    return (int) (image.getHeight() * zoomY);
  }

  private int getZoomedWidth() {
    return (int) (image.getWidth() * zoomX);
  }

  public void setImage(RGBImage image) {
    setImage(image.getBufferedImage());
  }

  public void setImage(BufferedImage image) {
    this.image = image != null ? image : dummyImage();
    revalidate();
    repaint();
  }

  public BufferedImage getImage() {
    return image;
  }

  public double getZoomX() {
    return zoomX;
  }

  public double getZoomY() {
    return zoomY;
  }

  public Dimension getPreferredSize() {
    return new Dimension(getZoomedWidth(), getZoomedHeight());
  }

  /** returns a scrollpane with the scroll-mode prevent-garbage-drawing fix applied */
  public JScrollPane makeScrollPane() {
    JScrollPane scrollPane = new JScrollPane(this);
    scrollPane.getViewport().setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE);
    return scrollPane;
  }

  public void zoomToWindow() { zoomToDisplaySize(); }
  public void zoomToDisplaySize() {
    if (image == null) return;
    Dimension display = getDisplaySize();
    double xRatio = display.width/(double) image.getWidth();
    double yRatio = display.height/(double) image.getHeight();
    setZoom(Math.min(xRatio, yRatio));
    revalidate();
  }

  /** tricky magic to get parent scroll pane */
  private Dimension getDisplaySize() {
    Container c = getParent();
    while (c != null) {
      if (c instanceof JScrollPane)
        return c.getSize();
      c = c.getParent();
    }
    return getSize();
  }

  public void setSelection(Rectangle r) {
    if (neq(selection, r)) {
      selection = r;
      pcallF(onSelectionChange);
      repaint();
    }
  }

  public Rectangle getSelection() {
    return selection;
  }

  public RGBImage getRGBImage() {
    return new RGBImage(getImage());
  }
  
  // p is in image coordinates
  void centerPoint(Point p) {
    JScrollPane sp = enclosingScrollPane(this);
    if (sp == null) return;
      
    p = new Point((int) (p.x*getZoomX()), (int) (p.y*getZoomY()));
    final JViewport viewport = sp.getViewport();
    Dimension viewSize = viewport.getExtentSize();
    
    //_print("centerPoint " + p);
    int x = max(0, p.x-viewSize.width/2);
    int y = max(0, p.y-viewSize.height/2);
    
    //_print("centerPoint " + p + " => " + x + "/" + y);
    p = new Point(x,y);
    //_print("centerPoint " + p);
    final Point _p = p;
    awtLater(new Runnable() { public void run() { try { 
      viewport.setViewPosition(_p);
    
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "viewport.setViewPosition(_p);"; }});
  }
  
  Pt pointFromEvent(MouseEvent e) {
    return pointFromComponentCoordinates(new Pt(e.getX(), e.getY()));
  }
  
  Pt pointFromComponentCoordinates(Pt p) {
    return new Pt((int) (p.x/zoomX), (int) (p.y/zoomY));
  }
  
  void uploadTheImage() {
    call(hotwire("#1007313"), "go", getImage(), titleForUpload);
  }
  
  void showFullScreen() {
    showFullScreenImageSurface(getImage());
  }
  
  void zoomIn(double f) { setZoom(getZoomX()*f, getZoomY()*f); }
  void zoomOut(double f) { setZoom(getZoomX()/f, getZoomY()/f); }
}

static class 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 + ">";
  }
}

static JFrame showFullScreen(final JComponent c) {
  return (JFrame) swingAndWait(new Object() { Object get() { try { 
    GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment()
      .getDefaultScreenDevice();
    if (!gd.isFullScreenSupported())
      throw fail("No full-screen mode supported!");
    boolean dec = JFrame.isDefaultLookAndFeelDecorated();
    if (dec) JFrame.setDefaultLookAndFeelDecorated(false);
    final JFrame window = new JFrame();
    window.setUndecorated(true);
    if (dec) JFrame.setDefaultLookAndFeelDecorated(true);
    registerEscape(window, new Runnable() { public void run() { try {  disposeWindow(window) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "disposeWindow(window)"; }});
    window.add(wrap(c));
    gd.setFullScreenWindow(window);
    
    // Only this hides the task bar in Peppermint Linux w/Substance
    for (int i = 100; i <= 1000; i += 100)
      awtLater(i, new Runnable() { public void run() { try {  window.toFront() ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "window.toFront()"; }});
    
    return window;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment()\r\n      .ge..."; }});
}
static boolean hasTransparency(BufferedImage img) {
  return img.getColorModel().hasAlpha();
}
static List<String> scoredSearch(String query, Collection<String> data) {
  Map<String,Integer> scores = new HashMap();
  for (String s : data) {
    int score = scoredSearch_score(s, query);
    if (score != 0)
      scores.put(s, score);
  }
  return keysSortedByValuesDesc(scores);
}

static int scoredSearch_score(String s, String query) {
  int score = 0;
  if (swic(s, query)) score += l(s) == l(query) ? 3 : 2;
  else if (containsIgnoreCase(s, query)) ++score;
  return score;
}
static int hashCodeFor(Object a) {
  return a == null ? 0 : a.hashCode();
}
static boolean stdEq2(Object a, Object b) {
  if (a == null) return b == null;
  if (b == null) return false;
  if (a.getClass() != b.getClass()) return false;
  for (String field : allFields(a))
    if (neq(getOpt(a, field), getOpt(b, field)))
      return false;
  return true;
}
static boolean equals(Object a, Object b) {
  return a == null ? b == null : a.equals(b);
}
static int stdHash2(Object a) {
  if (a == null) return 0;
  return stdHash(a, toStringArray(allFields(a)));
}
static void copyArrayToVector(Object[] array, Vector v) {
  v.clear();
  v.addAll(toList(array));
}
static void showFullScreenImageSurface(BufferedImage img) {
  showFullScreen(jscroll_centered(disposeFrameOnClick(new ImageSurface(img))));
}
static void popup(final Throwable throwable) {
  popupError(throwable);
}

static void popup(final String msg) {
  print(msg);
  SwingUtilities.invokeLater(new Runnable() {
    public void run() {
      JOptionPane.showMessageDialog(null, msg);
    }
  });
}
static <A, B> void put(Map<A, B> map, A a, B b) {
  if (map != null) map.put(a, b);
}
static JScrollPane enclosingScrollPane(Component c) {
  while (c.getParent() != null && !(c.getParent() instanceof JViewport) && c.getParent().getComponentCount() == 1) c = c.getParent(); // for jscroll_center
  if (!(c.getParent() instanceof JViewport)) return null;
  c = c.getParent().getParent();
  return c instanceof JScrollPane ? (JScrollPane) c : null;
}



// onDrop: voidfunc(File)
static void jHandleFileDrop(JComponent c, final Object onDrop) {
  new DropTarget(c, new DropTargetAdapter() {
    public void drop(DropTargetDropEvent e) {
      try {
        Transferable tr = e.getTransferable();
        DataFlavor[] flavors = tr.getTransferDataFlavors();
        for (DataFlavor flavor : flavors) {
          if (flavor.isFlavorJavaFileListType()) {
            e.acceptDrop(e.getDropAction());
            File file = first((List<File>) tr.getTransferData(flavor));
            if (file != null && !isFalse(callF(onDrop, file)))
              e.dropComplete(true);
            return;
          }
        }
      } catch (Throwable __e) { printStackTrace2(__e); }
      e.rejectDrop();
    }
  });
}



static BufferedImage getImageFromClipboard() { try {
  Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
  if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.imageFlavor))
    return (BufferedImage) transferable.getTransferData(DataFlavor.imageFlavor);
  return imageFromDataURL(getTextFromClipboard());
} catch (Exception __e) { throw rethrow(__e); } }
static void copyImageToClipboard(Image img) {
  TransferableImage trans = new TransferableImage(img);
  Toolkit.getDefaultToolkit().getSystemClipboard().setContents( trans, null);
  print("Copied image to clipboard (" + img.getWidth(null) + "*" + img.getHeight(null) + " px)");
}


static JScrollPane jscroll_centered(Component c) {
  return new JScrollPane(jFullCenter(c));
}
  static void popupError(final Throwable throwable) {
    throwable.printStackTrace(); // print stack trace to console for the experts
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        String text = throwable.toString();
        //text = cutPrefix(text, "java.lang.RuntimeException: ");
        JOptionPane.showMessageDialog(null, text);
      }
    });
  }
static <A extends JComponent> A disposeFrameOnClick(final A c) {
  onClick(c, new Runnable() { public void run() { try {  disposeFrame(c) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "disposeFrame(c)"; }});
  return c;
}
static boolean swic(String a, String b) {
  return startsWithIgnoreCase(a, b);
}


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

static void registerEscape(JFrame frame, final Runnable r) {
  String name = "Escape";
  Action action = abstractAction(name, r);
  JComponent pnl = frame.getRootPane();
  KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
  pnl.getActionMap().put(name, action);
  pnl.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, name);
}
static int stdHash(Object a, String... fields) {
  if (a == null) return 0;
  int hash = getClassName(a).hashCode();
  for (String field : fields)
    hash = hash*2+hashCode(getOpt(a, field));
  return hash;
}
static BufferedImage imageFromDataURL(String url) {
  String pref = "base64,";
  int i = indexOf(url, pref);
  if (i < 0) return null;
  return decodeImage(base64decode(substring(url, i+l(pref))));
}
static <A, B> List<A> keysSortedByValuesDesc(final Map<A, B> map) {
  List<A> l = new ArrayList(map.keySet());
  sort(l, mapComparatorDesc(map));
  return l;
}


static boolean startsWithIgnoreCase(String a, String b) {
  return a != null && a.regionMatches(true, 0, b, 0, b.length());
}
static int hashCode(Object a) {
  return a == null ? 0 : a.hashCode();
}
static <A, B> Comparator<A> mapComparatorDesc(final Map<A, B> map) {
  return new Comparator<A>() {
    public int compare(A a, A b) {
      return cmp(map.get(b), map.get(a));
    }
  };
}
static JPanel jFullCenter(final Component c) {
  return swing(new F0<JPanel>() { JPanel get() { try { 
    JPanel panel = new JPanel(new GridBagLayout());
    panel.add(c);
    return panel;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "JPanel panel = new JPanel(new GridBagLayout);\r\n    panel.add(c);\r\n    ret panel;"; }});
}
static <T> void sort(T[] a, Comparator<? super T> c) {
  Arrays.sort(a, c);
}

static <T> void sort(T[] a) {
  Arrays.sort(a);
}

static <T> void sort(List<T> a, Comparator<? super T> c) {
  Collections.sort(a, c);
}

static void sort(List a) {
  Collections.sort(a);
}
static BufferedImage decodeImage(byte[] data) { try {
  return ImageIO.read(new ByteArrayInputStream(data));
} catch (Exception __e) { throw rethrow(__e); } }
  static byte[] base64decode(String s) {
    byte[] alphaToInt = base64decode_base64toint;
    int sLen = s.length();
    int numGroups = sLen/4;
    if (4*numGroups != sLen)
      throw new IllegalArgumentException(
        "String length must be a multiple of four.");
    int missingBytesInLastGroup = 0;
    int numFullGroups = numGroups;
    if (sLen != 0) {
      if (s.charAt(sLen-1) == '=') {
        missingBytesInLastGroup++;
        numFullGroups--;
      }
      if (s.charAt(sLen-2) == '=')
        missingBytesInLastGroup++;
    }
    byte[] result = new byte[3*numGroups - missingBytesInLastGroup];

    // Translate all full groups from base64 to byte array elements
    int inCursor = 0, outCursor = 0;
    for (int i=0; i<numFullGroups; i++) {
      int ch0 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      int ch1 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      int ch2 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      int ch3 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
      result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
      result[outCursor++] = (byte) ((ch2 << 6) | ch3);
    }

    // Translate partial group, if present
    if (missingBytesInLastGroup != 0) {
      int ch0 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      int ch1 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));

      if (missingBytesInLastGroup == 1) {
        int ch2 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
        result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
      }
    }
    // assert inCursor == s.length()-missingBytesInLastGroup;
    // assert outCursor == result.length;
    return result;
  }

  static int base64decode_base64toint(char c, byte[] alphaToInt) {
    int result = alphaToInt[c];
    if (result < 0)
      throw new IllegalArgumentException("Illegal character " + c);
    return result;
  }

  static final byte base64decode_base64toint[] = {
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54,
    55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4,
    5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
    24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34,
    35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
  };








static class TransferableImage implements Transferable {
  Image i;

  TransferableImage(Image i) {
  this.i = i;}

  public Object getTransferData( DataFlavor flavor )
  throws UnsupportedFlavorException, IOException {
      if ( flavor.equals( DataFlavor.imageFlavor ) && i != null ) {
          return i;
      }
      else {
          throw new UnsupportedFlavorException( flavor );
      }
  }

  public DataFlavor[] getTransferDataFlavors() {
      DataFlavor[] flavors = new DataFlavor[ 1 ];
      flavors[ 0 ] = DataFlavor.imageFlavor;
      return flavors;
  }

  public boolean isDataFlavorSupported( DataFlavor flavor ) {
      DataFlavor[] flavors = getTransferDataFlavors();
      for ( int i = 0; i < flavors.length; i++ ) {
          if ( flavor.equals( flavors[ i ] ) ) {
              return true;
          }
      }

      return false;
  }
}

abstract static class Surface extends JPanel {
  public boolean clearSurface = true;
  private boolean clearOnce;

  Surface() {
    setDoubleBuffered(false);
  }

  Graphics2D createGraphics2D(int width, int height, Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setBackground(getBackground());
    if (clearSurface || clearOnce) {
      g2.clearRect(0, 0, width, height);
      clearOnce = false;
    }
    return g2;
  }

  public abstract void render(int w, int h, Graphics2D g);

  public void paintImmediately(int x,int y,int w, int h) {
    RepaintManager repaintManager = null;
    boolean save = true;
    if (!isDoubleBuffered()) {
      repaintManager = RepaintManager.currentManager(this);
      save = repaintManager.isDoubleBufferingEnabled();
      repaintManager.setDoubleBufferingEnabled(false);
    }
    super.paintImmediately(x, y, w, h);

    if (repaintManager != null)
      repaintManager.setDoubleBufferingEnabled(save);
  }

  public void paint(Graphics g) {
    Dimension d = getSize();
    Graphics2D g2 = createGraphics2D(d.width, d.height, g);
    render(d.width, d.height, g2);
    g2.dispose();
  }
}


static class RGB {
  public float r, g, b; // can't be final cause persistence
  
  RGB() {}
  
  public RGB(float r, float g, float b) {
    this.r = r;
    this.g = g;
    this.b = b;
  }

  public RGB(double r, double g, double b) {
    this.r = (float) r;
    this.g = (float) g;
    this.b = (float) b;
  }

  public RGB(int rgb) {
    this(new Color(rgb));
  }
  
  public RGB(double brightness) {
    this.r = this.g = this.b = max(0f, min(1f, (float) brightness));
  }

  public RGB(Color color) {
    this.r = color.getRed()/255f;
    this.g = color.getGreen()/255f;
    this.b = color.getBlue()/255f;
  }

  public RGB(String hex) {
    r = Integer.parseInt(hex.substring(0, 2), 16)/255f;
    g = Integer.parseInt(hex.substring(2, 4), 16)/255f;
    b = Integer.parseInt(hex.substring(4, 6), 16)/255f;
  }

  public float getComponent(int i) {
    return i == 0 ? r : i == 1 ? g : b;
  }

  public Color getColor() {
    return new Color(r, g, b);
  }

  public static RGB newSafe(float r, float g, float b) {
    return new RGB(Math.max(0, Math.min(1, r)), Math.max(0, Math.min(1, g)), Math.max(0, Math.min(1, b)));
  }

  int asInt() { return getColor().getRGB() & 0xFFFFFF; }
  int getInt() { return getColor().getRGB() & 0xFFFFFF; }

  public float getBrightness() {
    return (r+g+b)/3.0f;
  }

  public String getHexString() {
    return Integer.toHexString(asInt() | 0xFF000000).substring(2).toUpperCase();
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof RGB)) return false;

    RGB rgb = (RGB) o;

    if (Float.compare(rgb.b, b) != 0) return false;
    if (Float.compare(rgb.g, g) != 0) return false;
    if (Float.compare(rgb.r, r) != 0) return false;

    return true;
  }

  @Override
  public int hashCode() {
    int result = (r != +0.0f ? Float.floatToIntBits(r) : 0);
    result = 31 * result + (g != +0.0f ? Float.floatToIntBits(g) : 0);
    result = 31 * result + (b != +0.0f ? Float.floatToIntBits(b) : 0);
    return result;
  }

  public boolean isBlack() {
    return r == 0f && g == 0f && b == 0f;
  }

  public boolean isWhite() {
    return r == 1f && g == 1f && b == 1f;
  }

  public String toString() {
    return getHexString();
  }
}

static class RGBImage {
  transient BufferedImage bufferedImage;
  File file;
  int width, height;
  int[] pixels;

  RGBImage() {}

  RGBImage(BufferedImage image) {
    this(image, null);
  }

  RGBImage(BufferedImage image, File file) {
    this.file = file;
    bufferedImage = image;
    width = image.getWidth();
    height = image.getHeight();
    pixels = new int[width*height];
    PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width);
    try {
      if (!pixelGrabber.grabPixels())
        throw new RuntimeException("Could not grab pixels");
      cleanPixels(); // set upper byte to 0
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }
  }

  /** We assume it's a file name to load from */
  RGBImage(String file) throws IOException {
    this(new File(file));
  }

  RGBImage(Dimension size, Color color) {
    this(size.width, size.height, color);
  }

  RGBImage(Dimension size, RGB color) {
    this(size.width, size.height, color);
  }

  private void cleanPixels() {
    for (int i = 0; i < pixels.length; i++)
      pixels[i] &= 0xFFFFFF;
  }

  RGBImage(int width, int height, int[] pixels) {
    this.width = width;
    this.height = height;
    this.pixels = pixels;
  }

  RGBImage(int w, int h, RGB[] pixels) {
    this.width = w;
    this.height = h;
    this.pixels = asInts(pixels);
  }

  public static int[] asInts(RGB[] pixels) {
    int[] ints = new int[pixels.length];
    for (int i = 0; i < pixels.length; i++)
      ints[i] = pixels[i] == null ? 0 : pixels[i].getColor().getRGB();
    return ints;
  }

  public RGBImage(int w, int h) {
    this(w, h, Color.black);
  }
  
  RGBImage(int w, int h, RGB rgb) {
    this.width = w;
    this.height = h;
    this.pixels = new int[w*h];
    int col = rgb.asInt();
    if (col != 0)
      for (int i = 0; i < pixels.length; i++)
        pixels[i] = col;
  }

  RGBImage(RGBImage image) {
    this(image.width, image.height, copyPixels(image.pixels));
  }

  RGBImage(int width, int height, Color color) {
    this(width, height, new RGB(color));
  }

  RGBImage(File file) throws IOException {
    this(javax.imageio.ImageIO.read(file));
  }

  private static int[] copyPixels(int[] pixels) {
    int[] copy = new int[pixels.length];
    System.arraycopy(pixels, 0, copy, 0, pixels.length);
    return copy;
  }

  public int getIntPixel(int x, int y) {
    if (inRange(x, y))
      return pixels[y * width + x];
    else
      return 0xFFFFFF;
  }

  public static RGB asRGB(int packed) {
    int r = (packed >> 16) & 0xFF;
    int g = (packed >> 8) & 0xFF;
    int b = packed & 0xFF;
    return new RGB(r / 255f, g / 255f, b / 255f);
  }

  public RGB getRGB(int x, int y) {
    if (inRange(x, y))
      return asRGB(pixels[y * width + x]);
    else
      return new RGB(0xFFFFFF);
  }

  /** alias of getRGB - I kept typing getPixel instead of getRGB all the time, so I finally created it */
  RGB getPixel(int x, int y) {
    return getRGB(x, y);
  }
  
  RGB getPixel(Pt p) { return getPixel(p.x, p.y); }

  int getWidth() { return width; }
  int getHeight() { return height; }
  int w() { return width; }
  int h() { return height; }

  /** Attention: cached, i.e. does not change when image itself changes */
  /** @NotNull */
  public BufferedImage getBufferedImage() {
    if (bufferedImage == null) {
      bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
      //bufferedImage.setData(Raster.createRaster(new SampleModel()));
      for (int y = 0; y < height; y++)
        for (int x = 0; x < width; x++)
          bufferedImage.setRGB(x, y, pixels[y*width+x]);
    }
    return bufferedImage;
  }

  RGBImage clip(Rect r) {
    return r == null ? null : clip(r.getRectangle());
  }
  
  RGBImage clip(Rectangle r) {
    r = fixClipRect(r);
    int[] newPixels;
    try {
      newPixels = new int[r.width*r.height];
    } catch (RuntimeException e) {
      System.out.println(r);
      throw e;
    }
    for (int y = 0; y < r.height; y++) {
      System.arraycopy(pixels, (y+r.y)*width+r.x, newPixels, y*r.width, r.width);
    }
    return new RGBImage(r.width, r.height, newPixels);
  }

  private Rectangle fixClipRect(Rectangle r) {
    r = r.intersection(new Rectangle(0, 0, width, height));
    if (r.isEmpty())
      r = new Rectangle(r.x, r.y, 0, 0);
    return r;
  }

  public File getFile() {
    return file;
  }

  /** can now also do GIF (not just JPEG) */
  public static RGBImage load(String fileName) {
    return load(new File(fileName));
  }

  /** can now also do GIF (not just JPEG) */
  public static RGBImage load(File file) {
    try {
      BufferedImage bufferedImage = javax.imageio.ImageIO.read(file);
      return new RGBImage(bufferedImage);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public int getInt(int x, int y) {
    return pixels[y * width + x];
  }

  public void save(File file) throws IOException {
    String name = file.getName().toLowerCase();
    String type;
    if (name.endsWith(".png")) type = "png";
    else if (name.endsWith(".jpg") || name.endsWith(".jpeg")) type = "jpeg";
    else throw new IOException("Unknown image extension: " + name);
    javax.imageio.ImageIO.write(getBufferedImage(), type, file);
  }

  public static RGBImage dummyImage() {
    return new RGBImage(1, 1, new int[] {0xFFFFFF});
  }

  public int[] getPixels() {
    return pixels;
  }

  public void setPixel(int x, int y, RGB rgb) {
    if (x >= 0 && y >= 0 && x < width && y < height)
      pixels[y*width+x] = rgb.asInt();
  }

  public void setPixel(int x, int y, Color color) {
    setPixel(x, y, new RGB(color));
  }

  public void setPixel(int x, int y, int rgb) {
    if (x >= 0 && y >= 0 && x < width && y < height)
      pixels[y*width+x] = rgb;
  }
  
  void setPixel(Pt p, RGB rgb) { setPixel(p.x, p.y, rgb); }
  void setPixel(Pt p, Color color) { setPixel(p.x, p.y, color); }

  public RGBImage copy() {
    return new RGBImage(this);
  }

  public boolean inRange(int x, int y) {
    return x >= 0 && y >= 0 && x < width && y < height;
  }

  public Dimension getSize() {
    return new Dimension(width, height);
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    RGBImage rgbImage = (RGBImage) o;

    if (height != rgbImage.height) return false;
    if (width != rgbImage.width) return false;
    if (!Arrays.equals(pixels, rgbImage.pixels)) return false;

    return true;
  }

  @Override
  public int hashCode() {
    int result = width;
    result = 31 * result + height;
    result = 31 * result + Arrays.hashCode(pixels);
    return result;
  }

  public String getHex(int x, int y) {
    return getPixel(x, y).getHexString();
  }

  public RGBImage clip(int x, int y, int width, int height) {
    return clip(new Rectangle(x, y, width, height));
  }

  public RGBImage clipLine(int y) {
    return clip(0, y, width, 1);
  }

  public int numPixels() {
    return width*height;
  }
}



static boolean inRange(int x, int n) {
  return x >= 0 && x < n;
}
static int asInt(Object o) {
  return toInt(o);
}

}