import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;


import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.text.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.text.NumberFormat;
import java.awt.datatransfer.StringSelection;

class main {

public static void main(final String[] args) throws Exception { pExperiment(); 
  for (String s : tlft("\n    if (bla) blabla(); more;\n    if (bla) { block! } more;\n    if (bla) for (a; b; c) { block! } more; // will fail\n    if something else\n  ")) {
    List<String> tok = javaTok(s);
    T3<List<String>, List<String>, Integer> t = tok_parseIfStatement(tok);
    printStruct(t);
    if (t != null) printStruct(subList(tok, t.c));
  }
}
static void pExperiment() {
  if (!isMain()) return;
  //substance();
  autoRestart(5);
  experimentIcon();
  centerHigherConsole();
  tt();
}
static List<String> tlft(String s) { return toLinesFullTrim(s); }
static List<String> tlft(File f) { return toLinesFullTrim(f); }

// TODO: extended multi-line strings

static int javaTok_n, javaTok_elements;
static boolean javaTok_opt;

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

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

static List<String> javaTok(List<String> tok) {
  return javaTokWithExisting(join(tok), tok);
}
// t3(condition, statement, index)
static T3<List<String>, List<String>, Integer> tok_parseIfStatement(List<String> tok) {
  if (!eqGet(tok, 1, "if") || !eqGet(tok, 3, "(")) return null;
  int clBr = findEndOfBracketPart(tok, 5)-1;
  int end = tok_findEndOfStatement(tok, clBr+2);
  return t3(subList(tok, 6, clBr), subList(tok, clBr+1, end+1), end+1);
}
static <A> A printStruct(String prefix, A a) {
  printStructure(prefix, a);
  return a;
}

static <A> A printStruct(A a) {
  printStructure(a);
  return a;
}

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 = Math.max(0, Math.min(l(l), startIndex));
  endIndex = Math.max(0, Math.min(l(l), endIndex));
  if (startIndex > endIndex) return litlist();
  return l.subList(startIndex, endIndex);
}




static boolean isMain() {
  return isMainProgram();
}
static double autoRestart_interval = 10;
static boolean autoRestart_on, autoRestart_debug, autoRestart_simulate;
static java.util.Timer autoRestart_timer;

static void autoRestart(double interval) {
  autoRestart_interval = interval;
  autoRestart();
}

static void autoRestart() {
  if (!isMain() || autoRestart_on) return;
  autoRestart_on = true;
  autoRestart_schedule();
  preloadProgramTitle();
}

static void autoRestart_off() {
  if (!autoRestart_on) return;
  stopTimer(autoRestart_timer);
  autoRestart_timer = null;
}

static void autoRestart_schedule() {
  autoRestart_timer = doLater_daemon(toMS(autoRestart_interval), "autoRestart_check");
}

static void autoRestart_check() {
  try {
    String newMD5;
    try {
      newMD5 = serverAutoRestartMD5(programID());
    } catch (Throwable e) {
      return;
    }
    if (!isMD5(newMD5)) { if (autoRestart_debug) print("autoRestart: no server transpilation"); return; }
    if (autoRestart_localMD5 == null)
      autoRestart_localMD5 = md5(loadCachedTranspilation(programID()));

    String localMD5 = autoRestart_localMD5();
    if (neq(localMD5, newMD5)) {
      if (autoRestart_simulate)
        print("Would upgrade now. " + localMD5 + " -> " + newMD5);
      else {
        infoBox("Upgrading " + programTitle());
        restartWithDelay(500);
        sleep();
      }
    }
  } finally {
    if (autoRestart_debug) print("autoRestart: Done");
    autoRestart_schedule();
  }
}

static void experimentIcon() {
  consoleAndDefaultFrameIcon("#1101173" /*#1101171*/);
}
static void centerHigherConsole() {
  if (headless()) return;
  setConsoleHeight(600);
  centerConsole();
}
static void tt() {
  typeWriterConsole();
}

static String tt(Object contents, Object... params) {
  return tag("tt", contents, params);
}
static List<String> toLinesFullTrim(String s) {
  List<String> l = new ArrayList();
  for (String line : toLines(s)) if (nempty(line = trim(line))) l.add(line);
  return l;
}

static List<String> toLinesFullTrim(File f) {
  List<String> l = new ArrayList();
  for (String line : linesFromFile(f)) if (nempty(line = trim(line))) l.add(line);
  return l;
}

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

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

static boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
  return t.length() == j-i
    && s.regionMatches(i, t, 0, j-i); // << could be left out, but that's brave
}
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 join(String glue, Pair p) {
  return p == null ? "" : str(p.a) + glue + str(p.b);
}

static boolean eqGet(List l, int i, Object o) {
  return eq(get(l, i), o);
}
// i must point at the (possibly imaginary) opening bracket (any of the 2 types, not type parameters)
// index returned is index of closing bracket + 1
static int findEndOfBracketPart(List<String> cnc, int i) {
  int j = i+2, level = 1;
  while (j < cnc.size()) {
    if (eqOneOf(cnc.get(j), "{", "(")) ++level;
    else if (eqOneOf(cnc.get(j), "}", ")")) --level;
    if (level == 0)
      return j+1;
    ++j;
  }
  return cnc.size();
}
// Return value is index of semicolon/curly brace+1
static int tok_findEndOfStatement(List<String> tok, int i) {
  // Is it a block?
  if (eq(get(tok, i), "{"))
    return findEndOfBlock(tok, i);
    
  // It's a regular statement.
  int j = i;
  while (j < l(tok) && neq(tok.get(j), ";"))
    if (eqOneOf(get(tok, j), "{", "("))
      j = findEndOfBracketPart(tok, j)+1;
    else
      j += 2;
  return j+1;
}
static <A, B, C> T3<A, B, C> t3(A a, B b, C c) {
  return new T3(a, b, c);
}
static void printStructure(String prefix, Object o) {
  if (endsWithLetter(prefix)) prefix += ": ";
  print(prefix + structureForUser(o));
}

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

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

static int l(Object o) {
  return o == null ? 0
    : o instanceof String ? l((String) o)
    : o instanceof Map ? l((Map) o)
    : o instanceof Collection ? l((Collection) o)
    : o instanceof Object[] ? l((Object[]) o)
    : (Integer) call(o, "size");
}




static <A> ArrayList<A> litlist(A... a) {
  ArrayList l = new ArrayList(a.length);
  for (A x : a) l.add(x);
  return l;
}


static boolean isMainProgram() {
  return creator() == null;
}
static void preloadProgramTitle() {
  { Thread _t_0 = new Thread() {
public void run() { try { programTitle(); } catch (Throwable __e) { _handleException(__e); } }
};
startThread(_t_0); }
}
static void stopTimer(java.util.Timer timer) {
  if (timer != null) timer.cancel();
}
static java.util.Timer doLater_daemon(long delay, final Object r) {
  final java.util.Timer timer = new java.util.Timer(true);
  timer.schedule(timerTask(r), delay);
  return timer;
}

static java.util.Timer doLater_daemon(double delaySeconds, final Object r) {
  return doLater_daemon(toMS(delaySeconds), r);
}
static long toMS(double seconds) {
  return (long) (seconds*1000);
}
static int serverAutoRestartMD5_timeout = 10000;

static String serverAutoRestartMD5(String programID) {
  return loadPageSilentlyWithTimeout("http://botcompany.de/1010693/raw?id=" + psI(programID), serverAutoRestartMD5_timeout);
}

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

static String programID(Object o) {
  return getProgramID(o);
}
static boolean isMD5(String s) {
  return l(s) == 32 && isLowerHexString(s);
}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile Appendable print_log = local_log; // might be redirected, e.g. to main bot

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

static boolean print_silent; // total mute if set

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

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

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

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

static void print_noNewLine(String s) {
  
  Object f = print_byThread == null ? null : print_byThread.get();
  if (f == null) f = print_allThreads;
  if (f != null)
    // We do need the general callF machinery here as print_byThread is sometimes shared between modules
    if (isFalse(
      
      callF(f, s))) return;
  

  print_raw(s);
}

static void print_raw(String s) {
  s = fixNewLines(s);
  // TODO if (print_maxLineLength != 0)
  StringBuffer loc = local_log;
  Appendable buf = print_log;
  int loc_max = print_log_max;
  if (buf != loc && buf != null) {
    print_append(buf, s, print_log_max);
    loc_max = local_log_max;
  }
  if (loc != null) 
    print_append(loc, s, loc_max);
  System.out.print(s);
}
static String md5(String text) { try {
  if (text == null) return "-";
  return bytesToHex(md5_impl(text.getBytes("UTF-8"))); // maybe different than the way PHP does it...
} catch (Exception __e) { throw rethrow(__e); } }

static String md5(byte[] data) {
  if (data == null) return "-";
  return bytesToHex(md5_impl(data));
}

static MessageDigest md5_md;

/*static byte[] md5_impl(byte[] data) ctex {
  if (md5_md == null)
    md5_md = MessageDigest.getInstance("MD5");
  return ((MessageDigest) md5_md.clone()).digest(data);
}*/

static byte[] md5_impl(byte[] data) { try {
  return MessageDigest.getInstance("MD5").digest(data);
} catch (Exception __e) { throw rethrow(__e); } }

static String md5(File file) {
  return md5OfFile(file);
}
static String loadCachedTranspilation(String id) {
  return loadTextFilePossiblyGZipped(new File(getCodeProgramDir(id), "Transpilation"));
}

static String autoRestart_localMD5;

static String autoRestart_localMD5() { 
  if (autoRestart_localMD5 == null)
    autoRestart_localMD5 = md5(loadCachedTranspilation(programID()));
  return autoRestart_localMD5;
}
static boolean neq(Object a, Object b) {
  return !eq(a, b);
}
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 String programTitle() {
  return getProgramName();
}
static void restartWithDelay(int delay) {
  Object j = getJavaX();
  call(j, "preKill");
  call(j, "nohupJavax", smartJoin((String[]) get(j, "fullArgs")), call(j, "fullVMArguments"));
  sleep(delay);
  System.exit(0);
  sleep();
}
static volatile boolean sleep_noSleep;

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

static void sleep() { try {
  if (sleep_noSleep) throw fail("nosleep");
  print("Sleeping.");
  sleepQuietly();
} catch (Exception __e) { throw rethrow(__e); } }
static void consoleAndDefaultFrameIcon(String icon) {
  consoleIcon(icon);
  setDefaultFrameIcon(icon);
}
static boolean headless() {
  return isHeadless();
}
static void setConsoleHeight(int h) {
  setFrameHeight(consoleFrame(), h);
}
static void centerConsole() {
  centerConsoleFrame();
}

static void centerConsole(int w, int h) {
  setConsoleSize(w, h);
  centerConsoleFrame();
}
static void typeWriterConsole() {
  
  if (isHeadless()) return;
  Font f = typeWriterFont();
  consoleFont(f);
  consoleInputFont(f);
  
}
static String tag(String tag) {
  return htag(tag);
}

static String tag(String tag, Object contents, Object... params) {
  return htag(tag, str(contents), params);
}

static String tag(String tag, StringBuilder contents, Object... params) {
  return htag(tag, contents, params);
}

static String tag(String tag, StringBuffer contents, Object... params) {
  return htag(tag, contents, params);
}
static IterableIterator<String> toLines(File f) {
  return linesFromFile(f);
}

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

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

    start = i;
  }
  return lines;
}

static int toLines_nextLineBreak(String s, int start) {
  for (int i = start; i < s.length(); i++) {
    char c = s.charAt(i);
    if (c == '\r' || c == '\n')
      return i;
  }
  return -1;
}
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(byte[] o) { return !isEmpty(o); }

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

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

static boolean nempty(Object o) { return !empty(o); }
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 CloseableIterableIterator<String> linesFromFile(File f) { try {
  if (!f.exists()) return emptyCloseableIterableIterator();
  if (ewic(f.getName(), ".gz"))
    return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)));
  return linesFromReader(utf8bufferedReader(f));
} catch (Exception __e) { throw rethrow(__e); } }
static String str(Object o) {
  return o == null ? "null" : o.toString();
}

static String str(char[] c) {
  return new String(c);
}
static boolean eq(Object a, Object b) {
  return a == null ? b == null : a == b || a.equals(b);
}


// 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() & java.lang.reflect.Modifier.STATIC) != 0)
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}

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

static boolean eqOneOf(Object o, Object... l) {
  for (Object x : l) if (eq(o, x)) return true; return false;
}
// i must point at the (possibly imaginary) opening bracket ("{")
// index returned is index of closing bracket + 1 (or l(cnc))
static int findEndOfBlock(List<String> cnc, int i) {
  int j = i+2, level = 1;
  while (j < cnc.size()) {
    if (cnc.get(j).equals("{")) ++level;
    else if (cnc.get(j).equals("}")) --level;
    if (level == 0)
      return j+1;
    ++j;
  }
  return cnc.size();
}
static boolean endsWithLetter(String s) {
  return nempty(s) && isLetter(last(s));
}
static String structureForUser(Object o) {
  return beautifyStructure(struct_noStringSharing(o));
}
// TODO: remove
static Object call(Object o) {
  return callF(o);
}

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

static Object call(Object o, String method, Object... args) { try {
  if (o == null) return null;
  if (o instanceof Class) {
    Method m = call_findStaticMethod((Class) o, method, args, false);
    m.setAccessible(true);
    return invokeMethod(m, null, args);
  /*} else if (o instanceof DynamicMethods) {
    ret ((DynamicMethods) o)._dynCall(method, args);*/
  } else {
    Method m = call_findMethod(o, method, args, false);
    m.setAccessible(true);
    return invokeMethod(m, o, args);
  }
} catch (Exception __e) { throw rethrow(__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() & java.lang.reflect.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());
}


static WeakReference<Object> creator_class;

static Object creator() {
  return creator_class == null ? null : creator_class.get();
}
static volatile PersistableThrowable _handleException_lastException;
static List _handleException_onException = synchroList(ll("printStackTrace2"));

static void _handleException(Throwable e) {
  _handleException_lastException = persistableThrowable(e);
  for (Object f : cloneList(_handleException_onException)) try {
    callF(f, e);
  } catch (Throwable e2) {
    printStackTrace2(e2); // pcall could lead to endless loops
  }
}

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

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

static Thread startThread(Thread t) {
  
  _registerThread(t);
  
  t.start();
  return t;
}
static TimerTask timerTask(final Object r, final java.util.Timer timer) {
  return new TimerTask() {
    public void run() {
      if (!licensed())
        timer.cancel();
      else
        pcallF(r);
    }
  };
}

static TimerTask timerTask(final Object r) {
  return new TimerTask() {
    public void run() {
      ping();
      pcallF(r);
    }
  };
}
static String loadPageSilentlyWithTimeout(String url, int timeout) { try {
  url = loadPage_preprocess(url);
  URL _url = new URL(url);
  return loadPage(
    setURLConnectionTimeouts(_url.openConnection(), timeout),
    _url);
} catch (Exception __e) { throw rethrow(__e); } }
static long psI(String snippetID) {
  return parseSnippetID(snippetID);
}
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 isLowerHexString(String s) {
  for (int i = 0; i < l(s); i++) {
    char c = s.charAt(i);
    if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
      // ok
    } else
      return false;
  }
  return true;
}
static boolean endsWithLetterOrDigit(String s) {
  return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length()-1));
}
//sbool ping_actions_shareable = true;
static volatile boolean ping_pauseAll;
static int ping_sleep = 100; // poll pauseAll flag every 100

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


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

// returns true when it slept
static boolean ping_impl() { try {
  if (ping_pauseAll && !isAWTThread()) {
    do
      Thread.sleep(ping_sleep);
    while (ping_pauseAll);
    return true;
  }
  
  
  if (ping_anyActions) { // don't allow sharing ping_actions
    Object action = null;
    synchronized(ping_actions) {
      if (!ping_actions.isEmpty()) {
        action = ping_actions.get(currentThread());
        if (action instanceof Runnable)
          ping_actions.remove(currentThread());
        if (ping_actions.isEmpty()) ping_anyActions = false;
      }
    }
    
    if (action instanceof Runnable)
      ((Runnable) action).run();
    else if (eq(action, "cancelled"))
      throw fail("Thread cancelled.");
  }
  
  
  return false;
} catch (Exception __e) { throw rethrow(__e); } }
static boolean isFalse(Object o) {
  return eq(false, o);
}
static Map<Class, ArrayList<Method>> callF_cache = newDangerousWeakHashMap();


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







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


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

// used internally
static ArrayList<Method> callF_makeCache(Class c) {
  ArrayList<Method> l = new ArrayList();
  Class _c = c;
  do {
    for (Method m : _c.getDeclaredMethods())
      if (m.getName().equals("get")) {
        m.setAccessible(true);
        l.add(m);
      }
    if (!l.isEmpty()) break;
    _c = _c.getSuperclass();
  } while (_c != null);
  callF_cache.put(c, l);
  return l;
}
static String fixNewLines(String s) {
  int i = indexOf(s, '\r');
  if (i < 0) return s;
  int l = s.length();
  StringBuilder out = new StringBuilder(l);
  out.append(s, 0, i);
  for (; i < l; i++) {
    char c = s.charAt(i);
    if (c != '\r')
      out.append(c);
    else {
      out.append('\n');
      if (i+1 < l && s.charAt(i+1) == '\n') ++i;
    }
  }
  return out.toString();
}
static void print_append(Appendable _buf, String s, int max) { try {
  synchronized(_buf) {
    _buf.append(s);
    if (!(_buf instanceof StringBuilder)) return;
    StringBuilder buf = (StringBuilder) ( _buf);
    max /= 2;
    if (buf.length() > max) try {
      int newLength = max/2;
      int ofs = buf.length()-newLength;
      String newString = buf.substring(ofs);
      buf.setLength(0);
      buf.append("[...] ").append(newString);
    } catch (Exception e) {
      buf.setLength(0);
    }
  }
} catch (Exception __e) { throw rethrow(__e); } }
  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 RuntimeException rethrow(Throwable t) {
  
  if (t instanceof Error)
    _handleError((Error) t);
  
  throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static String md5OfFile(File f) { try {
  if (!f.exists()) return "-";
  
  MessageDigest md5 = MessageDigest.getInstance("MD5");
   FileInputStream in = new FileInputStream(f); try {

  byte buf[] = new byte[65536];
  int l;
  while (true) {
    l = in.read(buf);
    if (l <= 0) break;
    md5.update(buf, 0, l);
  }
  
  return bytesToHex(md5.digest());
} finally { _close(in); }} catch (Exception __e) { throw rethrow(__e); } }
static String loadTextFilePossiblyGZipped(String fileName) {
  return loadTextFilePossiblyGZipped(fileName, null);
}
  
static String loadTextFilePossiblyGZipped(String fileName, String defaultContents) {
  File gz = new File(fileName + ".gz");
  return gz.exists() ? loadGZTextFile(gz) : loadTextFile(fileName, defaultContents);
}

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

static String loadTextFilePossiblyGZipped(File fileName, String defaultContents) {
  return loadTextFilePossiblyGZipped(fileName.getPath(), defaultContents);
}

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

static File getCodeProgramDir(String snippetID) {
  return new File(javaxCodeDir(), formatSnippetID(snippetID));
}

static File getCodeProgramDir(long snippetID) {
  return getCodeProgramDir(formatSnippetID(snippetID));
}
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) {
  printHidingCredentials(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) {
  final String text = hideCredentials(_text);
  if (empty(text)) return null;
  logQuotedWithDate(infoBoxesLogFile(), text); 
  if (isHeadless()) return null;
  return (JWindow) swingAndWait(new F0<Object>() { Object get() { try { 
    final JWindow window = showWindow(infoMessage_makePanel(text));
    window.setSize(300, 150);
    moveToTopRightCorner(window);
    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 "final JWindow window = showWindow(infoMessage_makePanel(text));\r\n    window.s..."; }});
}

static JWindow infoMessage(Throwable e) {
  showConsole();
  printStackTrace(e);
  return infoMessage(exceptionToStringShort(e));
}
static String getProgramName_cache;

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

static void _onLoad_getProgramName() {
  { Thread _t_0 = new Thread() {
public void run() { try { getProgramName(); } catch (Throwable __e) { _handleException(__e); } }
};
startThread(_t_0); }
}
static Class __javax;

static Class getJavaX() { try {
  
  return __javax;
} catch (Exception __e) { throw rethrow(__e); } }
// 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));
}
// 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 RuntimeException fail() { throw new RuntimeException("fail"); }
static RuntimeException fail(Throwable e) { throw asRuntimeException(e); }
static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); }
static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }

static Object sleepQuietly_monitor = new Object();

static void sleepQuietly() { try {
  assertFalse(isAWTThread());
  synchronized(sleepQuietly_monitor) { sleepQuietly_monitor.wait(); }
} catch (Exception __e) { throw rethrow(__e); } }
static void consoleIcon(String imageID) {
  frameIcon(consoleFrame(), or2(imageID, javaxDefaultIcon()));
}
static void setDefaultFrameIcon(String icon) {
  makeFrame_defaultIcon = icon;
}
static Boolean isHeadless_cache;

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

static JFrame setFrameHeight(int h, JFrame frame) {
  return setFrameHeight(frame, h);
}

static JFrame consoleFrame() {
  return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
}
static void centerConsoleFrame() {
  centerFrame(consoleFrame());
}
static void setConsoleSize(int w, int h) {
  setFrameSize(consoleFrame(), w, h);
}
static Font typeWriterFont() {
  return typeWriterFont(14);
}
  
static Font typeWriterFont(int size) {
  return new Font("Courier", Font.PLAIN, size);
}
static void consoleFont(Font font) {
  callOpt(getConsoleTextArea_gen(), "setFont", font);
}
static void consoleInputFont(final Font f) {
  { swing(new Runnable() { public void run() { try { 
    JTextField input = consoleInputField();
    if (input != null) {
      input.setFont(f);
      revalidateFrame(input);
    }
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "JTextField input = consoleInputField();\r\n    if (input != null) {\r\n      inpu..."; }}); }
}
static String htag(String tag) {
  return htag(tag, "");
}

static String htag(String tag, Object contents, Object... params) {
  String openingTag = hopeningTag(tag, params);
  String s = str(contents);
  if (empty(s) && neqic(tag, "script"))
    return dropLast(openingTag) + "/>";
  return openingTag + s + "</" + tag + ">";
}
static boolean isEmpty(Collection c) {
  return c == null || c.isEmpty();
}

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

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

static boolean isEmpty(Map map) {
  return map == null || map.isEmpty();
}
static boolean empty(Collection c) { return c == null || c.isEmpty(); }
static boolean empty(CharSequence s) { return s == null || s.length() == 0; }
static boolean empty(Map map) { return map == null || map.isEmpty(); }
static boolean empty(Object[] o) { return o == null || o.length == 0; }
static boolean empty(Object o) {
  if (o instanceof Collection) return empty((Collection) o);
  if (o instanceof String) return empty((String) o);
  if (o instanceof Map) return empty((Map) o);
  if (o instanceof Object[]) return empty((Object[]) o);
  if (o instanceof byte[]) return empty((byte[]) o);
  if (o == null) return true;
  throw fail("unknown type for 'empty': " + getType(o));
}

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


static CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() {
  public Object next() { throw fail(); }
  public boolean hasNext() { return false; }
};

static <A> CloseableIterableIterator<A> emptyCloseableIterableIterator() {
  return emptyCloseableIterableIterator_instance; 
}
static boolean ewic(String a, String b) {
  return endsWithIgnoreCase(a, b);
}


static CloseableIterableIterator<String> linesFromReader(Reader r) {
  final BufferedReader br = bufferedReader(r);
  return iteratorFromFunction_f0_autoCloseable(new F0<String>() { String get() { try { return  readLineFromReaderWithClose(br) ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "readLineFromReaderWithClose(br)"; }}, _wrapIOCloseable(r));
}
static BufferedReader utf8bufferedReader(InputStream in) { try {
  return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in));
} catch (Exception __e) { throw rethrow(__e); } }

static BufferedReader utf8bufferedReader(File f) { try {
  return utf8bufferedReader(newFileInputStream(f));
} catch (Exception __e) { throw rethrow(__e); } }
static GZIPInputStream newGZIPInputStream(File f) {
  return gzInputStream(f);
}

static GZIPInputStream newGZIPInputStream(InputStream in) {
  return gzInputStream(in);
}
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 RuntimeException asRuntimeException(Throwable t) {
  
  if (t instanceof Error)
    _handleError((Error) t);
  
  return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static boolean isLetter(char c) {
  return Character.isLetter(c);
}
static <A> A last(List<A> l) {
  return empty(l) ? 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 <A> A last(A[] a) {
  return l(a) != 0 ? a[l(a)-1] : null;
}

static <A> A last(Iterator<A> it) {
  A a = null;
  while  (it.hasNext()) { ping(); a = it.next(); }
  return a;
}
static String beautifyStructure(String s) {
  return structure_addTokenMarkers(s);
}
static String struct_noStringSharing(Object o) {
  structure_Data d = new structure_Data();
  d.noStringSharing = true;
  return structure(o, d);
}
static Object invokeMethod(Method m, Object o, Object... args) { try {
  try {
    return m.invoke(o, args);
  } catch (InvocationTargetException e) {
    throw rethrow(getExceptionCause(e));
  } catch (IllegalArgumentException e) {
    throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
  }
} catch (Exception __e) { throw rethrow(__e); } }
static boolean call_checkArgs(Method m, Object[] args, boolean debug) {
  Class<?>[] types = m.getParameterTypes();
  if (types.length != args.length) {
    if (debug)
      System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
    return false;
  }
  for (int i = 0; i < types.length; i++)
    if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
      if (debug)
        System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
      return false;
    }
  return true;
}


static 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 String makeFrame_defaultIcon;
static boolean makeFrame_hideConsole;
static ThreadLocal < VF1 < JFrame > > makeFrame_post = new ThreadLocal();

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

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

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

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

static JFrame makeFrame(final String title, final Object content, final boolean showIt) {
  final VF1<JFrame> post = optParam(makeFrame_post);
  return swing(new F0<JFrame>() { JFrame get() { try { 
    if (getFrame(content) != null)
      return getFrame(setFrameTitle((Component) content, title));
    final JFrame frame = new JFrame(title);
    if (makeFrame_defaultIcon != null)
      setFrameIconLater(frame, makeFrame_defaultIcon);
    _initFrame(frame);
    Component wrapped = wrap(content);
    if (wrapped != null)
      frame.getContentPane().add(wrapped);
    frame.setBounds(defaultNewFrameBounds());
    
    callF(post, frame);
    
    if (showIt)
      frame.setVisible(true);
    //callOpt(content, "requestFocus");
    //exitOnFrameClose(frame);
    
    if (showIt && makeFrame_hideConsole) {
      hideConsole();
      makeFrame_hideConsole = false;
    }
    
    return frame;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "if (getFrame(content) != null)\r\n      ret getFrame(setFrameTitle((Component) ..."; }});
}
static <A> List<A> synchroList() {
  return Collections.synchronizedList(new ArrayList<A>());
}

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

static <A> List<A> ll(A... a) {
  ArrayList l = new ArrayList(a.length);
  for (A x : a) l.add(x);
  return l;
}
static PersistableThrowable persistableThrowable(Throwable e) {
  return e == null ? null : new PersistableThrowable(e);
}
static <A> ArrayList<A> cloneList(Iterable<A> l) {
  return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}

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

static String defaultThreadName() {
  if (defaultThreadName_name == null)
    defaultThreadName_name = "A thread by " + programID();
  return defaultThreadName_name;
}
static Runnable wrapAsActivity(Object r) {
  return toRunnable(r);
}
// runnable = Runnable or String (method name)
static Thread newThread(Object runnable) {
  return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
}

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

static Thread newThread(String name, Object runnable) {
  return newThread(runnable, name);
}
static Runnable toRunnable(final Object o) {
  if (o instanceof Runnable) return (Runnable) o;
  return new Runnable() { public void run() { try {  callF(o) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "callF(o)"; }};
}
static Map<Thread, Boolean> _registerThread_threads;
static Object _onRegisterThread; // voidfunc(Thread)

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

static void _registerThread() { _registerThread(Thread.currentThread()); }
static volatile boolean licensed_yes = true;

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

static void licensed_off() {
  licensed_yes = false;
}
static Object pcallF(Object f, Object... args) {
  return pcallFunction(f, args);
}


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



static int loadPage_defaultTimeout = 60000;
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();
static volatile int loadPage_forcedTimeout; // ms
static ThreadLocal<Integer> loadPage_forcedTimeout_byThread = new ThreadLocal(); // ms
static ThreadLocal<Map<String, List<String>>> loadPage_responseHeaders = new ThreadLocal();
static ThreadLocal<Map<String, String>> loadPage_extraHeaders = new ThreadLocal();

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

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

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

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

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

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

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

static URLConnection loadPage_openConnection(URL url) {
  URLConnection con = openConnection(url);
  int timeout = toInt(loadPage_forcedTimeout_byThread.get());
  if (timeout == 0) timeout = loadPage_forcedTimeout;
  if (timeout != 0)
    setURLConnectionTimeouts(con, loadPage_forcedTimeout);
  else
    setURLConnectionDefaultTimeouts(con, loadPage_defaultTimeout);
  return con;
}
static URLConnection setURLConnectionTimeouts(URLConnection con, long timeout) {
  con.setConnectTimeout(toInt(timeout));
  con.setReadTimeout(toInt(timeout));
  if (con.getConnectTimeout() != timeout || con.getReadTimeout() != timeout)
    print("Warning: Timeouts not set by JDK.");
  return con;
}
public static long parseSnippetID(String snippetID) {
  long id = Long.parseLong(shortenSnippetID(snippetID));
  if (id == 0) throw fail("0 is not a snippet ID");
  return id;
}
static String formatSnippetIDOpt(String s) {
  return isSnippetID(s) ? formatSnippetID(s) : s;
}
static Object getOpt(Object o, String field) {
  return getOpt_cached(o, field);
}

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

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

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

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

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

static Class getMainClass(Object o) { try {
  if (o == null) return null;
  if (o instanceof Class && eq(((Class) o).getName(), "x30")) return (Class) o;
  return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) { throw rethrow(__e); } }
static <A, B> Map<A, B> newWeakHashMap() {
  return _registerWeakMap(synchroMap(new WeakHashMap()));
}
static Thread currentThread() {
  return Thread.currentThread();
}
static <A, B> Map<A, B> newDangerousWeakHashMap() {
  return _registerDangerousWeakMap(synchroMap(new WeakHashMap()));
}

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

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

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

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

static void callMC_makeCache() {
  synchronized(callMC_cache) {
    callMC_cache.clear();
    Class _c = (Class) mc(), c = _c;
    while (c != null) {
      for (Method m : c.getDeclaredMethods())
        if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
          m.setAccessible(true);
          multiMapPut(callMC_cache, m.getName(), m);
        }
      c = c.getSuperclass();
    }
  }
}
static String getClassName(Object o) {
  return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static <A> int indexOf(List<A> l, A a, int startIndex) {
  if (l == null) return -1;
  for (int i = startIndex; i < l(l); i++)
    if (eq(l.get(i), a))
      return i;
  return -1;
}

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

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

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

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

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

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

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

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

static <A> int indexOf(A[] x, A a) {
  if (x == null) return -1;
  for (int i = 0; i < l(x); i++)
    if (eq(x[i], a))
      return i;
  return -1;
}
static void _handleError(Error e) {
  call(javax(), "_handleError", e);
}
static void _close(AutoCloseable c) { try {
  if (c != null) c.close();
} catch (Exception __e) { throw rethrow(__e); } }
static String loadGZTextFile(File file) { try {
  if (!file.isFile()) return null;
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  InputStream fis = new FileInputStream(file);
  GZIPInputStream gis = newGZIPInputStream(fis);
  try {
    byte[] buffer = new byte[1024];
    int len;
    while((len = gis.read(buffer)) != -1){
        baos.write(buffer, 0, len);
    }
  } finally {
    fis.close();
  }
  baos.close();
  return fromUtf8(baos.toByteArray()); // TODO: use a Reader
} catch (Exception __e) { throw rethrow(__e); } }
static String loadTextFile(String fileName) {
  return loadTextFile(fileName, null);
}

static String loadTextFile(File f, String defaultContents) { try {
  checkFileNotTooBigToRead(f);
  if (f == null || !f.exists()) return defaultContents;

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

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

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

static String loadTextFile(Reader reader) throws IOException {
  StringBuilder builder = new StringBuilder();
  try {
    char[] buffer = new char[1024];
    int n;
    while (-1 != (n = reader.read(buffer)))
      builder.append(buffer, 0, n);
  } finally {
    reader.close();
  }
  return str(builder);
}
static File javaxCodeDir_dir; // can be set to work on different base dir

static File javaxCodeDir() {
  return javaxCodeDir_dir != null ? javaxCodeDir_dir : new File(userHome(), "JavaX-Code");
}
static <A> A printHidingCredentials(A o) {
  print(hideCredentials(str(o)));
  return o;
}
static String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); }

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

static String hideCredentials(Object o) {
  return hideCredentials(str(o));
}
static void logQuotedWithDate(String s) {
  logQuotedWithTime(s);
}

static void logQuotedWithDate(String logFile, String s) {
  logQuotedWithTime(logFile, s);
}

static void logQuotedWithDate(File logFile, String s) {
  logQuotedWithTime(logFile, s);
}
static File infoBoxesLogFile() {
  return new File(javaxDataDir(), "Logs/infoBoxes.txt");
}
static void swingAndWait(Runnable r) { try {
  if (isAWTThread())
    r.run();
  else
    EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) { throw rethrow(__e); } }

static Object swingAndWait(final Object f) {
  if (isAWTThread())
    return callF(f);
  else {
    final Var result = new Var();
    swingAndWait(new Runnable() { public void run() { try { 
      result.set(callF(f));
    
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "result.set(callF(f));"; }});
    return result.get();
  }
}
static JWindow showWindow(Component c) {
  JWindow w = new JWindow();
  w.add(wrap(c));
  return w;
}
static JPanel infoMessage_makePanel(String text) {
  final JTextArea ta = wrappedTextArea(text);
  onClick(ta, new Runnable() { public void run() { try {  disposeWindow(ta) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "disposeWindow(ta)"; }});
  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);
  return withMargin(sp);
}
static int moveToTopRightCorner_inset = 20;

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

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

static <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 <A extends Window> A disposeWindowAfter(A w, double seconds) {
  return disposeWindowAfter(toMS_int(seconds), w);
}
static int iround(double d) {
  return (int) Math.round(d);
}
static void showConsole() {
  callOpt(get(javax(), "console"), "showConsole");
}
static Throwable printStackTrace(Throwable e) {
  // we go to system.out now - system.err is nonsense
  print(getStackTrace(e));
  return e;
}

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

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

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

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

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

static ReentrantLock lock() {
  return fairLock();
}
static String getSnippetTitleOpt(String s) {
  return isSnippetID(s) ? getSnippetTitle(s) : s;
}
static void unlock(Lock lock, String msg) {
  if (lock == null) return;
  print("Unlocking: " + msg);
  lock.unlock();
}

static void unlock(Lock lock) {
  if (lock == null) return;
  lock.unlock();
}
static boolean isJavaIdentifier(String s) {
  if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
    return false;
  for (int i = 1; i < s.length(); i++)
    if (!Character.isJavaIdentifierPart(s.charAt(i)))
      return false;
  return true;
}
// supports the usual quotings (", variable length double brackets) except ' quoting
static boolean isQuoted(String s) {
  
  
  if (isNormalQuoted(s)) return true; // use the exact version
  
  return isMultilineQuoted(s);
}
static String quote(Object o) {
  if (o == null) return "null";
  return quote(str(o));
}

static String quote(String s) {
  if (s == null) return "null";
  StringBuilder out = new StringBuilder((int) (l(s)*1.5+2));
  quote_impl(s, out);
  return out.toString();
}
  
static void quote_impl(String s, StringBuilder out) {
  out.append('"');
  int l = s.length();
  for (int i = 0; i < l; i++) {
    char c = s.charAt(i);
    if (c == '\\' || c == '"')
      out.append('\\').append(c);
    else if (c == '\r')
      out.append("\\r");
    else if (c == '\n')
      out.append("\\n");
    else if (c == '\0')
      out.append("\\0");
    else
      out.append(c);
  }
  out.append('"');
}
static String[] toStringArray(Collection<String> c) {
  String[] a = new String[l(c)];
  Iterator<String> it = c.iterator();
  for (int i = 0; i < l(a); i++)
    a[i] = it.next();
  return a;
}

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

static 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 void assertFalse(Object o) {
  if (!(eq(o, false) /*|| isFalse(pcallF(o))*/))
    throw fail(str(o));
}
  
static boolean assertFalse(boolean b) {
  if (b) throw fail("oops");
  return b;
}

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

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

static Component frameIcon(String imageID, Component c) {
  setFrameIconLater(c, imageID);
  return c;
}
static String or2(String a, String b) {
  return nempty(a) ? a : b;
}

static String or2(String a, String b, String c) {
  return or2(or2(a, b), c);
}
static String javaxDefaultIcon() {
  return "#1005557";
}
static <A extends Component> A centerFrame(A c) {
  Window w = getWindow(c);
  if (w != null)
    w.setLocationRelativeTo(null); // magic trick
  return c;
}

static <A extends Component> A centerFrame(int w, int h, A c) {
  return centerFrame(setFrameSize(w, h, c));
}

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 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 invokeMethod(m, null, args);
    /*} else if (o instanceof DynamicMethods) {
      ret ((DynamicMethods) o)._dynCall(method, args);*/
    } else {
      Method m = callOpt_findMethod(o, method, args, false);
      if (m == null) return null;
      m.setAccessible(true);
      return invokeMethod(m, o, args);
    }
  } catch (Exception e) {
    //fail(e.getMessage() + " | Method: " + method + ", receiver: " + className(o) + ", args: (" + join(", ", map(f className, args) + ")");
    throw rethrow(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() & java.lang.reflect.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 Object getConsoleTextArea_gen() {
  return getOpt(get(getJavaX(), "console"), "textArea");
}
static Object swing(Object f) {
  return swingAndWait(f);
}

static <A> A swing(F0<A> f) {
  return (A) swingAndWait(f);
}
static JTextField consoleInputField() {
  Object console = get(getJavaX(), "console");
  return (JTextField) getOpt(console, "tfInput");
}
static void revalidateFrame(Component c) {
  revalidate(getFrame(c));
}
static String hopeningTag(String tag, Map params) {
  return hopeningTag(tag, mapToParams(params));
}

static String hopeningTag(String tag, Object... params) {
  StringBuilder buf = new StringBuilder();
  buf.append("<" + tag);
  for (int i = 0; i < l(params); i += 2) {
    String name = (String) get(params, i);
    Object val = get(params, i+1);
    if (nempty(name) && val != null) {
      String s = str(val);
      if (!empty(s))
        buf.append(" " + name + "=" + htmlQuote(s));
    }
  }
  buf.append(">");
  return str(buf);
}
static boolean neqic(String a, String b) {
  return !eqic(a, b);
}
static String[] dropLast(String[] a, int n) {
  n = Math.min(n, a.length);
  String[] b = new String[a.length-n];
  System.arraycopy(a, 0, b, 0, b.length);
  return b;
}

static <A> List<A> dropLast(List<A> l) {
  return subList(l, 0, l(l)-1);
}

static <A> List<A> dropLast(int n, List<A> l) {
  return subList(l, 0, l(l)-n);
}

static <A> List<A> dropLast(Iterable<A> l) {
  return dropLast(asList(l));
}

static String dropLast(String s) {
  return substring(s, 0, l(s)-1);
}

static String dropLast(String s, int n) {
  return substring(s, 0, l(s)-n);
}

static String dropLast(int n, String s) {
  return dropLast(s, n);
}

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


static BufferedReader bufferedReader(Reader r) {
  return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r), r);
}
static <A> CloseableIterableIterator<A> iteratorFromFunction_f0_autoCloseable(final F0<A> f, final AutoCloseable closeable) {
  class IFF2 extends CloseableIterableIterator<A> {
    A a;
    boolean done;
    
    public boolean hasNext() {
      getNext();
      return !done;
    }
    
    public A next() {
      getNext();
      if (done) throw fail();
      A _a = a;
      a = null;
      return _a;
    }
    
    void getNext() {
      if (done || a != null) return;
      a = f.get();
      done = a == null;
    }
    
    public void close() throws Exception {
      if (closeable != null) closeable.close();
    }
  };
  return new IFF2();
}
static String readLineFromReaderWithClose(BufferedReader r) { try {
  String s = r.readLine();
  if (s == null) r.close();
  return s;
} catch (Exception __e) { throw rethrow(__e); } }
static AutoCloseable _wrapIOCloseable(final AutoCloseable c) {
  return c == null ? null : new AutoCloseable() { public void close() throws Exception {
    c.close();
    _registerIO(c, null, false);
  }};
}

static <A> A _registerIOWrap(A wrapper, Object wrapped) {
  return wrapper;
}
static FileInputStream newFileInputStream(File path) throws IOException {
  return newFileInputStream(path.getPath());
}

static FileInputStream newFileInputStream(String path) throws IOException {
  FileInputStream f = new FileInputStream(path);
  _registerIO(f, path, true);
  return f;
}
static int gzInputStream_defaultBufferSize = 65536;

static GZIPInputStream gzInputStream(File f) { try {
  return gzInputStream(new FileInputStream(f));
} catch (Exception __e) { throw rethrow(__e); } }

static GZIPInputStream gzInputStream(File f, int bufferSize) { try {
  return gzInputStream(new FileInputStream(f), bufferSize);
} catch (Exception __e) { throw rethrow(__e); } }

static GZIPInputStream gzInputStream(InputStream in) {
  return gzInputStream(in, gzInputStream_defaultBufferSize);
}

static GZIPInputStream gzInputStream(InputStream in, int bufferSize) { try {
  return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in);
} catch (Exception __e) { throw rethrow(__e); } }
static 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 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();
  HashMap<Class,Field> persistenceInfo = 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) { try {
  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 Short) { short s = ((Short) o).shortValue(); d.append("sh ", 2); out.print(s); d.n += s < 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(o instanceof LinkedHashSet ? "lhs" : "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.sta..."; }});
      return;
    }
    
    if (o instanceof Map && !startsWith(name, "main$")) {
      if (o instanceof LinkedHashMap) d.append("lhm");
      else if (o instanceof HashMap) d.append("hm");
      else if (name.equals("java.util.Collections$SynchronizedMap")) d.append("sync");
      else if (name.equals("java.util.Collections$SynchronizedSortedMap")) { d.append("sync tm", 2); }
      
      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)) {
        String fieldName = field.getName();
        if (fieldName.equals("_persistenceInfo"))
          d.persistenceInfo.put(c, field);
        if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0)
          continue;

        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
  }

  Field persistenceInfoField = (Field) ( d.persistenceInfo.get(c));
  Map<String, Object> persistenceInfo = persistenceInfoField == null ? null : (Map) persistenceInfoField.get(o);
  
  LinkedHashMap<String,Object> fv = new LinkedHashMap();
  for (Field f : lFields) {
    Object value;
    try {
      value = f.get(o);
    } catch (Exception e) {
      value = "?";
    }
      
    if (value != null && (persistenceInfo == null
      || !Boolean.FALSE.equals(persistenceInfo.get(f.getName()))))
      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..."; }});
} catch (Exception __e) { throw rethrow(__e); } }

static Throwable getExceptionCause(Throwable e) {
  Throwable c = e.getCause();
  return c != null ? c : e;
}
static String joinWithSpace(Collection<String> c) {
  return join(" ", c);
}

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

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

static List<String> classNames(Object[] l) {
  return getClassNames(Arrays.asList(l));
}
static boolean isInstanceX(Class type, Object arg) {
  if (type == boolean.class) return arg instanceof Boolean;
  if (type == int.class) return arg instanceof Integer;
  if (type == long.class) return arg instanceof Long;
  if (type == float.class) return arg instanceof Float;
  if (type == short.class) return arg instanceof Short;
  if (type == char.class) return arg instanceof Character;
  if (type == byte.class) return arg instanceof Byte;
  if (type == double.class) return arg instanceof Double;
  return type.isInstance(arg);
}


static String getStackTrace2(Throwable e) {
  return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ",
    hideCredentials(str(getInnerException(e)))) + "\n");
}
static <A> A optParam(ThreadLocal<A> tl, A defaultValue) {
  return optPar(tl, defaultValue);
}

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

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

static <A> A optParam(Object[] opt, String name) {
  return optParam(opt, name, null);
}
static JFrame getFrame(final Object _o) {
  return swing(new F0<JFrame>() { JFrame get() { try { 
    Object o = _o;
    if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o));
    if (!(o instanceof Component)) return null;
    Component c = (Component) o;
    while (c != null) {
      if (c instanceof JFrame) return (JFrame) c;
      c = c.getParent();
    }
    return null;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "O o = _o;\r\n    if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button..."; }});
}
static <A> A setFrameTitle(A c, final String title) {
  final Frame f = getAWTFrame(c);
  if (f != null) { swing(new Runnable() { public void run() { try {  f.setTitle(title); 
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "f.setTitle(title);"; }}); }
  return c;
}

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

// magically find a field called "frame" in main class :-)
static JFrame setFrameTitle(String title) {
  Object f = getOpt(mc(), "frame");
  if (f instanceof JFrame)
    return setFrameTitle((JFrame) f, title);
  return null;
}
static JFrame setFrameIconLater(Component c, final String imageID) {
  final JFrame frame = getFrame(c);
  if (frame != null)
    { Thread _t_0 = new Thread("Loading Icon") {
public void run() { try {
  
      final Image i = imageIcon(or2(imageID, "#1005557")).getImage();
      swingLater(new Runnable() { public void run() { try { 
        frame.setIconImage(i);
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "frame.setIconImage(i);"; }});
    } catch (Throwable __e) { _handleException(__e); } }
};
startThread(_t_0); }
  return frame;
}
static void _initFrame(JFrame f) {
  myFrames_list.put(f, Boolean.TRUE);
  standardTitlePopupMenu(f);
}
// c = Component or something implementing swing()
static Component wrap(Object swingable) {
  return _recordNewSwingComponent(wrap_2(swingable));
}

static Component wrap_2(Object swingable) {
  if (swingable == null) return null;
  Component c;
  if (swingable instanceof Component) c = (Component) swingable;
  
  else c = (Component) callOpt(swingable, "swing");
  if (c instanceof JTable || c instanceof JList
    || c instanceof JTextArea || c instanceof JEditorPane
    || c instanceof JTextPane || c instanceof JTree)
    return jscroll(c);
  return c == null ? jlabel(str(swingable)) : c;
}
static Rectangle defaultNewFrameBounds_r = new Rectangle(300, 100, 500, 400);

static Rectangle defaultNewFrameBounds() {
  return swing(new F0<Rectangle>() { Rectangle get() { try { 
    defaultNewFrameBounds_r.translate(60, 20);
    if (!screenRectangle().contains(defaultNewFrameBounds_r))
      defaultNewFrameBounds_r.setLocation(30+random(30), 20+random(20));
    return new Rectangle(defaultNewFrameBounds_r);
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "defaultNewFrameBounds_r.translate(60, 20);\r\n    if (!screenRectangle().contai..."; }});
}
static void hideConsole() {
  final JFrame frame = consoleFrame();
  if (frame != null) {
    autoVMExit();
    swingLater(new Runnable() { public void run() { try { 
      frame.setVisible(false);
    
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "frame.setVisible(false);"; }});
  }
}
static <A> ArrayList<A> asList(A[] a) {
  return a == null ? new ArrayList<A>() : new ArrayList<A>(Arrays.asList(a));
}

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

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



static <A> ArrayList<A> asList(Enumeration<A> e) {
  ArrayList l = new ArrayList();
  if (e != null)
    while (e.hasMoreElements())
      l.add(e.nextElement());
  return l;
}
static Object collectionMutex(Object o) {
  String c = className(o);
  if (eq(c, "java.util.TreeMap$KeySet"))
    c = className(o = getOpt(o, "m"));
  else if (eq(c, "java.util.HashMap$KeySet"))
    c = className(o = get_raw(o, "this$0"));

  
  
  if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
    c = className(o = get_raw(o, "m"));
    
  
    
  return o;
}
static Runnable _topLevelErrorHandling(final Runnable runnable) {
  final Object info = _threadInfo();
  return new Runnable() { public void run() { try { 
    try {
      _threadInheritInfo(info);
      runnable.run();
    } catch (Throwable __e) { _handleException(__e); }
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "pcall {\r\n      _threadInheritInfo(info);\r\n      runnable.run();\r\n    }"; }};
}
static Map vm_generalWeakSubMap(Object name) {
  synchronized(get(javax(), "generalMap")) {
    Map map = (Map) ( vm_generalMap_get(name));
    if (map == null)
      vm_generalMap_put(name, map = newWeakMap());
    return map;
  }
}

static <A> WeakReference<A> weakRef(A a) {
  return newWeakReference(a);
}
static Class mc() {
  return main.class;
}
static Object pcallFunction(Object f, Object... args) {
  try { return callFunction(f, args); } catch (Throwable __e) { _handleException(__e); }
  return null;
}




static volatile boolean disableCertificateValidation_attempted;

static void disableCertificateValidation() { try {
  if (disableCertificateValidation_attempted) return;
  disableCertificateValidation_attempted = true;
  
  try {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { 
      new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() { 
          return new X509Certificate[0]; 
        }
        public void checkClientTrusted(X509Certificate[] certs, String authType) {}
        public void checkServerTrusted(X509Certificate[] certs, String authType) {}
    }};
  
    // Ignore differences between given hostname and certificate hostname
    HostnameVerifier hv = new HostnameVerifier() {
      public boolean verify(String hostname, SSLSession session) { return true; }
    };
  
    // Install the all-trusting trust manager
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
  } catch (Throwable __e) { _handleException(__e); }
} catch (Exception __e) { throw rethrow(__e); } }
static boolean networkAllowanceTest(String url) {
  return isAllowed("networkAllowanceTest", url);
}
static final boolean loadPageThroughProxy_enabled = false;

static String loadPageThroughProxy(String url) {
  return null;
}
static void sleepSeconds(double s) {
  if (s > 0) sleep(round(s*1000));
}
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 boolean isTrue(Object o) {
  if (o instanceof Boolean)
    return ((Boolean) o).booleanValue();
  if (o == null) return false;
  if (o instanceof ThreadLocal)
    return isTrue(((ThreadLocal) o).get());
  throw fail(getClassName(o));
}
static void printWithTime(String s) {
  print(hmsWithColons() + ": " + s);
}
static <A> A getAndClearThreadLocal(ThreadLocal<A> tl) {
  A a = tl.get();
  tl.set(null);
  return a;
}
static void setHeaders(URLConnection con) throws IOException {
  
  String computerID = getComputerID_quick();
  if (computerID != null) try {
    con.setRequestProperty("X-ComputerID", computerID);
    con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version"));
  } catch (Throwable e) {
    //printShortException(e);
  }
  
}
static <A, B> Set<A> keys(Map<A, B> map) {
  return map == null ? new HashSet() : map.keySet();
}

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






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

static String unquote(String s) {
  if (s == null) return null;
  if (startsWith(s, '[')) {
    int i = 1;
    while (i < s.length() && s.charAt(i) == '=') ++i;
    if (i < s.length() && s.charAt(i) == '[') {
      String m = s.substring(1, i);
      if (s.endsWith("]" + m + "]"))
        return s.substring(i+1, s.length()-i-1);
    }
  }
  
  if (s.length() > 1) {
    char c = s.charAt(0);
    if (c == '\"' || c == '\'') {
      int l = endsWith(s, c) ? s.length()-1 : s.length();
      StringBuilder sb = new StringBuilder(l-1);
  
      for (int i = 1; i < l; i++) {
        char ch = s.charAt(i);
        if (ch == '\\') {
          char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
          // Octal escape?
          if (nextChar >= '0' && nextChar <= '7') {
              String code = "" + nextChar;
              i++;
              if ((i < l - 1) && s.charAt(i + 1) >= '0'
                      && s.charAt(i + 1) <= '7') {
                  code += s.charAt(i + 1);
                  i++;
                  if ((i < l - 1) && s.charAt(i + 1) >= '0'
                          && s.charAt(i + 1) <= '7') {
                      code += s.charAt(i + 1);
                      i++;
                  }
              }
              sb.append((char) Integer.parseInt(code, 8));
              continue;
          }
          switch (nextChar) {
          case '\"': ch = '\"'; break;
          case '\\': ch = '\\'; break;
          case 'b': ch = '\b'; break;
          case 'f': ch = '\f'; break;
          case 'n': ch = '\n'; break;
          case 'r': ch = '\r'; break;
          case 't': ch = '\t'; break;
          case '\'': ch = '\''; break;
          // Hex Unicode: u????
          case 'u':
              if (i >= l - 5) {
                  ch = 'u';
                  break;
              }
              int code = Integer.parseInt(
                      "" + s.charAt(i + 2) + s.charAt(i + 3)
                         + s.charAt(i + 4) + s.charAt(i + 5), 16);
              sb.append(Character.toChars(code));
              i += 5;
              continue;
          default:
            ch = nextChar; // added by Stefan
          }
          i++;
        }
        sb.append(ch);
      }
      return sb.toString();
    }
  }
    
  return s; // not quoted - return original
}
static String toHex(byte[] bytes) {
  return bytesToHex(bytes);
}

static String toHex(byte[] bytes, int ofs, int len) {
  return bytesToHex(bytes, ofs, len);
}

static byte[] utf8(String s) {
  return toUtf8(s);
}
static <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); } }
static int toInt(Object o) {
  if (o == null) return 0;
  if (o instanceof Number)
    return ((Number) o).intValue();
  if (o instanceof String)
    return parseInt((String) o);
  throw fail("woot not int: " + getClassName(o));
}

static int toInt(long l) {
  if (l != (int) l) throw fail("Too large for int: " + l);
  return (int) l;
}
static URLConnection setURLConnectionDefaultTimeouts(URLConnection con, long timeout) {
  if (con.getConnectTimeout() == 0) {
    con.setConnectTimeout(toInt(timeout));
    if (con.getConnectTimeout() != timeout)
      print("Warning: URL connect timeout not set by JDK.");
  }
  if (con.getReadTimeout() == 0) {
    con.setReadTimeout(toInt(timeout));
    if (con.getReadTimeout() != timeout)
      print("Warning: URL read timeout not set by JDK.");
  }
  return con;
}
static String shortenSnippetID(String snippetID) {
  if (snippetID.startsWith("#"))
    snippetID = snippetID.substring(1);
  String httpBlaBla = "http://tinybrain.de/";
  if (snippetID.startsWith(httpBlaBla))
    snippetID = snippetID.substring(httpBlaBla.length());
  return "" + parseLong(snippetID);
}
  public static boolean isSnippetID(String s) {
    try {
      parseSnippetID(s);
      return true;
    } catch (RuntimeException e) {
      return false;
    }
  }
//static final Map<Class, HashMap<S, Field>> getOpt_cache = newDangerousWeakHashMap(f getOpt_special_init);

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

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

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

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

  Class c = o.getClass();
  HashMap<String, Field> map;
  synchronized(getOpt_cache) {
    map = getOpt_cache.get(c);
    if (map == null)
      map = getOpt_makeCache(c);
  }
  
  if (map == getOpt_special) {
    if (o instanceof Class)
      return getOpt((Class) o, field);
    /*if (o instanceof S)
      ret getOpt(getBot((S) o), field);*/
    if (o instanceof Map)
      return ((Map) o).get(field);
  }
    
  Field f = map.get(field);
  if (f != null) return f.get(o);
  
    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);
  }
  if (getOpt_cache != null) getOpt_cache.put(c, map);
  return map;
}
static List _registerWeakMap_preList;

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

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

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

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

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

static void _onLoad_registerDangerousWeakMap() {
  assertNotNull(javax());
  if (_registerDangerousWeakMap_preList == null) return;
  for (Pair p : _registerDangerousWeakMap_preList)
    _registerDangerousWeakMap(p.a, p.b);
  _registerDangerousWeakMap_preList = null;
}
static <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 Class javax() {
  return getJavaX();
}
static String fromUtf8(byte[] bytes) { try {
  return new String(bytes, "UTF-8");
} catch (Exception __e) { throw rethrow(__e); } }
static ThreadLocal < VF1 < File > > checkFileNotTooBigToRead_tl = new ThreadLocal();

static void checkFileNotTooBigToRead(File f) {
  callF(checkFileNotTooBigToRead_tl.get(), f);
}
static File newFile(File base, String... names) {
  for (String name : names) base = new File(base, name);
  return base;
}

static File newFile(String name) {
  return name == null ? null : new File(name);
}
static 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 void logQuotedWithTime(String s) {
  logQuotedWithTime(standardLogFile(), s);
}

static void logQuotedWithTime(File logFile, String s) {
  logQuoted(logFile, logQuotedWithTime_format(s));
}

static void logQuotedWithTime(String logFile, String s) {
  logQuoted(logFile, logQuotedWithTime_format(s));
}

static String logQuotedWithTime_format(String s) {
  return formatGMTWithDate_24(now()) + " " + s;
}
static File javaxDataDir_dir; // can be set to work on different base dir

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

static File javaxDataDir(String sub) {
  return newFile(javaxDataDir(), sub);
}
static Runnable addThreadInfoToRunnable(final Object r) {
  final Object info = _threadInfo();
  return info == null ? asRunnable(r) : new Runnable() { public void run() { try {  _inheritThreadInfo(info); callF(r); 
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "_inheritThreadInfo(info); callF(r);"; }};
}
static JTextArea wrappedTextArea(final JTextArea ta) {
  enableWordWrapForTextArea(ta);
  return ta;
}

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

static JTextArea wrappedTextArea(String text) {
  JTextArea ta = wrappedTextArea();
  ta.setText(text);
  return ta;
}
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 void disposeWindow(final Window window) {
  if (window != null) { swing(new Runnable() { public void run() { try { 
    window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); // call listeners
    myFrames_list.remove(window);
    window.dispose();
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); //..."; }}); }
}

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

static void disposeWindow(Object o) {
  if (o != null) disposeWindow(((Component) o));
}

static void disposeWindow() {
  disposeWindow(heldInstance(Component.class));
}
static 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 int withMargin_defaultWidth = 6;

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

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

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

static JPanel withMargin(final int top, final int left, final int bottom, final int right, final Component c) {
  return swing(new F0<JPanel>() { JPanel get() { try { 
    JPanel p = new JPanel(new BorderLayout());
    p.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right));
    p.add(c);
    return p;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n    p.setBorder(BorderFactory.creat..."; }});
}
static 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 Dimension getScreenSize() {
  return Toolkit.getDefaultToolkit().getScreenSize();
}
static void swingLater(long delay, final Object r) {
  javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(wrapAsActivity(r)));
  timer.setRepeats(false);
  timer.start();
}

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

static int toMS_int(double seconds) {
  return toInt_checked((long) (seconds*1000));
}
static String getStackTrace(Throwable throwable) {
  lastException(throwable);
  return getStackTrace_noRecord(throwable);
}

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

static String getStackTrace() {
  return getStackTrace_noRecord(new Throwable());
}
// PersistableThrowable doesn't hold GC-disturbing class references in backtrace
static volatile PersistableThrowable lastException_lastException;

static PersistableThrowable lastException() {
  return lastException_lastException;
}

static void lastException(Throwable e) {
  lastException_lastException = persistableThrowable(e);
}
static Throwable getInnerException(Throwable e) {
  while (e.getCause() != null)
    e = e.getCause();
  return e;
}
static String unnull(String s) {
  return s == null ? "" : s;
}

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

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

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

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

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



//ifclass Symbol

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

static String baseClassName(Object o) {
  return baseClassName(getClassName(o));
}
static String prependIfNempty(String prefix, String s) {
  return empty(s) ? s : prefix + s;
}
static ReentrantLock fairLock() {
  return new ReentrantLock(true);
}
static void lockOrFail(Lock lock, long timeout) { try {
  ping();
  if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
    String s = "Couldn't acquire lock after " + timeout + " ms.";
    if (lock instanceof ReentrantLock) {
      ReentrantLock l = (ReentrantLock) ( lock);
      s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
    }
    throw fail(s);
  }
  ping();
} catch (Exception __e) { throw rethrow(__e); } }
static 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.space/images/raw/title/" + parsedID + muricaCredentialsQuery();
  else if (isGeneralFileServerSnippet(parsedID))
    url = "http://butter.botcompany.de:8080/files/name/" + parsedID;
  else
    url = tb_mainServer() + "/tb-int/getfield.php?id=" + parsedID + "&field=title" + standardCredentials_noCookies();
  return or2(trim(loadPageSilently(url)), "?");
} catch (Exception __e) { throw rethrow(__e); } }

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

static boolean isNormalQuoted(String s) {
  int l = l(s);
  if (!(l >= 2 && s.charAt(0) == '"' && lastChar(s) == '"')) return false;
  int j = 1;
  while (j < l)
    if (s.charAt(j) == '"')
      return j == l-1;
    else if (s.charAt(j) == '\\' && j+1 < l)
      j += 2;
    else
      ++j;
  return false;
}
static boolean isMultilineQuoted(String s) {
  if (!startsWith(s, "[")) return false;
  int i = 1;
  while (i < s.length() && s.charAt(i) == '=') ++i;
  return i < s.length() && s.charAt(i) == '[';
}
static void revalidate(final Component c) {
  if (c == null || !c.isShowing()) return;
  { swing(new Runnable() { public void run() { try { 
    // magic combo to actually relayout and repaint
    c.revalidate();
    c.repaint();
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "// magic combo to actually relayout and repaint\r\n    c.revalidate();\r\n    c.r..."; }}); }
}

static void revalidate(RootPaneContainer c) { revalidate((Component) c); }
static void revalidate(JFrame f) { revalidate((Component) f); }
static void revalidate(JInternalFrame f) { revalidate((Component) f); }
static Object[] mapToParams(Map map) {
  return mapToObjectArray(map);
}
static String htmlQuote(String s) {
  return "\"" + htmlencode_forParams(s) + "\"";
}
static boolean eqic(String a, String b) {
  
  
    if ((a == null) != (b == null)) return false;
    if (a == null) return true;
    return a.equalsIgnoreCase(b);
  
}



static boolean eqic(char a, char b) {
  if (a == b) return true;
  
    char u1 = Character.toUpperCase(a);
    char u2 = Character.toUpperCase(b);
    if (u1 == u2) return true;
  
  return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static 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 boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
  
  
    return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
  
}
static void _registerIO(Object object, String path, boolean opened) {
}
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 int parseInt(String s) {
  return empty(s) ? 0 : Integer.parseInt(s);
}

static int parseInt(char c) {
  return Integer.parseInt(str(c));
}
static <A> A assertEquals(Object x, A y) {
  return assertEquals(null, x, y);
}

static <A> A assertEquals(String msg, Object x, A y) {
  if (assertVerbose()) return assertEqualsVerbose(msg, x, y);
  if (!(x == null ? y == null : x.equals(y)))
    throw fail((msg != null ? msg + ": " : "") + y + " != " + x);
  return y;
}
static List<String> javaTokC(String s) {
  if (s == null) return null;
  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(javaTok_substringC(s, i, j));
    i = j;
  }
  
  return tok;
}
static <A> A popLast(List<A> l) {
  return liftLast(l);
}
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 if (c == '\0')
      out.print("\\0");
    else
      out.print(c);
  }
  out.print('"');
}
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 int shorten_default = 100;

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

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

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

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

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



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


static String boolArrayToHex(boolean[] a) {
  return bytesToHex(boolArrayToBytes(a));
}
static Iterator emptyIterator() {
  return Collections.emptyIterator();
}
static String shortDynamicClassName(Object o) {
 if (o instanceof DynamicObject && ((DynamicObject) o).className != null)
    return ((DynamicObject) o).className;
  return shortClassName(o);
}
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 Map<Class, Field[]> getDeclaredFields_cache = newDangerousWeakHashMap();

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 dropPrefix(String prefix, String s) {
  return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
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 <A, B, C> A first(T3<A, B, C> t) {
  return t == null ? null : t.a;
}

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


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

static List<JFrame> myFrames() {
  return swing(new F0<List<JFrame>>() { List<JFrame> get() { try { return  keysList(myFrames_list) ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "keysList(myFrames_list)"; }});
}

static Throwable unwrapTrivialExceptionWraps(Throwable e) {
  if (e == null) return e;
  while (e.getClass() == RuntimeException.class
    && e.getCause() != null && eq(e.getMessage(), str(e.getCause())))
    e = e.getCause();
  return e;
}
static String replacePrefix(String prefix, String replacement, String s) {
  if (!startsWith(s, prefix)) return s;
  return replacement + substring(s, l(prefix));
}
static <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 boolean even(int i) {
  return (i & 1) == 0;
}

static boolean even(long i) {
  return (i & 1) == 0;
}
static List<AbstractButton> buttonsInGroup(ButtonGroup g) {
  if (g == null) return ll();
  return asList(g.getElements());
}
static Frame getAWTFrame(final Object _o) {
  return swing(new F0<Frame>() { Frame get() { try { 
    Object o = _o;
    /*
    ifdef HaveProcessing
      if (o instanceof PApplet) o = ((PApplet) o).getSurface();
    endifdef
    */
    if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o));
    if (!(o instanceof Component)) return null;
    Component c = (Component) o;
    while (c != null) {
      if (c instanceof Frame) return (Frame) c;
      c = c.getParent();
    }
    return null;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "O o = _o;\r\n    /*\r\n    ifdef HaveProcessing\r\n      if (o instanceof PApplet) ..."; }});
}
static int imageIcon_cacheSize = 10;
static boolean imageIcon_verbose;
static Map<String, ImageIcon> imageIcon_cache;
static Lock imageIcon_lock = lock();
static ThreadLocal<Boolean> imageIcon_fixGIF = new ThreadLocal();

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

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


static void standardTitlePopupMenu(final JFrame frame) {
  // standard right-click behavior on titles
  if (isSubstanceLAF())
    titlePopupMenu(frame,
      new VF1<JPopupMenu>() { public void get(JPopupMenu menu) { try { 
        boolean alwaysOnTop = frame.isAlwaysOnTop();
        menu.add(jmenuItem("Restart Program", "restart"));
        menu.add(jmenuItem("Duplicate Program", "duplicateThisProgram"));
        menu.add(jmenuItem("Show Console", "showConsole"));
        menu.add(jCheckBoxMenuItem("Always On Top", alwaysOnTop, new Runnable() { public void run() { try { 
          toggleAlwaysOnTop(frame) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "toggleAlwaysOnTop(frame)"; }}));
        menu.add(jMenuItem("Shoot Window", new Runnable() { public void run() { try {  shootWindowGUI_external(frame, 500) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "shootWindowGUI_external(frame, 500)"; }}));
        //addMenuItem(menu, "Bigger fonts", f swingBiggerFonts);
        //addMenuItem(menu, "Smaller fonts", f swingSmallerFonts);
       } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "bool alwaysOnTop = frame.isAlwaysOnTop();\r\n        menu.add(jmenuItem(\"Restar..."; }});
}

static <A extends Component> A _recordNewSwingComponent(A c) {
  if (c != null)
    callF(vm_generalMap_get("newSwingComponentRegistry"), c);
  return c;
}
static JLabel jlabel(final String text) {
  return swingConstruct(BetterLabel.class, text);
}

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

static 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) {
  if (c instanceof List) return random((List<A>) c);
  int i = random(l(c));
  return collectionGet(c, i);
}
static void autoVMExit() {
  call(getJavaX(), "autoVMExit");
}
static String className(Object o) {
  return getClassName(o);
}
static List<VF1<Map>> _threadInfo_makers = synchroList();

static Object _threadInfo() {
  if (empty(_threadInfo_makers)) return null;
  HashMap map = new HashMap();
  pcallFAll(_threadInfo_makers, map);
  return map;
}
static List<VF1<Map>> _threadInheritInfo_retrievers = synchroList();

static void _threadInheritInfo(Object info) {
  if (info == null) return;
  pcallFAll(_threadInheritInfo_retrievers, (Map) info);
}
static <A> A vm_generalMap_get(Object key) {
  return (A) vm_generalMap().get(key);
}
static Object vm_generalMap_put(Object key, Object value) {
  return mapPutOrRemove(vm_generalMap(), key, value);
}
static <A, B> Map<A, B> newWeakMap() {
  return newWeakHashMap();
}
static <A> WeakReference<A> newWeakReference(A a) {
  return a == null ? null : new WeakReference(a);
}
static Object callFunction(Object f, Object... args) {
  return callF(f, args);
}
static volatile Object isAllowed_function; // func(S, O[]) -> bool
static volatile boolean isAllowed_all = true;

static boolean isAllowed(String askingMethod, Object... args) {
  // check on VM level
  Object f = vm_generalMap_get("isAllowed_function");
  if (f != null && !isTrue(callF(f, askingMethod, args))) return false;
  
  // check locally
  return isAllowed_all || isTrue(callF(isAllowed_function, askingMethod, args));
}
static long round(double d) {
  return Math.round(d);
}
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);
}



static String hmsWithColons() {
  return hmsWithColons(now());
}

static String hmsWithColons(long time) {
  return new SimpleDateFormat("HH:mm:ss").format(time);
}

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

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



static byte[] toUtf8(String s) { try {
  return s.getBytes("UTF-8");
} catch (Exception __e) { throw rethrow(__e); } }
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 void clear(Collection c) {
  if (c != null) c.clear();
}
static <A, B> void put(Map<A, B> map, A a, B b) {
  if (map != null) map.put(a, b);
}
static boolean isSubtypeOf(Class a, Class b) {
  return b.isAssignableFrom(a); // << always hated that method, let's replace it!
}
static void printException(Throwable e) {
  printStackTrace(e);
}
static <A> A assertNotNull(A a) {
  assertTrue(a != null);
  return a;
}

static <A> A assertNotNull(String msg, A a) {
  assertTrue(msg, a != null);
  return a;
}
static Map synchroHashMap() {
  return Collections.synchronizedMap(new HashMap());
}

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

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

static File userDir(String path) {
  return new File(userHome(), path);
}
static File standardLogFile() {
  return getProgramFile("log");
}
static void logQuoted(String logFile, String line) {
  logQuoted(getProgramFile(logFile), line);
}

static void logQuoted(File logFile, String line) {
  appendToFile(logFile, quote(line) + "\n");
}


static String formatGMTWithDate_24(long time) {
  return simpleDateFormat_GMT("yyyy/MM/dd").format(time) + " " + formatGMT_24(time);
}
static long now_virtualTime;
static long now() {
  return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}

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


static void _inheritThreadInfo(Object info) {
  _threadInheritInfo(info);
}
static void enableWordWrapForTextArea(final JTextArea ta) {
  if (ta != null) { swing(new Runnable() { public void run() { try { 
    ta.setLineWrap(true);
    ta.setWrapStyleWord(true);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "ta.setLineWrap(true);\r\n    ta.setWrapStyleWord(true);"; }}); }
}
static JTextArea jtextarea() {
  return jTextArea();
}

static JTextArea jtextarea(String text) {
  return jTextArea(text);
}
static JTextField onEnter(final JTextField tf, final Object action) {
  if (action == null || tf == null) return tf;
  tf.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
    tf.selectAll();
    callF(action);
  } catch (Throwable __e) { messageBox(__e); }}});
  return tf;
}

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

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

// 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 JTable onEnter(final JTable table, final Object action) {  
  table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
    .put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
    
  table.getActionMap().put("Enter", new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
      callF(action, table.getSelectedRow());
    }
  });
  return table;
}

/*static JTextArea onEnter(final JTextArea ta, fO action) {
  addKeyListener(ta, enterKeyListener(action));
  ret ta;
}*/
static <A> A heldInstance(Class<A> c) {
  List<Object> l = holdInstance_l.get();
  for (int i = l(l)-1; i >= 0; i--) {
    Object o = l.get(i);
    if (isInstanceOf(o, c))
      return (A) o;
  }
  throw fail("No instance of " + className(c) + " held");
}
static ActionListener actionListener(final Object runnable) {
  return actionListener(runnable, null);
}

static ActionListener actionListener(final Object runnable, final Object instanceToHold) {
  if (runnable instanceof ActionListener) return (ActionListener) runnable;
  final Object info = _threadInfo();
  return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
    _threadInheritInfo(info);
     AutoCloseable __193 = holdInstance(instanceToHold); try {
    callF(runnable);
  } finally { _close(__193); }} catch (Throwable __e) { messageBox(__e); }}};
}
static int toInt_checked(long l) {
  if (l != (int) l) throw fail("Too large for int: " + l);
  return (int) l;
}
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 Map emptyMap() {
  return new HashMap();
}
static boolean isImageServerSnippet(long id) {
  return id >= 1100000 && id < 1200000;
}
static String muricaCredentialsQuery() {
  return htmlQuery(muricaCredentials());
}
static boolean isGeneralFileServerSnippet(long id) {
  return id >= 1400000 && id < 1500000;
}
static String standardCredentials_noCookies() {
  return standardCredentials() + "&noCookies=1";
}
static String fsI(String id) {
  return formatSnippetID(id);
}

static String fsI(long id) {
  return formatSnippetID(id);
}
static char lastChar(String s) {
  return empty(s) ? '\0' : s.charAt(l(s)-1);
}
static Object[] mapToObjectArray(Map map) {
  List l = new ArrayList();
  for (Object o : keys(map)) {
    l.add(o);
    l.add(map.get(o));
  }
  return toObjectArray(l);
}
static String htmlencode_forParams(String s) {
  if (s == null) return "";
  StringBuilder out = new StringBuilder(Math.max(16, s.length()));
  for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      /*if (c >= 0x100)
        out.append("&#x").append(charToHex(c)).append(';');
      else*/ if (c > 127 || c == '"' || c == '<' || c == '>') {
          out.append("&#");
          out.append((int) c);
          out.append(';');
      } else
          out.append(c);
  }
  return out.toString();
}
static String asString(Object o) {
  return o == null ? null : o.toString();
}
static ThreadLocal<Boolean> assertVerbose_value = new ThreadLocal();

static void assertVerbose(boolean b) {
  assertVerbose_value.set(b);
}

static boolean assertVerbose() { return isTrue(assertVerbose_value.get()); }
static <A> A assertEqualsVerbose(Object x, A y) {
  assertEqualsVerbose((String) null, x, y);
  return y;
}

static <A> A assertEqualsVerbose(String msg, Object x, A y) {
  if (!eq(x, y)) {
    

    throw fail((msg != null ? msg + ": " : "") + /*sfu*/(y) + " != " + /*sfu*/(x));
  } else
    print("OK: " + /*sfu*/(x));
  return y;
}


static <A> A liftLast(List<A> l) {
  if (l.isEmpty()) return null;
  int i = l(l)-1;
  A a = l.get(i);
  l.remove(i);
  return a;
}
static int min(int a, int b) {
  return Math.min(a, b);
}

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

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

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

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

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

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

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

static int min(int[] c) {
  int x = Integer.MAX_VALUE;
  for (int d : c) if (d < x) x = d;
  return x;
}
static 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 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 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 void restart() {
  Object j = getJavaX();
  call(j, "cleanRestart", get(j, "fullArgs"));
}
static void duplicateThisProgram() {
  nohupJavax(trim(programID() + " " + smartJoin((String[]) get(getJavaX(), "fullArgs"))));
}
static ThreadLocal < List < Object > > holdInstance_l = new ThreadLocal();

static AutoCloseable holdInstance(Object o) {
  if (o == null) return null;
  listThreadLocalAdd(holdInstance_l, o);
  return new AutoCloseable() {
    public void close() {
      listThreadLocalPopLast(holdInstance_l);
    }
  };
}
static <A, B> Map<A, B> weakHashMap() {
  return newWeakHashMap();
}
static <A, B> List<A> keysList(Map<A, B> map) {
  return cloneListSynchronizingOn(keys(map), map);
}
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 boolean loadBufferedImageFixingGIFs_debug;
static ThreadLocal<Var<byte[]>> loadBufferedImageFixingGIFs_output = new ThreadLocal();

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

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

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

  int numImages = reader.getNumImages(true);

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

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

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

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

              break;
          }
      }
  }

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

      writer.prepareWriteSequence(null);

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

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

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

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

                  break;
              }
          }

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

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

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

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

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

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


static boolean isSubstanceLAF() {
  return substanceLookAndFeelEnabled();
}
// menuMaker = voidfunc(JPopupMenu)
static void titlePopupMenu(final Component c, final Object menuMaker) {
  JComponent titleBar = getTitlePaneComponent(getPossiblyInternalFrame(c));
  if (titleBar == null)
    print("Can't add title right click!");
  else
    componentPopupMenu(titleBar, menuMaker);
}
static boolean jmenuItem_newThreads;

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

static JMenuItem jmenuItem(final String text, final Object r) {
  return swing(new F0<JMenuItem>() { JMenuItem get() { try { 
    Pair<String, Integer> p = jmenu_autoMnemonic(text);
    JMenuItem mi = new JMenuItem(p.a);
    if (p.b != 0) mi.setMnemonic(p.b);
    mi.addActionListener(jmenuItem_newThreads
      ? actionListenerInNewThread(r)
      : actionListener(r));
    return mi;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "Pair<S, Int> p = jmenu_autoMnemonic(text);\r\n    JMenuItem mi = new JMenuItem(..."; }});
}
static JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, final Object r) {
  JCheckBoxMenuItem mi = new JCheckBoxMenuItem(text, checked);
  mi.addActionListener(actionListener(r));
  return mi;
}
static void toggleAlwaysOnTop(JFrame frame) {
  frame.setAlwaysOnTop(!frame.isAlwaysOnTop());
}
static JMenuItem jMenuItem(final String text) {
  return jmenuItem(text);
}

static JMenuItem jMenuItem(String text, Object r) {
  return jmenuItem(text, r);
}
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 <A> A swingConstruct(final Class<A> c, final Object... args) {
  return swing(new F0<A>() { A get() { try { return  nuObject(c, args) ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "nuObject(c, args)"; }});
}
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 <A> A collectionGet(Collection<A> c, int idx) {
  if (c == null || idx < 0 || idx >= l(c)) return null;
  if (c instanceof List) return listGet((List<A>) c, idx);
  Iterator<A> it = c.iterator();
  for (int i = 0; i < idx; i++) if (it.hasNext()) it.next(); else return null;
  return it.hasNext() ? it.next() : null;
}
static void pcallFAll(Collection l, Object... args) {
  if (l != null) for (Object f : cloneList(l)) pcallF(f, args);
}
static Map vm_generalMap_map;

static Map vm_generalMap() {
  if (vm_generalMap_map == null)
    vm_generalMap_map = (Map) get(javax(), "generalMap");
  return vm_generalMap_map;
}
static <A, B> B mapPutOrRemove(Map<A, B> map, A key, B value) {
  if (map != null && key != null)
    if (value != null) return map.put(key, value);
    else return map.remove(key);
  return null;
}
static File getProgramDir() {
  return programDir();
}

static File getProgramDir(String snippetID) {
  return programDir(snippetID);
}
static String _computerID;
static Lock computerID_lock = lock();

public static String computerID() {
  if (_computerID == null) {
    Lock __767 = computerID_lock; lock(__767); try {
    if (_computerID != null) return _computerID;
    File file = computerIDFile();
    _computerID = loadTextFile(file.getPath());
    if (_computerID == null) {
      // legacy load
      _computerID = loadTextFile(userDir(".tinybrain/computer-id"));
      if (_computerID == null)
        _computerID = makeRandomID(12);
      saveTextFile(file, _computerID);
    }
  } finally { unlock(__767); } }
  return _computerID;
}
static String dropSuffix(String suffix, String s) {
  return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static void assertTrue(Object o) {
  if (!(eq(o, true) /*|| isTrue(pcallF(o))*/))
    throw fail(str(o));
}
  
static boolean assertTrue(String msg, boolean b) {
  if (!b)
    throw fail(msg);
  return b;
}

static boolean assertTrue(boolean b) {
  if (!b)
    throw fail("oops");
  return b;
}
static Lock appendToFile_lock = lock();
static boolean appendToFile_keepOpen;
static HashMap<String,Writer> appendToFile_writers = new HashMap();

static void appendToFile(String path, String s) { try {
  Lock __213 = appendToFile_lock; lock(__213); try { // Let's just generally synchronize this to be safe.
  mkdirsForFile(new File(path));
  path = getCanonicalPath(path);
  Writer writer = appendToFile_writers.get(path);
  if (writer == null) {
    //print("[Logging to " + path + "]");
    writer = new BufferedWriter(new OutputStreamWriter(
      newFileOutputStream(path, true), "UTF-8"));
    if (appendToFile_keepOpen)
      appendToFile_writers.put(path, writer);
  }
  writer.write(s);
  if (!appendToFile_keepOpen)
    writer.close();
} finally { unlock(__213); } } catch (Exception __e) { throw rethrow(__e); } }
  
static void appendToFile(File path, String s) {
  if (path != null)
    appendToFile(path.getPath(), s);
}

static void cleanMeUp_appendToFile() {
  Lock __214 = appendToFile_lock; lock(__214); try {
  closeAllWriters(values(appendToFile_writers));
  appendToFile_writers.clear();
} finally { unlock(__214); } }


static SimpleDateFormat simpleDateFormat_GMT(String format) {
  SimpleDateFormat sdf = new SimpleDateFormat(format);
  sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
  return sdf;
}


static String formatGMT_24(long time) {
  SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
  sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
  return sdf.format(time) + " GMT";
}
static JTextArea jTextArea() {
  return jTextArea("");
}

static JTextArea jTextArea(final String text) {
  return swingNu(JTextArea.class, text);
}
static void messageBox(final String msg) {
  if (headless()) print(msg);
  else { swing(new Runnable() { public void run() { try { 
    JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MES..."; }}); }
}

static void messageBox(Throwable e) {
  //showConsole();
  printStackTrace(e);
  messageBox(hideCredentials(innerException(e)));
}
static KeyListener enterKeyListener(final Object action) {
  return new KeyAdapter() {
    public void keyReleased(KeyEvent ke) {
      if (ke.getKeyCode() == KeyEvent.VK_ENTER)
        pcallF(action);
    }
  };
}
static Runnable rCallOnSelectedListItem(final JList list, final Object action) {
  return new Runnable() { public void run() { try {  pcallF(action, getSelectedItem(list)) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "pcallF(action, getSelectedItem(list))"; }};
}
static boolean isInstanceOf(Object o, Class type) {
  return type.isInstance(o);
}
static String htmlQuery(Map params) {
  return params.isEmpty() ? "" : "?" + makePostData(params);
}

static String htmlQuery(Object... data) {
  return htmlQuery(litmap(data));
}
static Object[] muricaCredentials() {
  String pass = muricaPassword();
  return nempty(pass) ? new Object[] {"_pass", pass } : new Object[0];
}
static String standardCredentials() {
  String user = standardCredentialsUser();
  String pass = standardCredentialsPass();
  if (nempty(user) && nempty(pass))
    return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
  return "";
}
static Object[] toObjectArray(Collection c) {
  List l = asList(c);
  return l.toArray(new Object[l.size()]);
}

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 void nohupJavax(final String javaxargs) {
  { Thread _t_0 = new Thread() {
public void run() { try { call(hotwireOnce("#1008562"), "nohupJavax", javaxargs); } catch (Throwable __e) { _handleException(__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) { _handleException(__e); } }
};
startThread(_t_1); }
}
static <A> void listThreadLocalAdd(ThreadLocal<List<A>> tl, A a) {
  List<A> l = tl.get();
  if (l == null) tl.set(l = new ArrayList());
  l.add(a);
}
static <A> A listThreadLocalPopLast(ThreadLocal<List<A>> tl) {
  List<A> l = tl.get();
  if (l == null) return null;
  A a = popLast(l);
  if (empty(l)) tl.set(null);
  return a;
}
static <A> ArrayList<A> cloneListSynchronizingOn(Collection<A> l, Object mutex) {
  if (l == null) return new ArrayList();
  synchronized(mutex) {
    return new ArrayList<A>(l);
  }
}
// If you change this, also change DiskSnippetCache_fileToLibID
static File DiskSnippetCache_file(long snippetID) {
  return new File(getGlobalCache(), "data_" + snippetID + ".jar");
}
  
  // Data files are immutable, use centralized cache
public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
  File file = DiskSnippetCache_file(snippetID);
  return file.exists() ? file : null;
}

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

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

static File loadDataSnippetToFile(String snippetID) { try {
  snippetID = fsI(snippetID);
  File f = DiskSnippetCache_file(parseSnippetID(snippetID));
  List<URL> urlsTried = new ArrayList();
  List<Throwable> errors = new ArrayList();
  try {
    URL url = addAndReturn(urlsTried, new URL(dataSnippetLink(snippetID)));
    print("Loading library: " + hideCredentials(url));
    try {
      loadBinaryPageToFile(openConnection(url), f);
      if (fileSize(f) == 0) throw fail();
    } catch (Throwable e) {
      errors.add(e);
      url = addAndReturn(urlsTried, new URL("http://data.tinybrain.de/blobs/"
        + psI(snippetID)));
      print("Trying other server: " + hideCredentials(url));
      loadBinaryPageToFile(openConnection(url), f);
      print("Got bytes: " + fileSize(f));
    }
    // TODO: check if we hit the "LOADING" message
    if (fileSize(f) == 0) throw fail();
    System.err.println("Bytes loaded: " + fileSize(f));
  } catch (Throwable e) {
    printStackTrace(e);
    errors.add(e);
    throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors));
  }
  return f;
} catch (Exception __e) { throw rethrow(__e); } }
static byte[] isGIF_magic = bytesFromHex("47494638"); // Actual signature is longer, but we're lazy

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

static boolean isGIF(File f) {
  return isGIF(loadBeginningOfBinaryFile(f, l(isGIF_magic)));
}
static String f2s(File f) {
  return f == null ? null : f.getAbsolutePath();
}

static String f2s(java.nio.file.Path p) {
  return p == null ? null : f2s(p.toFile());
}
static <A> void setVar(Var<A> v, A value) {
  if (v != null) v.set(value);
}
static boolean substanceLookAndFeelEnabled() {
  return startsWith(getLookAndFeel(), "org.pushingpixels.");
}
static JComponent getTitlePaneComponent(RootPaneContainer window) {
  if (window instanceof JInternalFrame)
	  return getInternalFrameTitlePaneComponent((JInternalFrame) window);
	  
  if (!substanceLookAndFeelEnabled() || window == null) return null;
	JRootPane rootPane = window.getRootPane();
	if (rootPane != null) {
		Object /*SubstanceRootPaneUI*/ ui = rootPane.getUI();
		return (JComponent) call(ui, "getTitlePane");
	}
	return null;
}
static RootPaneContainer getPossiblyInternalFrame(Component c) {
  JInternalFrame f = getInternalFrame(c);
  if (f != null) return f;
  return optCast(RootPaneContainer.class, getWindow(c));
}


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

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

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

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

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


static Pair<String, Integer> jmenu_autoMnemonic(String s) {
  int i = indexOf(s, '&');
  if (i >= 0 && i < l(s) && isLetterOrDigit(s.charAt(i+1)))
    return pair(substring(s, 0, i) + substring(s, i+1), (int) s.charAt(i+1));
  return pair(s, 0);
}
static ActionListener actionListenerInNewThread(final Object runnable) {
  return actionListenerInNewThread(runnable, null);
}

static ActionListener actionListenerInNewThread(final Object runnable, final Object instanceToHold) {
  if (runnable instanceof ActionListener) return (ActionListener) runnable;
  return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
    { Thread _t_0 = new Thread("Action Listener") {
public void run() { try {
  
       AutoCloseable __1064 = holdInstance(instanceToHold); try {
      callF(runnable);
    } finally { _close(__1064); }} catch (Throwable __e) { _handleException(__e); } }
};
startThread(_t_0); }
  } catch (Throwable __e) { messageBox(__e); }}};
}
static Class hotwireOnce(String programID) {
  return hotwireCached(programID, false);
}
static Object nuObject(String className, Object... args) { try {
  return nuObject(classForName(className), args);
} catch (Exception __e) { throw rethrow(__e); } }

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

static <A> A nuObject(Class<A> c, Object... args) { try {
  if (args.length == 0) return nuObjectWithoutArguments(c); // cached!
  
  Constructor m = nuObject_findConstructor(c, args);
  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() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}

 static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
    if (types.length != args.length) {
      if (debug)
        System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
      return false;
    }
    for (int i = 0; i < types.length; i++)
      if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
        if (debug)
          System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
        return false;
      }
    return true;
  }
static <A> A listGet(List<A> l, int idx) {
  return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
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 File programDir(String snippetID, String subPath) {
  return new File(programDir(snippetID), subPath);
}
static File computerIDFile() {
  return javaxDataDir("Basic Info/computer-id.txt");
}
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);
}
/** writes safely (to temp file, then rename) */
static File saveTextFile(String fileName, String contents) throws IOException {
  CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
  try {
    File file = new File(fileName);
    mkdirsForFile(file);
    String tempFileName = fileName + "_temp";
    File tempFile = new File(tempFileName);
    if (contents != null) {
      if (tempFile.exists()) try {
        String saveName = tempFileName + ".saved." + now();
        copyFile(tempFile, new File(saveName));
      } catch (Throwable e) { printStackTrace(e); }
      FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
      OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
      PrintWriter printWriter = new PrintWriter(outputStreamWriter);
      printWriter.print(contents);
      printWriter.close();
    }
    
    if (file.exists() && !file.delete())
      throw new IOException("Can't delete " + fileName);
  
    if (contents != null)
      if (!tempFile.renameTo(file))
        throw new IOException("Can't rename " + tempFile + " to " + file);
        
    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); } }
public static File mkdirsForFile(File file) {
  File dir = file.getParentFile();
  if (dir != null) { // is null if file is in current dir
    dir.mkdirs();
    if (!dir.isDirectory())
      if (dir.isFile()) throw fail("Please delete the file " + f2s(dir) + " - it is supposed to be a directory!");
      else throw fail("Unknown IO exception during mkdirs of " + f2s(file));
  }
  return file;
}

public static String mkdirsForFile(String path) {
  mkdirsForFile(new File(path));
  return path;
}
static String getCanonicalPath(String path) { try {
  return new File(path).getCanonicalPath();
} catch (Exception __e) { throw rethrow(__e); } }
static FileOutputStream newFileOutputStream(File path) throws IOException {
  return newFileOutputStream(path.getPath());
}

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

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

static FileOutputStream newFileOutputStream(String path, boolean append) throws IOException {
  mkdirsForFile(path);
  FileOutputStream f = new FileOutputStream(path, append);
  
  _registerIO(f, path, true);
  
  return f;
}
static void closeAllWriters(Collection<? extends Writer> l) {
  for (Writer w : unnull(l)) try {
    w.close();
  } catch (Throwable __e) { _handleException(__e); }
}
static <A, B> Collection<B> values(Map<A, B> map) {
  return map == null ? emptyList() : map.values();
}




static <A> A swingNu(final Class<A> c, final Object... args) {
  return swingConstruct(c, args);
}
static Throwable innerException(Throwable e) {
  return getInnerException(e);
}
static String getSelectedItem(JList l) {
  return (String) l.getSelectedValue();
}

static String getSelectedItem(JComboBox cb) {
  return strOrNull(cb.getSelectedItem());
}
static String makePostData(Map<Object, Object> map) {
  List<String> l = new ArrayList();
  for (Map.Entry<Object, Object> e : map.entrySet()) {
    String key = (String) ( e.getKey());
    Object val = e.getValue();
    if (val != null) {
      String value = str(val); //structureOrText(val);
      l.add(urlencode(key) + "=" + urlencode(/*escapeMultichars*/(value)));
    }
  }
  return join("&", l);
}

static String makePostData(Object... params) {
  return makePostData(litorderedmap(params));
}

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

static void litmap_impl(Map map, Object... x) {
  for (int i = 0; i < x.length-1; i += 2)
    if (x[i+1] != null)
      map.put(x[i], x[i+1]);
}
static volatile boolean muricaPassword_pretendNotAuthed;

static String muricaPassword() {
  if (muricaPassword_pretendNotAuthed) return null;
  return trim(loadTextFile(muricaPasswordFile()));
}
static String standardCredentialsUser() {
  return trim(loadTextFile(new File(userHome(), ".tinybrain/username")));
}
static String standardCredentialsPass() {
  return trim(loadTextFile(new File(userHome(), ".tinybrain/userpass")));
}
static String urlencode(String x) {
  try {
    return URLEncoder.encode(unnull(x), "UTF-8");
  } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); }
}
static int lastIndexOf(String a, String b) {
  return a == null || b == null ? -1 : a.lastIndexOf(b);
}

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


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

  /** 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 >= 1100000 && id < 1200000)
    return "http://ai1.space/images/raw/" + id;
  if (id >= 1400000 && id < 1500000)
    return "http://butter.botcompany.de:8080/files/" + id + "?_pass=" + muricaPassword();
  if (id >= 1200000 && id < 1300000) { // Woody files, actually
    String pw = muricaPassword();
    if (empty(pw)) throw fail("Please set 'murica password by running #1008829");
    return "http://butter.botcompany.de:8080/1008823/raw/" + id + "?_pass=" + pw; // 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 ThreadLocal<Map<String, List<String>>> loadBinaryPage_responseHeaders = new ThreadLocal();
static ThreadLocal<Map<String, String>> loadBinaryPage_extraHeaders = new ThreadLocal();

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

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

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

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 <B, A extends B> A addAndReturn(Collection<B> c, A a) {
  if (c != null) c.add(a);
  return a;
}
static void loadBinaryPageToFile(String url, File file) { try {
  print("Loading " + url);
  loadBinaryPageToFile(openConnection(new URL(url)), file);
} catch (Exception __e) { throw rethrow(__e); } }

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

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

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

static List<String> allToString(Object[] c) {
  List<String> l = new ArrayList();
  for (Object o : unnull(c)) l.add(str(o));
  return l;
}
static byte[] bytesFromHex(String s) {
  return hexToBytes(s);
}
static boolean byteArrayStartsWith(byte[] a, byte[] b) {
  if (a == null || b == null) return false;
  if (a.length < b.length) return false;
  for (int i = 0; i < b.length; i++)
    if (a[i] != b[i])
      return false;
  return true;
}
static byte[] loadBeginningOfBinaryFile(File file, int maxBytes) {
  return loadBinaryFilePart(file, 0, maxBytes);
}
static String getLookAndFeel() {
  return getClassName(UIManager.getLookAndFeel());
}
static JComponent getInternalFrameTitlePaneComponent(JInternalFrame f) {
  return (JComponent) childWithClassNameEndingWith(f, "InternalFrameTitlePane");
}

static JInternalFrame getInternalFrame(final Object _o) {
  return swing(new F0<JInternalFrame>() { JInternalFrame get() { try { 
    Object o = _o;
    if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o));
    if (!(o instanceof Component)) return null;
    Component c = (Component) o;
    while (c != null) {
      if (c instanceof JInternalFrame) return (JInternalFrame) c;
      c = c.getParent();
    }
    return null;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "O o = _o;\r\n    if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button..."; }});
}
static <A> A optCast(Class<A> c, Object o) {
  return isInstance(c, o) ? (A) o : null;
}
static boolean isLetterOrDigit(char c) {
  return Character.isLetterOrDigit(c);
}
static TreeMap<String,Class> hotwireCached_cache = new TreeMap();
static Lock hotwireCached_lock = lock();

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

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

static Class hotwireCached(String programID, boolean runMain, boolean dependent) {
  Lock __690 = hotwireCached_lock; lock(__690); try {
  
  programID = formatSnippetID(programID);
  Class c = hotwireCached_cache.get(programID);
  if (c == null) {
    c = hotwire(programID);
    if (dependent)
      makeDependent(c);
    if (runMain)
      callMain(c);
    hotwireCached_cache.put(programID, c);
  }
  return c;
} finally { unlock(__690); } }
static Map<String, Class> classForName_cache = synchroHashMap();

static Class classForName(String name) { try {
  Class c = classForName_cache.get(name);
  if (c == null)
    classForName_cache.put(name, c = Class.forName(name));
  return c;
} catch (Exception __e) { throw rethrow(__e); } }
static Map<Class, Constructor> nuObjectWithoutArguments_cache = newDangerousWeakHashMap();

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

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

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

static List<Class> getClasses(Object[] array) {
  List<Class> l = new ArrayList();
  for (Object o : array) l.add(_getClass(o));
  return l;
}
static boolean sameSnippetID(String a, String b) {
  if (!isSnippetID(a) || !isSnippetID(b)) return false;
  return parseSnippetID(a) == parseSnippetID(b);
}
static volatile String caseID_caseID;

static String caseID() { return caseID_caseID; }

static void caseID(String id) {
  caseID_caseID = id;
}
static List<CriticalAction> beginCriticalAction_inFlight = synchroList();

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

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

static void cleanMeUp_beginCriticalAction() {
  int n = 0;
  while (nempty(beginCriticalAction_inFlight)) {
    int m = l(beginCriticalAction_inFlight);
    if (m != n) {
      n = m;
      try {
        print("Waiting for " + n2(n, "critical actions") + ": " + join(", ", collect(beginCriticalAction_inFlight, "description")));
      } catch (Throwable __e) { _handleException(__e); }
    }
    sleepInCleanUp(10);
  }
}
public static void copyFile(File src, File dest) { try {
  FileInputStream inputStream = new FileInputStream(src.getPath());
  FileOutputStream outputStream = newFileOutputStream(dest.getPath());
  try {
    copyStream(inputStream, outputStream);
    inputStream.close();
  } finally {
    outputStream.close();
  }
} catch (Exception __e) { throw rethrow(__e); } }
static <A> List<A> concatLists(Collection<A>... lists) {
  List<A> l = new ArrayList();
  for (Collection<A> list : lists)
    if (list != null)
      l.addAll(list);
  return l;
}

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

static String strOrNull(Object o) {
  return o == null ? null : str(o);
}
static LinkedHashMap litorderedmap(Object... x) {
  LinkedHashMap map = new LinkedHashMap();
  litmap_impl(map, x);
  return map;
}
static File muricaPasswordFile() {
  return new File(javaxSecretDir(), "murica/muricaPasswordFile");
}


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

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

static File javaxCachesDir(String sub) {
  return newFile(javaxCachesDir(), sub);
}
static <A> A println(A a) {
  return print(a);
}
public static File mkdirsFor(File file) {
  return mkdirsForFile(file);
}

static void copyStreamWithPrints(InputStream in, OutputStream out, String pat) { try {
  byte[] buf = new byte[65536];
  int total = 0;
  while (true) {
    int n = in.read(buf);
    if (n <= 0) return;
    out.write(buf, 0, n);
    if ((total+n)/100000 > total/100000)
      print(pat.replace("{*}", str(roundDownTo(total, 100000))));
    total += n;
  }
} catch (Exception __e) { throw rethrow(__e); } }
static void renameFile_assertTrue(File a, File b) { try {
  if (!a.exists()) throw fail("Source file not found: " + f2s(a));
  if (b.exists()) throw fail("Target file exists: " + f2s(b));
  mkdirsForFile(b);
  
  
  if (!a.renameTo(b))
    throw fail("Can't rename " + f2s(a) + " to " + f2s(b));
  
} catch (Exception __e) { throw rethrow(__e); } }
static byte[] hexToBytes(String s) {
  if (odd(l(s))) throw fail("Hex string has odd length: " + quote(shorten(10, s)));
  int n = l(s) / 2;
  byte[] bytes = new byte[n];
  for (int i = 0; i < n; i++) {
    int a = parseHexChar(s.charAt(i*2));
    int b = parseHexChar(s.charAt(i*2+1));
    if (a < 0 || b < 0)
      throw fail("Bad hex byte: " + quote(substring(s, i*2, i*2+2)) + " at " + i*2 + "/" + l(s));
    bytes[i] = (byte) ((a << 4) | b);
  }
  return bytes;
}
static byte[] loadBinaryFilePart(File file, long start, long end) { try {
  RandomAccessFile raf = new RandomAccessFile(file, "r");
  int n = toInt(min(raf.length(), end-start));
  byte[] buffer = new byte[n];
  try {
    raf.seek(start);
    raf.readFully(buffer, 0, n);
    return buffer;
  } finally {
    raf.close();
  }
} catch (Exception __e) { throw rethrow(__e); } }
static Component childWithClassNameEndingWith(Component c, String suffix) {
  if (endsWith(className(c), suffix)) return c;
  Component x;
  for (Component comp : getComponents(c))
    if ((x = childWithClassNameEndingWith(comp, suffix)) != null) return x;
  return null;
}
static boolean isInstance(Class type, Object arg) {
  return type.isInstance(arg);
}
static Class<?> hotwire(String src) {
  assertFalse(_inCore());
  Class j = getJavaX();
  if (isAndroid()) {
    synchronized(j) { // hopefully this goes well...
      List<File> libraries = new ArrayList<File>();
      File srcDir = (File) call(j, "transpileMain", src, libraries);
      if (srcDir == null)
        throw fail("transpileMain returned null (src=" + quote(src) + ")");
    
      Object androidContext = get(j, "androidContext");
      return (Class) call(j, "loadx2android", srcDir, src);
    }
  } else {
    
    
    Class c = (Class) ( call(j, "hotwire", src));
    hotwire_copyOver(c);
    return c;
    
  }
}
static void makeDependent(Object c) {
  if (c == null) return;
  assertTrue("Not a class", c instanceof Class);
  dependentClasses(); // cleans up the list
  hotwire_classes.add(new WeakReference(c));
  
  Object local_log = getOpt(mc(), "local_log");
  if (local_log != null)
    setOpt(c, "local_log", local_log);
    
  /*if (isTrue(getOpt(c, 'ping_actions_shareable)))
    setOpt(c, +ping_actions);*/
    
  Object print_byThread = getOpt(mc(), "print_byThread");
  if (print_byThread != null)
    setOpt(c, "print_byThread", print_byThread);
}

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

static void callMain() {
  callMain(mc());
}
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 String n2(long l) { return formatWithThousands(l); }
static String n2(Collection l) { return n2(l(l)); }

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

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

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

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

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

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

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


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

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


static void sleepInCleanUp(long ms) { try {
  if (ms < 0) return;
  Thread.sleep(ms);
} catch (Exception __e) { throw rethrow(__e); } }
static void copyStream(InputStream in, OutputStream out) { try {
  byte[] buf = new byte[65536];
  while (true) {
    int n = in.read(buf);
    if (n <= 0) return;
    out.write(buf, 0, n);
  }
} catch (Exception __e) { throw rethrow(__e); } }
static File javaxSecretDir_dir; // can be set to work on different base dir

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

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


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

static long roundDownTo(long x, long n) {
  return x/n*n;
}
static boolean odd(int i) {
  return (i & 1) != 0;
}

static boolean odd(long i) {
  return (i & 1) != 0;
}
static int parseHexChar(char c) {
  if (c >= '0' && c <= '9') return charDiff(c, '0');
  if (c >= 'a' && c <= 'f') return charDiff(c, 'a')+10;
  if (c >= 'A' && c <= 'F') return charDiff(c, 'A')+10;
  return -1;
}
static List<Component> getComponents(final Component c) {
  return !(c instanceof Container) ? emptyList() : asList(swing(new F0<Component[]>() { Component[] get() { try { return  ((Container) c).getComponents() ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "((Container) c).getComponents()"; }}));
}
static boolean _inCore() {
  return false;
}
static List hotwire_copyOver_after = synchroList();

static void hotwire_copyOver(Class c) {
  // TODO: make a mechanism for making such "inheritable" fields
  for (String field : ll("print_log", "print_silent", "androidContext", "_userHome"))
    setOptIfNotNull(c, field, getOpt(mc(), field));
    
  
  
  setOptIfNotNull(c, "mainBot" , getMainBot());
  setOpt(c, "creator_class" , new WeakReference(mc()));
  pcallFAll(hotwire_copyOver_after, c);
}
static List<Class> dependentClasses() {
  return cleanUpAndGetWeakReferencesList(hotwire_classes);
}
static Field setOpt_findField(Class c, String field) {
  HashMap<String, Field> map;
  synchronized(getOpt_cache) {
    map = getOpt_cache.get(c);
    if (map == null)
      map = getOpt_makeCache(c);
  }
  return map.get(field);
}

static void setOpt(Object o, String field, Object value) { try {
  if (o == null) return;
  
  
  
  Class c = o.getClass();
  HashMap<String, Field> map;
  
  if (getOpt_cache == null)
    map = getOpt_makeCache(c); // in class init
  else synchronized(getOpt_cache) {
    map = getOpt_cache.get(c);
    if (map == null)
      map = getOpt_makeCache(c);
  }
  
  if (map == getOpt_special) {
    if (o instanceof Class) {
      setOpt((Class) o, field, value);
      return;
    }
    
    // It's probably a subclass of Map. Use raw method
    setOpt_raw(o, field, value);
    return;
  }
  
  Field f = map.get(field);
  if (f != null)
    smartSet(f, o, value); // possible improvement: skip setAccessible
} catch (Exception __e) { throw rethrow(__e); } }

static void setOpt(Class c, String field, Object value) {
  if (c == null) return;
  try {
    Field f = setOpt_findStaticField(c, field);
    if (f != null)
      smartSet(f, null, value);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
  
static Field setOpt_findStaticField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
        f.setAccessible(true);
        return f;
      }
    _c = _c.getSuperclass();
  } while (_c != null);
  return null;
}
static Class<?> getClass(String name) {
  try {
    return Class.forName(name);
  } catch (ClassNotFoundException e) {
    return null;
  }
}

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

static Class getClass(Object realm, String name) { try {
  try {
    return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
  } catch (ClassNotFoundException e) {
    return null;
  }
} catch (Exception __e) { throw rethrow(__e); } }
static String classNameToVM(String name) {
  return name.replace(".", "$");
}
static String formatWithThousands(long l) {
  return formatWithThousandsSeparator(l);
}
static String n_fancy2(long l, String singular, String plural) {
  return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
}

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

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

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


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

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


static List<WeakReference<Class>> hotwire_classes = synchroList();

static Class<?> hotwireDependent(String src) {
  Class c = hotwire(src);
  makeDependent(c);
  return c;
}

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

static int charDiff(String a, char b) {
  return charDiff(stringToChar(a), b);
}
static void setOptIfNotNull(Object o, String field, Object value) {
  if (value != null) setOpt(o, field, value);
}
static Object mainBot;

static Object getMainBot() {
  return mainBot;
}
static <A> List<A> cleanUpAndGetWeakReferencesList(List<WeakReference<A>> l) {
  synchronized(l) {
    List<A> out = new ArrayList();
    for (int i = 0; i < l(l); i++) {
      A a = l.get(i).get();
      if (a == null)
        l.remove(i--);
      else
        out.add(a);
    }
    return out;
  }
}
static void setOpt_raw(Object o, String field, Object value) { try {
  if (o == null) return;
  if (o instanceof Class) setOpt_raw((Class) o, field, value);
  else {
    Field f = setOpt_raw_findField(o.getClass(), field);
    if (f != null) {
      f.setAccessible(true);
      smartSet(f, o, value);
    }
  }
} catch (Exception __e) { throw rethrow(__e); } }

static void setOpt_raw(Class c, String field, Object value) { try {
  if (c == null) return;
  Field f = setOpt_raw_findStaticField(c, field);
  if (f != null) {
    f.setAccessible(true);
    smartSet(f, null, value);
  }
} catch (Exception __e) { throw rethrow(__e); } }
  
static Field setOpt_raw_findStaticField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  return null;
}

static Field setOpt_raw_findField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field))
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  return null;
}
static void smartSet(Field f, Object o, Object value) throws Exception {
  try {
    f.set(o, value);
  } catch (Exception e) {
    Class type = f.getType();
    
    // take care of common case (long to int)
    if (type == int.class && value instanceof Long)
      value = ((Long) value).intValue();
    
    if (type == LinkedHashMap.class && value instanceof Map)
      { f.set(o, asLinkedHashMap((Map) value)); return; }
    
    
    throw e;
  }
}


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


static char stringToChar(String s) {
  if (l(s) != 1) throw fail("bad stringToChar: " + s);
  return firstChar(s);
}
static <A, B> LinkedHashMap<A, B> asLinkedHashMap(Map<A, B> map) {
  if (map instanceof LinkedHashMap) return (LinkedHashMap) map;
  LinkedHashMap<A,B> m = new LinkedHashMap();
  if (map != null) synchronized(collectionMutex(map)) {
    m.putAll(map);
  }
  return m;
}


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


static abstract class VF1<A> {
  abstract void get(A a);
}static class BetterLabel extends JLabel {
  boolean autoToolTip = true;
  
  BetterLabel() {
    // Listeners given out to componentPopupMenu must not directly
    // reference the outer object (-> weak map problem).
    final WeakReference < BetterLabel > me = new WeakReference(this);
    componentPopupMenu(this, BetterLabel_menuItems(me));
  }
  
  BetterLabel(String text) {
    this();
    this.setText(text);
  }
  
  public void setText(String text) {
    super.setText(text);
    if (autoToolTip)
      if (!swic(text, "<html>")) // HTML labels make super-huge, confusing tool tips
        setToolTipText(nullIfEmpty(text));
  }
}

// moved outside of class for GC reasons (see above)
static VF1<JPopupMenu> BetterLabel_menuItems(final WeakReference<BetterLabel> me) {
  return new VF1<JPopupMenu>() { public void get(JPopupMenu menu) { try { 
    addMenuItem(menu, "Copy text to clipboard", new Runnable() { public void run() { try { 
      copyTextToClipboard(me.get().getText());
    
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "copyTextToClipboard(me.get().getText());"; }});
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "addMenuItem(menu, \"Copy text to clipboard\", r {\r\n      copyTextToClipboard(me..."; }};
}// elements are put to front when added (not when accessed)
static class MRUCache<A, B> extends LinkedHashMap<A, B> {
  int maxSize = 10;

  MRUCache() {}
  MRUCache(int maxSize) {
  this.maxSize = maxSize;}
  
  protected boolean removeEldestEntry(Map.Entry eldest) {
    return size() > maxSize;
  }
}static abstract class CloseableIterableIterator<A> extends IterableIterator<A> implements AutoCloseable {
  public void close() throws Exception {}
}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 PersistableThrowable {
  String className;
  String msg;
  String stacktrace;
  
  PersistableThrowable() {}
  PersistableThrowable(Throwable e) {
    if (e == null)
      className = "Crazy Null Error";
    else {
      className = getClassName(e).replace('/', '.');
      msg = e.getMessage();
      stacktrace = getStackTrace_noRecord(e);
    }
  }
  
  public String toString() {
    return nempty(msg) ? className + ": " + msg : className;
  }
}static abstract class F0<A> {
  abstract A get();
}// you still need to implement hasNext() and next()
static abstract class IterableIterator<A> implements Iterator<A>, Iterable<A> {
  public Iterator<A> iterator() {
    return this;
  }
  
  public void remove() {
    unsupportedOperation();
  }
}static class T3<A, B, C> {
  A a;
  B b;
  C c;
  
  T3() {}
  T3(A a, B b, C c) {
  this.c = c;
  this.b = b;
  this.a = a;}
  T3(T3<A, B, C> t) { a = t.a; b = t.b; c = t.c; }
  
  public int hashCode() {
    return _hashCode(a) + 2*_hashCode(b) - 4*_hashCode(c);
  }
  
  public boolean equals(Object o) {
    if (o == this) return true;
    if (!(o instanceof T3)) return false;
    T3 t = (T3) o;
    return eq(a, t.a) && eq(b, t.b) && eq(c, t.c);
  }
  
  public String toString() {
    return "(" + quoteBorderless(a) + ", " + quoteBorderless(b) + ", " + quoteBorderless(c) + ")";
  }
}static class Pair<A, B> implements Comparable<Pair<A, B>> {
  A a;
  B b;

  Pair() {}
  Pair(A a, B b) {
  this.b = b;
  this.a = a;}
  
  public int hashCode() {
    return hashCodeFor(a) + 2*hashCodeFor(b);
  }
  
  public boolean equals(Object o) {
    if (o == this) return true;
    if (!(o instanceof Pair)) return false;
    Pair t = (Pair) o;
    return eq(a, t.a) && eq(b, t.b);
  }
  
  public String toString() {
    return "<" + a + ", " + b + ">";
  }
  
  public int compareTo(Pair<A, B> p) {
    if (p == null) return 1;
    int i = ((Comparable<A>) a).compareTo(p.a);
    if (i != 0) return i;
    return ((Comparable<B>) b).compareTo(p.b);
  }
}

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

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


static <A extends JComponent> A setToolTipText(final A c, final Object toolTip) {
  if (c == null) return null;
  { swing(new Runnable() { public void run() { try { 
    String s = nullIfEmpty(str(toolTip));
    if (neq(s, c.getToolTipText()))
      c.setToolTipText(s);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "String s = nullIfEmpty(str(toolTip));\r\n    if (neq(s, c.getToolTipText()))\r\n ..."; }}); }
  return c;
}

static <A extends JComponent> A setToolTipText(Object toolTip, A c) {
  return setToolTipText(c, toolTip);
}
static String nullIfEmpty(String s) {
  return isEmpty(s) ? null : s;
}

static Map nullIfEmpty(Map map) {
  return isEmpty(map) ? null : map;
}
static void addMenuItem(JPopupMenu menu, String text, Object action) {
  menu.add(jmenuItem(text, action));
}

static void addMenuItem(JPopupMenu menu, JMenuItem menuItem) {
  menu.add(menuItem);
}

static void addMenuItem(JMenu menu, String text, Object action) {
  menu.add(jmenuItem(text, action));
}

static void addMenuItem(Menu menu, String text, Object action) {
  menu.add(menuItem(text, action));
}

static void addMenuItem(JMenu menu, JMenuItem menuItem) {
  menu.add(menuItem);
}



static String copyTextToClipboard(String text) {
  StringSelection selection = new StringSelection(text);
  Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
  return text;
}
static <A> Iterator<A> iterator(Iterable<A> c) {
  return c == null ? emptyIterator() : c.iterator();
}
static UnsupportedOperationException unsupportedOperation() {
  throw new UnsupportedOperationException();
}
static int _hashCode(Object a) {
  return a == null ? 0 : a.hashCode();
}
static String quoteBorderless(Object o) {
  if (o == null) return "null";
  return quoteBorderless(str(o));
}

static String quoteBorderless(String s) {
  if (s == null) return "null";
  StringBuilder out = new StringBuilder((int) (l(s)*1.5));
  quoteBorderless_impl(s, out);
  return out.toString();
}
  
static void quoteBorderless_impl(String s, StringBuilder out) {
  int l = s.length();
  for (int i = 0; i < l; i++) {
    char c = s.charAt(i);
    if (c == '\\' || c == '"')
      out.append('\\').append(c);
    else if (c == '\r')
      out.append("\\r");
    else if (c == '\n')
      out.append("\\n");
    else
      out.append(c);
  }
}
static int hashCodeFor(Object a) {
  return a == null ? 0 : a.hashCode();
}


static boolean startsWithIgnoreCase(String a, String b) {
  return regionMatchesIC(a, 0, b, 0, b.length());
}
static MenuItem menuItem(String text, final Object r) {
  MenuItem mi = new MenuItem(text);
  mi.addActionListener(actionListener(r));
  return mi;
}

}