import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import javax.swing.border.*;
import java.text.NumberFormat;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.awt.datatransfer.StringSelection;
import java.nio.file.Files;
import java.nio.file.Path;

class main {

static class Standalone_OSWithSplashScreens {
  String programName = "Unknown Program"; // doubles as virtualDirName
  String virtualDirName;
  String backgroundID = "#1102649";
  String osID = "#1016478"; // version of Stefan's OS to use
  String mainIconID = "#1102666";
  boolean showTopInput = true;
  transient Runnable additionalUnpacking;
  transient boolean standalone = true;
  
  String virtualDirName() { return or2(virtualDirName, programName); }
  
  // name / module lib ID / name / module lib ID / ...
  List<String> mainModules = new ArrayList();
  List<String> helperModules = ll("Task Bar", "#1019954/TaskBar_dev");
  
  void run(String[] args) { try {
    if (standalone && javaXStandalone_init(args, "noConsole" , true)) {
      print("exiting");
      return;
    }
  
    autoVMExit();
    try {
      // TODO: shouldn't we call standalone_start2 first? it sets the resource loader which we need for loading the background image!
       AutoCloseable __1 = tempWindow(standardSplashScreen(backgroundID, programName + " Loading")); try {
      { if (standalone_start2(standalone, programName, osID, virtualDirName())) return; }
      
      zip2dir_withPredicate_overwriteIfDifferentSize(getMainJarLocation(),
        actualUserDir("JavaX-Caches/#1002203"),
        //getCacheProgramDir("#1002203"), // x30.hotwire doesn't find this
          s -> regexpMatches(md5Regexp() + "\\.jar", s));
  
      callF(additionalUnpacking);
      
      saveTextFile(stefansOS_backgroundFile(), backgroundID);
      standalone_runOSWithInitialModules(osID,
        concatLists(oddEntries(mainModules), oddEntries(helperModules)),
        "osParams" , litparams(
          "onStart" , new VF1<Object>() { public void get(Object os) { try {  setOpt(os, "minLoadScreenShowingTime" , 20.0);  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "setOpt(os, minLoadScreenShowingTime := 20.0);"; }},
          "hideFeatures" , stefansOS_technicalFeatures(),
          "standardModules" , mainModules,
          "botName" , "",
          "osName" , programName,
          "showTopInput", showTopInput,
          "mainIconID", mainIconID,
          "shutdownConsole" , new Runnable() {  public void run() { try {  standardSplashScreen(backgroundID, programName + " Shutting Down") ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "standardSplashScreen(backgroundID, programName + \" Shutting Down\")"; }}));
    } finally { _close(__1); }} catch (Throwable e) { _handleException(e); showConsole(); }
  } catch (Throwable __e) { _handleException(__e); }}
}
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 <A> List<A> ll(A... a) {
  ArrayList l = new ArrayList(a.length);
  if (a != null) for (A x : a) l.add(x);
  return l;
}

static boolean javaXStandalone_init_runArbitraryPrograms = true;

// returns true if you should exit
// idempotent
static boolean javaXStandalone_init(String[] args, Object... __) {
  if (javax() != null) return false;
  getJavaXDirectly((Runnable) optPar("beforeInit",__));
  
  // forward to JavaX if arguments start with a program ID
  if (javaXStandalone_init_runArbitraryPrograms && isInteger(first(args)))
    { call(javax(), "goMain", new Object[] {args}); return true; }

  call(javax(), "initHelloMessage"); // TODO: fix security (user check)
  call(javax(), "loadMyClasses"); // for when jar file is modified while program is running
  callOnLoadMethods(mc());
  
  call(javax(), "redirectSystemOutAndErr");
  
  // always make console to get the log, show it optionally
  setOpt(javax(), "consoleOn" , !boolPar("noConsole",__));
  call(javax(), "tryToOpenConsole", args);
  
  print("javax=" + javax() + ", console=" + getOpt(javax(), "console"));
  return false;
}

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




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

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

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

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

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

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

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

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

  print_raw(s);
}

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

static void print_autoRotate() {
  
}

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

static <A> AutoCloseable tempWindow(Window w) {
  return tempDisposeWindow(w);
}

static JWindow standardSplashScreen(String backgroundID, String text, Object... __) {
  return chessOCR_splashScreen(backgroundID, paramsPlus(__, "text", text));
}

// returns true if you should exit
static boolean standalone_start2(boolean standalone, String programName, String framesID) {
  return standalone_start2(standalone, programName, framesID, programName);
}

static boolean standalone_start2(boolean standalone, String programName, String framesID, String virtualDirName) {
  File virtualHome = javaxVirtualDir(virtualDirName);
  File mainJar = getMainJarLocation();
  File unpackDir = newFile(virtualHome, "unpacked");
  if (standalone)
    { if (standalone_start(null, programName, virtualHome, mainJar, unpackDir, framesID)) return true; }
  else
    setUserDir(virtualHome);
  return false;
}

static void zip2dir_withPredicate_overwriteIfDifferentSize(File inZip, File outDir, IF1<String, Boolean> pred) { try {
   ZipFile zipFile = new ZipFile(inZip); try {
  Enumeration entries = zipFile.entries();
  while (entries.hasMoreElements()) {
    ZipEntry entry = (ZipEntry) entries.nextElement(); 
    
    if (entry.isDirectory()) continue; // We care about files only, really. Directories are made on the fly anyway.
    
    if (!pred.get(entry.getName())) continue;
    
    File outFile = new File(outDir, entry.getName());
    if (fileSize(outFile) == entry.getSize()) continue;
    
    System.out.println("Unzipping " + entry.getName() + " to " + outFile.getAbsolutePath());
    
    stream2file(zipFile.getInputStream(entry), outFile);
  }
} finally { _close(zipFile); }} catch (Exception __e) { throw rethrow(__e); } }

static File getMainJarLocation() { try {
  Class c = or(javax(), mc());
  return new File(c.getProtectionDomain().getCodeSource().getLocation().toURI());
} catch (Exception __e) { throw rethrow(__e); } }

static File actualUserDir() {
  return new File(actualUserHome());
}

static File actualUserDir(String path) {
  return new File(actualUserHome(), path);
}

static boolean regexpMatches(String pat, String s) {
  return pat != null && s != null && regexp(pat, s).matches();
}

static String md5Regexp() {
  return "[a-f0-9]{32}";
}

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


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



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



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



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





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



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


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

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

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

/** writes safely (to temp file, then rename) */
static File saveTextFile(String fileName, String contents) throws IOException {
  CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
  try {
    File file = new File(fileName);
    mkdirsForFile(file);
    String tempFileName = fileName + "_temp";
    File tempFile = new File(tempFileName);
    if (contents != null) {
      if (tempFile.exists()) try {
        String saveName = tempFileName + ".saved." + now();
        copyFile(tempFile, new File(saveName));
      } catch (Throwable e) { printStackTrace(e); }
      FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
      OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
      PrintWriter printWriter = new PrintWriter(outputStreamWriter);
      printWriter.print(contents);
      printWriter.close();
    }
    
    if (file.exists() && !file.delete())
      throw new IOException("Can't delete " + fileName);
  
    if (contents != null)
      if (!tempFile.renameTo(file))
        throw new IOException("Can't rename " + tempFile + " to " + file);
        
    
    vmBus_send("wroteFile", file);
    
    return file;
  } finally {
    action.done();
  }
}

static File saveTextFile(File fileName, String contents) { try {
  saveTextFile(fileName.getPath(), contents);
  return fileName;
} catch (Exception __e) { throw rethrow(__e); } }

static File stefansOS_backgroundFile() {
  return javaxDataDir("os-background.txt");
}

static void standalone_runOSWithInitialModules(String osID, List<String> initialModuleIDs, Object... __) {
  print("Running OS.");
  
  CompilerBot.verbose = true;
  runAsMainWithParams(osID, paramsPlus((Object[]) optPar("osParams",__),
    "_userHome" , userHome(),
    "initialModules_override" , new VF1<Object>() { public void get(Object os) { try { 
      dm_makeOrShowModules(initialModuleIDs)
    ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "dm_makeOrShowModules(initialModuleIDs)"; }},
    "restarter_override" , new Runnable() {  public void run() { try { 
      print("WOULD RESTART")
    ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "print(\"WOULD RESTART\")"; }}));
}

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

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


static <A> List<A> oddEntries(List<A> l) {
  int n = l(l)/2;
  List<A> out = emptyList(n);
  for (int i = 0; i < n; i++)
    out.add(l.get(i*2+1));
  return out;
}

static Object[] litparams(Object... l) {
  int n = 0, n1 = l(l);
  for (int i = 0; i < n1; i += 2)
    if (l[i] != null && l[i+1] != null)
      ++n;
  if (n == 0) return null;
  Object[] params = new Object[n*2];
  int j = 0;
  for (int i = 0; i < n1; i += 2) {
    Object key = l[i], value = l[i+1];
    if (key != null && value != null) {
      params[j++] = key;
      params[j++] = value;
    }
  }
  return params;
}

static Field setOpt_findField(Class c, String field) {
  HashMap<String, Field> map;
  synchronized(getOpt_cache) {
    map = getOpt_cache.get(c);
    if (map == null)
      map = getOpt_makeCache(c);
  }
  return map.get(field);
}

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

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

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

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

static Set<String> stefansOS_technicalFeatures() {
  return tlft_ciSet("\r\n    Screenshot\r\n    Full screen on/off\r\n    Switch OS version\r\n    Restart OS\r\n    Exit\r\n    Other module...\r\n    Welcome screen\r\n    Quick module search\r\n    Internal types\r\n    Module classes\r\n    Show source code\r\n    Retranspile\r\n    Find memory leaks\r\n    Remove moduleless frames\r\n  ");
}


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

static volatile PersistableThrowable _handleException_lastException;
static List _handleException_onException = synchroList(ll("printStackTrace2"));
static boolean _handleException_showThreadCancellations = false;

static void _handleException(Throwable e) {
  _handleException_lastException = persistableThrowable(e);
  
  Throwable e2 = innerException(e);
  if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException) {
    if (_handleException_showThreadCancellations)
      System.out.println(getStackTrace_noRecord(e2));
    return;
  }

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

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



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

//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 mapGet2(((DynamicObject) o).fieldValues, field);
  
  return null;
} catch (Exception __e) { throw rethrow(__e); } }

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

static 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 boolean nempty(Collection c) {
  return !empty(c);
}

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

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

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

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


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








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

static Class getJavaXDirectly() {
  return getJavaXDirectly(null);
}

static Class getJavaXDirectly(Runnable beforeInit) {
  if (__javax == null) {
    __javax = classForName("x30");
    callF(beforeInit);
    call(__javax, "initMe");
  }
  return __javax;
}

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

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

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

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

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

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

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

static boolean isInteger(String s) {
  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 Object first(Object list) {
  return first((Iterable) list);
}


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

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


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


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

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

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


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




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





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

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

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

static void callOnLoadMethods(Class c) {
  for (String name : methodsStartingWith(c, "_onLoad_"))
    pcallOpt(c, name);
  pcallOpt(c, "_onLoad");
}

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

static boolean boolPar(ThreadLocal<Boolean> tl) {
  return boolOptParam(tl);
}



// defaults to false
static boolean boolPar(Object[] __, String name) {
  return boolOptParam(__, name);
}

static boolean boolPar(String name, Object[] __) {
  return boolOptParam(__, name);
}

static boolean boolPar(String name, Map __) {
  return boolOptParam(name, __);
}

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


static boolean noConsole() {
  return consoleFrame() == null;
}

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

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

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

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

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


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

static void ping_okInCleanUp() {

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

}

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

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

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

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

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

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

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

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

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

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

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

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

static Class __javax;

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

static <A> AutoCloseable tempDisposeWindow(final Window w) {
  return new AutoCloseable() {
    public void close() {
      disposeWindow(w);
    }
  };
}

static JWindow chessOCR_splashScreen(String backgroundID, Object... __) {
  String text = optPar("text",__,  "Chess Board Recognizer Loading");
  
  return showCenterPackedWindow(
    centerAndSouthWithMargins(
      jimage(resizeImage(600, loadImage2(backgroundID))),
      centerAndEastWithMargin(
        fontSizePlus(4, jCenteredBoldLabel(text)),
        fontSizeMinus(2, jButton("TROUBLESHOOT", runnableThread(new Runnable() {  public void run() { try {  showConsole(); 
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "showConsole();"; }}))))
      ));
}

static Object[] paramsPlus(Object[] a1, Object... a2) {
  if (a2 == null) return a1;
  if (a1 == null) return a2;
  if (l(a1) == 1 && a1[0] instanceof Map)
    return new Object[] { mapPlus((Map) a1[0], a2) };
  assertEvenLength(a1);
  assertEvenLength(a2);
  Map map = paramsToOrderedMap(a1);
  int n = l(a2);
  for (int i = 0; i < n; i += 2) {
    Object key = a2[i];
    if (key != null) map.put(key, a2[i+1]);
  }
  return mapToParams(map);
}

static Object[] paramsPlus(Map a1, Object... a2) {
  return paramsPlus(new Object[] {a1}, a2);
}

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

static File javaxVirtualDir() {
  return javaxVirtualDir_dir != null ? javaxVirtualDir_dir : new File(actualUserHome(), "JavaX-Virtual");
}

static File javaxVirtualDir(String... subs) {
  return newFile(javaxVirtualDir(), subs);
}

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

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

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

static boolean standalone_start(String[] args, String programName, File newUserDir, File mainJar, File unpackDir, String framesID) {
  print(programName + " starting.");
  { if (javaXStandalone_init(args)) return true; }
  setUserDir(newUserDir);
  { if (standalone_activateFrames(framesID)) return true; }
  vm_setResourceLoader(resourceLoaderFromJar(mainJar, unpackDir));
  return false;
}

static void setUserDir(File dir) {
  _userHome = f2s(dir);
}

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


// closes the input stream too.
static void stream2file(InputStream in, File out) { try {
  mkdirsForFile(out);
  FileOutputStream fos = new FileOutputStream(out);
  copyStream(in, fos);
  in.close();
  fos.close();
} catch (Exception __e) { throw rethrow(__e); } }

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

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

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

static Matcher regexp(String pat, String s) {
  return regexp(compileRegexp(pat), unnull(s));
}

static Matcher regexp(java.util.regex.Pattern pat, String s) {
  return pat.matcher(unnull(s));
}

static java.util.regex.Pattern regexp(String pat) {
  return compileRegexp(pat);
}

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

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

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

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

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

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



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

















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


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

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

static boolean call_checkArgs(Method m, Object[] args, boolean debug) {
  Class<?>[] types = m.getParameterTypes();
  if (types.length != args.length) {
    if (debug)
      print("Bad parameter length: " + args.length + " vs " + types.length);
    return false;
  }
  for (int i = 0; i < types.length; i++) {
    Object arg = args[i];
    if (!(arg == null ? !types[i].isPrimitive()
      : isInstanceX(types[i], arg))) {
      if (debug)
        print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
      return false;
    }
  }
  return true;
}

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

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

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

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 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 long now_virtualTime;
static long now() {
  return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}


static File copyFile(File src, File dest) { try {
  FileInputStream inputStream = new FileInputStream(src.getPath());
  FileOutputStream outputStream = newFileOutputStream(dest.getPath());
  try {
    copyStream(inputStream, outputStream);
    inputStream.close();
  } finally {
    outputStream.close();
  }
  return dest;
} catch (Exception __e) { throw rethrow(__e); } }

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

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

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

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

static 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 File javaxDataDir_dir; // can be set to work on different base dir

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

static File javaxDataDir(String... subs) {
  return newFile(javaxDataDir(), subs);
}

static Class runAsMainWithParams(String snippetID, Object... params) {
  return runWithParams(snippetID, arrayPlus(params, "creator_class" , null));
}

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

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

static void dm_makeOrShowModules(Iterable<String> moduleLibIDs) {
  for (String moduleID : unnull(moduleLibIDs))
    dm_makeOrShowModule(moduleID);
}

static <A, B extends A> void addAll(Collection<A> c, Iterable<B> b) {
  if (c != null && b != null) for (A a : b) c.add(a);
}

static <A, B extends A> boolean addAll(Collection<A> c, Collection<B> b) {
  return c != null && b != null && c.addAll(b);
}

static <A, B extends A> boolean addAll(Collection<A> c, B... b) {
  return c != null && b != null && c.addAll(Arrays.asList(b));
}



static <A, B> Map<A, B> addAll(Map<A, B> a, Map<? extends A,? extends B> b) {
  if (a != null) a.putAll(b);
  return a;
}

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

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

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

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

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

static void setOpt_raw(Object o, String field, Object value) { try {
  if (o == null) return;
  if (o instanceof Class) setOpt_raw((Class) o, field, value);
  else {
    Field f = setOpt_raw_findField(o.getClass(), field);
    if (f != null) {
      makeAccessible(f);
      smartSet(f, o, value);
    }
  }
} catch (Exception __e) { throw rethrow(__e); } }

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

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

static void smartSet(Field f, Object o, Object value) throws Exception {
  try {
    f.set(o, value);
  } catch (Exception e) {
    Class type = f.getType();
    
    // take care of common case (long to int)
    if (type == int.class && value instanceof Long)
      value = ((Long) value).intValue();
    
    if (type == LinkedHashMap.class && value instanceof Map)
      { f.set(o, asLinkedHashMap((Map) value)); return; }
    
    
    throw e;
  }
}

static <A extends DynamicObject> A setDyn(A o, String key, Object value) {
  if (o == null) return o;
  setDynObjectValue(o, key, value);
  return o;
}

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

static TreeSet<String> tlft_ciSet(String s) {
  return asCISet(tlft(s));
}


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

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


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

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

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



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

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

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

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

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

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

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

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

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

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

static Object get(Object o, String field) {
  try {
    if (o == null) return null;
    if (o instanceof Class) return get((Class) o, field);
    
    if (o instanceof Map)
      return ((Map) o).get(field);
      
    Field f = getOpt_findField(o.getClass(), field);
    if (f != null) {
      makeAccessible(f);
      return f.get(o);
    }
      
    
      if (o instanceof DynamicObject)
        return ((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(String field, Object o) {
  return get_raw(o, field);
}

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

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

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

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

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



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

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

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

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

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

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

static List<Pair> _registerDangerousWeakMap_preList;

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

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

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

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

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

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

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

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

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

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

static String getStackTrace2(Throwable e) {
  return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ",
    hideCredentials(str(innerException2(e)))) + "\n");
}

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


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


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

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





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









static Map<String, Class> classForName_cache = synchroHashMap();

static Class classForName(String name) { try {
  if (classForName_cache == null) return Class.forName(name); // in class init
  Class c = classForName_cache.get(name);
  if (c == null)
    classForName_cache.put(name, c = Class.forName(name));
  return c;
} catch (Exception __e) { throw rethrow(__e); } }

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

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

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

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

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

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

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

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

static List<String> methodsStartingWith(Object o, final String prefix) {
  return filter(allMethodNames(o), new F1<String, Object>() { public Object get(String s) { try {  return startsWith(s, prefix);  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "startsWith(s, prefix)"; }});
}

static Object pcallOpt(Object o, String method, Object... args) {
  try { return callOpt(o, method, args); } catch (Throwable __e) { _handleException(__e); }
  return null;
}

static boolean boolOptParam(ThreadLocal<Boolean> tl) {
  return isTrue(optPar(tl));
}

// defaults to false
static boolean boolOptParam(Object[] __, String name) {
  return isTrue(optParam(__, name));
}

static boolean boolOptParam(String name, Object[] __) {
  return boolOptParam(__, name);
}

static boolean boolOptParam(String name, Map __) {
  return isTrue(optPar(name, __));
}

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

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




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

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

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

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


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

static PersistableThrowable lastException() {
  return lastException_lastException;
}

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

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

static String hideCredentials(String url) {
  try {
    if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url))) return url;
  } catch (Throwable e) {
    print("HideCredentials", e);
  }
  return url.replaceAll("([&?])(_pass|key|cookie)=[^&\\s\"]*", "$1$2=<hidden>");
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

static 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 JWindow showCenterPackedWindow(Component c) {
  return swing(() -> {
    JWindow w = new JWindow();
    w.add(c);
    w.pack();
    centerWindow(w);
    w.setVisible(true);
    return w;
  });
}

static JPanel centerAndSouthWithMargins(Component c, Component s) {
  return applyDefaultMargin(centerAndSouth(c, withTopMargin(s)));
}

static JPanel centerAndSouthWithMargins(int margin, Component c, Component s) {
  return applyMargin(margin, centerAndSouth(c, withTopMargin(margin, s)));
}

static JLabel jimage(Image img) {
  return jImageLabel(img);
}

static JLabel jimage(String imageID) {
  return jImageLabel(imageID);
}

static BufferedImage resizeImage(BufferedImage img, int newW, int newH) {
  return resizeImage(img, newW, newH, Image.SCALE_SMOOTH);
}

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

static BufferedImage resizeImage(BufferedImage img, int newW) {
  int newH = iround(img.getHeight()*(double) newW/img.getWidth());
  return resizeImage(img, newW, newH);
}

static BufferedImage resizeImage(int newW, BufferedImage img) {
  return resizeImage(img, newW);
}

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

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

static JPanel centerAndEastWithMargin(Component c, Component e) {
  return centerAndEastWithMarginInbetween(c, e);
}

static <A extends JComponent> A fontSizePlus(final int delta, final A c) {
  if (c != null) { swing(new Runnable() {  public void run() { try { 
    Font font = c.getFont();
    c.setFont(font.deriveFont(font.getSize2D()+delta));
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "Font font = c.getFont();\r\n    c.setFont(font.deriveFont(font.getSize2D()+delt..."; }}); }
  return c;
}

static JLabel jCenteredBoldLabel(String text) {
  return jcenteredBoldLabel(text);
}



static JLabel jCenteredBoldLabel() {
  return jcenteredBoldLabel();
}

static <A extends JComponent> A fontSizeMinus(int delta, A c) {
  return fontSizePlus(-delta, c);
}

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

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

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

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

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

static <A, B> Map<A, B> mapPlus(Map<A, B> m, Object... data) {
  m = cloneMap(m);
  litmap_impl(m, data);
  return m;
}

static Object[] assertEvenLength(Object[] a) {
  assertTrue(even(l(a)));
  return a;
}

static LinkedHashMap paramsToOrderedMap(Object... params) {
  return asLinkedHashMap(paramsToMap(params));
}

static Object[] mapToParams(Map map) {
  return mapToObjectArray(map);
}

// returns true if you should exit
static boolean standalone_activateFrames(String programID) {
  String fullID = programIDPlusHome(programID, userHome());
  if (swic(activateFramesOf(fullID), "OK")) {
    print(fullID + " already running, activating its windows.");
    cleanKill();
    return true;
  }
  return false;
}

static void vm_setResourceLoader(IResourceLoader loader) {
  vm_generalMap_put("_officialResourceLoader", loader);
}

static IResourceLoader resourceLoaderFromJar(File mainJar, File unpackDir) {
  print("Unpacking to: " + unpackDir);
  
  Map<String, String> titles =  (Map<String, String>) (safeUnstructure(loadTextFileFromZip(mainJar, "snippet-titles.struct")));
  assertNempty("Snippet titles", titles);
  Map<String, Integer> types =  (Map<String, Integer>) (safeUnstructure(loadTextFileFromZip(mainJar, "snippet-types.struct")));

  return new IResourceLoader() {
    public String loadSnippet(String snippetID) {
      return loadTextFileFromZip(mainJar, psI(snippetID) + ".text");
    }
    
    public String getTranspiled(String snippetID) {
      String src = loadTextFileFromZip(mainJar, psI(snippetID) + ".transpiled");
      if (empty(src))
        print("Warning: Transpilation for " + snippetID + " not found");
      return src;
    }
    
    public int getSnippetType(String snippetID) {
      return or0(types.get(fsI(snippetID)));
    }
    
    public String getSnippetTitle(String snippetID) {
      return titles.get(fsI(snippetID));
    }
    
    public File loadLibrary(String snippetID) {
      long id = psI(snippetID);
      if (isImageServerSnippet(id)) 
        return optExtractFileFromZipToDir_tryMultipleNames(mainJar, unpackDir, id + ".png", id + ".gif");
      else
        return optExtractFileFromZipToDir(mainJar, unpackDir, id + ".bin");
    }
    
    public File pathToJavaXJar() {
      return mainJar;
    }
  };
}

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

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


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


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

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

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

static int 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 Map<String, java.util.regex.Pattern> compileRegexp_cache = syncMRUCache(10);

static java.util.regex.Pattern compileRegexp(String pat) {
  java.util.regex.Pattern p = compileRegexp_cache.get(pat);
  if (p == null) {
    
    compileRegexp_cache.put(pat, p = java.util.regex.Pattern.compile(pat));
  }
  return p;
}

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

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

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

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

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

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

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



//ifclass Symbol



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


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

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

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

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

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

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


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

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

static boolean isInstanceX(Class type, Object arg) {
  if (type == boolean.class) return arg instanceof Boolean;
  if (type == int.class) return arg instanceof Integer;
  if (type == long.class) return arg instanceof Long;
  if (type == float.class) return arg instanceof Float;
  if (type == short.class) return arg instanceof Short;
  if (type == char.class) return arg instanceof Character;
  if (type == byte.class) return arg instanceof Byte;
  if (type == double.class) return arg instanceof Double;
  return type.isInstance(arg);
}

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

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

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

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

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

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

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

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

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

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



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

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

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

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

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


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


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

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

/*ifclass Concept
static L collect(Class c, S field) {
  ret collect(list(c), field);
}
endif
TODO: make translator ignore stuff in ifclass until resolved
*/

static void sleepInCleanUp(long ms) { try {
  if (ms < 0) return;
  Thread.sleep(ms);
} catch (Exception __e) { throw rethrow(__e); } }

static void _registerIO(Object object, String path, boolean opened) {
}

static Class runWithParams(String snippetID, Object... params) {
  Class c = hotwire(snippetID);
  setOpt(c, "_computerID" , null); // _onLoads should be called later to avoid this
  setOptAll(c, params);
  callMain(c);
  return c;
}

// one array plus more elements
static Object[] arrayPlus(Object[] a1, Object... a2) {
  return concatArrays(a1, a2);
}

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

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

// makes dynamic & static modules
static String dm_makeOrShowModule(String moduleLibID) {
  return (String) dm_callOS("makeOrShowModule", moduleLibID);
}

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

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

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

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

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

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

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

static <A, B> LinkedHashMap<A, B> asLinkedHashMap(Map<A, B> map) {
  if (map instanceof LinkedHashMap) return (LinkedHashMap) map;
  LinkedHashMap<A, B> m = new LinkedHashMap();
  if (map != null) synchronized(collectionMutex(map)) {
    m.putAll(map);
  }
  return m;
}

static void setDynObjectValue(DynamicObject o, String field, Object value) {
  dynamicObject_setRawFieldValue(o, field, value);
}

static TreeSet<String> asCISet(Iterable<String> c) {
  return toCaseInsensitiveSet(c);
}

static TreeSet<String> asCISet(String... x) {
  return toCaseInsensitiveSet(x);
}

static List<String> tlft(String s) { return toLinesFullTrim(s); }
static List<String> tlft(File f) { return toLinesFullTrim(f); }


static Throwable getInnerException(Throwable e) {
  if (e == null) return null;
  while (e.getCause() != null)
    e = e.getCause();
  return e;
}

static Throwable getInnerException(Runnable r) {
  return getInnerException(getException(r));
}

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

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

// unclear semantics as to whether return null on null

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

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

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

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

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

static <A> ArrayList<A> asList(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(Producer<A> p) {
  ArrayList l = new ArrayList();
  A a;
  if (p != null) while ((a = p.next()) != null)
    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(List l) {
  return l;
}

static Object collectionMutex(Object o) {
  

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

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

static Object callOpt_withVarargs(Object o, String method, Object... args) { try {
  if (o == null) return null;
  
  if (o instanceof Class) {
    Class c = (Class) o;
    _MethodCache cache = callOpt_getCache(c);
    
    Method me = cache.findMethod(method, args);
    if (me == null) {
      // TODO: varargs
      return null;
    }
    if ((me.getModifiers() & Modifier.STATIC) == 0)
      return null;
    return invokeMethod(me, null, args);
  } else {
    Class c = o.getClass();
    _MethodCache cache = callOpt_getCache(c);

    Method me = cache.findMethod(method, args);
    if (me != null)
      return invokeMethod(me, o, args);
      
    // try varargs
    List<Method> methods = cache.cache.get(method);
    if (methods != null) methodSearch: for (Method m : methods) {
      { if (!(m.isVarArgs())) continue; }
      Object[] newArgs = massageArgsForVarArgsCall(m, args);
      if (newArgs != null)
        return invokeMethod(m, o, newArgs);
    }
    
    return null;
  }
} catch (Exception __e) { throw rethrow(__e); } }



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

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


static <A> AutoCloseable tempSetThreadLocal(final ThreadLocal<A> tl, A a) {
  if (tl == null) return null;
  final A prev = setThreadLocal(tl, a);
  return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); }};
}

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

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

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

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

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

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

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

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

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

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


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

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 Throwable innerException2(Throwable e) {
  if (e == null) return null;
  while (empty(e.getMessage()) && e.getCause() != null)
    e = e.getCause();
  return e;
}

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

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

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

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

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

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

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

static Object callOpt_cached(Object o, String methodName, Object... args) { try {
  if (o == null) return null;
  
  if (o instanceof Class) {
    Class c = (Class) o;
    _MethodCache cache = callOpt_getCache(c);
    
    // TODO: (super-rare) case where method exists static and non-static
    // with different args
    
    Method me = cache.findMethod(methodName, args);
    if (me == null || (me.getModifiers() & Modifier.STATIC) == 0) return null;
    return invokeMethod(me, null, args);
  } else {
    Class c = o.getClass();
    _MethodCache cache = callOpt_getCache(c);

    Method me = cache.findMethod(methodName, args);
    if (me == null) return null;
    return invokeMethod(me, o, args);
  }
} catch (Exception __e) { throw rethrow(__e); } }

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

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

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

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

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


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


static <A> List<A> filter(Iterable<A> c, Object pred) {
  if (pred instanceof F1) return filter(c, (F1<A, Boolean>) pred);

  
  List x = new ArrayList();
  if (c != null) for (Object o : c)
    if (isTrue(callF(pred, o)))
      x.add(o);
  return x;
}

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

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

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

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

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

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

static List<String> allMethodNames(Object o) {
  Class c = _getClass(o);
  TreeSet<String> names = new TreeSet();
  while (c != null) {
    for (Method m : c.getDeclaredMethods())
      names.add(m.getName());
    c = c.getSuperclass();
  }
  return asList(names);
}

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

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


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


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



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

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

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

// 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 void failIfUnlicensed() {
  assertTrue("license off", licensed());
}

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

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

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

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

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

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


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



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



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


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


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


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


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

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

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

static 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 <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 Window centerWindow(Component c) {
  Window w = getWindow(c);
  if (w != null)
    w.setLocationRelativeTo(null); // magic trick
  return w;
}

static Window centerWindow(Component c, int width, int height) {
  setWindowSize(c, width, height);
  return centerWindow(c);
}

static JWindow centerWindow(JWindow w) {
  centerWindow(getRootPane(w));
  return w;
}

static <A extends JComponent> A applyDefaultMargin(final A c) {
  if (c != null) { swing(new Runnable() {  public void run() { try { 
    c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth));
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMarg..."; }}); }
  return c;
}

static JPanel centerAndSouth(final Component c, final Component s) {
  return swing(new F0<JPanel>() { public JPanel get() { try { 
    JPanel panel = new JPanel(new BorderLayout());
    panel.add(BorderLayout.CENTER, wrap(c));
    if (s != null) panel.add(BorderLayout.SOUTH, wrap(s));
    return panel;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n    panel.add(BorderLayout.CENT..."; }});
}

static int withTopMargin_defaultWidth = 6;

static JPanel withTopMargin(Component c) {
  return withTopMargin(withTopMargin_defaultWidth, c);
}

static JPanel withTopMargin(final int w, final Component c) {
  return swing(new F0<JPanel>() { public JPanel get() { try { 
    JPanel p = new JPanel(new BorderLayout());
    p.setBorder(BorderFactory.createEmptyBorder(w, 0, 0, 0));
    p.add(c);
    return p;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n    p.setBorder(BorderFactory.creat..."; }});
}



static <A extends JComponent> A applyMargin(int top, int left, int bottom, int right, A c) {
  return addMargin(top, left, bottom, right, c);
}



static <A extends JComponent> A applyMargin(int w, A c) {
  return addMargin(w, c);
}

static JLabel jImageLabel(Image img) {
  return swingNu(JLabel.class, imageIcon(img));
}

static JLabel jImageLabel(javax.swing.Icon icon) {
  return swingNu(JLabel.class, icon);
}

static JLabel jImageLabel(String imageID) {
  return jImageLabel(imageIcon(imageID));
}

static JLabel jImageLabel(String text, String imageID) {
  final JLabel l = swingNu(JLabel.class, text, imageIcon(imageID), JLabel.CENTER);
  { swing(new Runnable() {  public void run() { try { 
    l.setVerticalTextPosition(SwingConstants.BOTTOM);
    l.setHorizontalTextPosition(SwingConstants.CENTER);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "l.setVerticalTextPosition(SwingConstants.BOTTOM);\r\n    l.setHorizontalTextPos..."; }}); }
  return l;
}

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

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

static boolean loadBufferedImage_useImageCache = true;

static BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) { try {
  ping();
  if (snippetIDOrURLOrFile == null) return null;
  if (isURL(snippetIDOrURLOrFile))
    return imageIO_readURL(snippetIDOrURLOrFile);

  if (isAbsolutePath(snippetIDOrURLOrFile)) 
    return loadBufferedImage(new File(snippetIDOrURLOrFile));
  
  if (!isSnippetID(snippetIDOrURLOrFile))
    throw fail("Not a URL or snippet ID or file: " + snippetIDOrURLOrFile);
  String snippetID = "" + parseSnippetID(snippetIDOrURLOrFile);
  
  
  IResourceLoader rl = vm_getResourceLoader();
  if (rl != null)
    return loadBufferedImage(rl.loadLibrary(snippetID));
  
  
  File dir = imageSnippetsCacheDir();
  if (loadBufferedImage_useImageCache) {
    dir.mkdirs();
    File file = new File(dir, snippetID + ".png");
    if (file.exists() && file.length() != 0)
      try {
        return ImageIO.read(file);
      } catch (Throwable e) {
        e.printStackTrace();
        // fall back to loading from sourceforge
      }
  }

  String imageURL = snippetImageURL_http(snippetID);
  print("Loading image: " + imageURL);
  BufferedImage image = imageIO_readURL(imageURL);

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

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

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

static JPanel centerAndEastWithMarginInbetween(Component c, final Component e) {
  return centerAndEast(c, withLeftMargin(e));
}

static JLabel jcenteredBoldLabel(String text) {
  JLabel l = jboldLabel(text);
  l.setHorizontalAlignment(JLabel.CENTER);
  return l;
}

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

static boolean newButton_autoToolTip = true;

// action can be Runnable or a function name
static JButton newButton(final String text, final Object action) {
  return swing(new F0<JButton>() { public JButton get() { try { 
    String text2 = dropPrefix("[disabled] ", text);
    final JButton btn = new JButton(text2);
    if (l(text2) < l(text)) btn.setEnabled(false);
    if (newButton_autoToolTip) {
      btn.setToolTipText(btn.getText());
      //onChangeAndNow(btn, r { btn.setToolTipText(btn.getText()) });
    }
    // submitButtonOnEnter(btn); // test this first
    if (action != null)
      btn.addActionListener(actionListener(action, btn));
    return btn;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "S text2 = dropPrefix(\"[disabled] \", text);\r\n    final JButton btn = new JButt..."; }});
}

static JButton setButtonImage(BufferedImage img, JButton btn) {
  btn.setIcon(imageIcon(img));
  return btn;
}

static JButton setButtonImage(JButton btn, BufferedImage img) {
  return setButtonImage(img, btn);
}

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

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

/*static JButton jbutton(BufferedImage img, O action) {
  ret setButtonImage(img, jbutton("", action));
}*/

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

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

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 <A, B> Map<A, B> cloneMap(Map<A, B> map) {
  if (map == null) return new HashMap();
  // assume mutex is equal to map
  synchronized(map) {
    return map instanceof TreeMap ? new TreeMap((TreeMap) map) // copies comparator
      : map instanceof LinkedHashMap ? new LinkedHashMap(map)
      : new HashMap(map);
  }
}

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

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

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

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 Map paramsToMap(Object... params) {
  int n = l(params);
  if (l(params) == 1 && params[0] instanceof Map) return (Map) params[0];
  LinkedHashMap map = new LinkedHashMap();
  for (int i = 0; i+1 < n; i += 2)
    mapPut(map, params[i], params[i+1]);
  return map;
}

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 Object[] mapToObjectArray(Object f, Collection l) {
  int n = l(l);
  Object[] array = new Object[n];
  if (n != 0) {
    Iterator it = iterator(l);
    for (int i = 0; i < n; i++)
      array[i] = callF(f, it.next());
  }
  return array;
}

static Object[] mapToObjectArray(Object f, Object[] l) {
  int n = l(l);
  Object[] array = new Object[n];
  for (int i = 0; i < n; i++)
    array[i] = callF(f, l[i]);
  return array;
}

static <A> Object[] mapToObjectArray(Collection<A> l, IF1<A, Object> f) {
  return mapToObjectArray(f, l);
}

static <A> Object[] mapToObjectArray(A[] l, IF1<A, Object> f) {
  return mapToObjectArray(f, l);
}

static String programIDPlusHome() {
  return programIDPlusHome(programID(), userHomeIfNotActual());
}

static String programIDPlusHome(String programID, File home) {
  return programIDPlusHome(programID, f2s(home));
}

static String programIDPlusHome(String programID, String home) {
  if (home != null)
    programID += " " + quote(home);
  return programID;
}

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


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


// returns null if program not running, answer otherwise
static String activateFramesOf(String progID) {
  return sendOptQuietly(fsIOpt(progID) + " Frames.", "activate frames");
}

static void cleanKill() {
  cleanKillVM();
}

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

static Object safeUnstructure(String s) {
  return unstructure(s, true);
}

static String loadTextFileFromZip(File inZip, String fileName) {
  return loadTextFileFromZipFile(inZip, fileName);
}

static <A> A assertNempty(A a) {
  return assertNempty("empty", a);
}

static <A> A assertNempty(String msg, A a) {
  if (empty(a)) throw fail(msg + ": " + a);
  return a;
}

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

static int or0(Integer i) { return i == null ? 0 : i; }
static long or0(Long l) { return l == null ? 0L : l; }
static double or0(Double d) { return d == null ? 0.0 : d; }

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

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

static File loadLibrary(String snippetID) {
  return loadBinarySnippet(snippetID);
}

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

static File optExtractFileFromZipToDir_tryMultipleNames(File zip, File dir, String... names) {
  for (String name : unnull(names))
    if (zipFileContains(zip, name))
      return optExtractFileFromZipToDir(zip, dir, name);
  return null;
}


static File optExtractFileFromZipToDir(File zip, File dir, String name) {
  File f = newFile(dir, name);
  if (f.exists()) return f;
  extractFileFromZip(zip, name, f);
  return f;
}


static <A, B> Map<A, B> syncMRUCache(int size) {
  return synchroMap(new MRUCache(size));
}

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

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

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

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

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

static 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 String formatWithThousands(long l) {
  return formatWithThousandsSeparator(l);
}

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

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

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

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

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



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

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

static 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 {
    
    return hotwire_overInternalBot(src);
    
    
  }
}

static void setOptAll(Object o, Map<String, Object> fields) {
  if (fields == null) return;
  for (String field : keys(fields))
    setOpt/*_flex*/(o, field, fields.get(field));
}

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

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

static void callMain() {
  callMain(mc());
}

static Object[] concatArrays(Object[]... arrays) {
  int l = 0;
  for (Object[] a : arrays) l += l(a);
  Object[] x = new Object[l];
  int i = 0;
  for (Object[] a : arrays) if (a != null) {
    System.arraycopy(a, 0, x, i, l(a));
    i += l(a);
  }
  return x;
}


static Object dm_callOS(String functionName, Object... args) {
  return call(dm_os(), functionName, args);
}

static void dynamicObject_setRawFieldValue(DynamicObject o, Object key, Object value) {
  if (o == null) return;
  
  // double sync, but should be OK here because of locking order o > o.fieldValues
  synchronized(o) {
    o.fieldValues = syncMapPut2_createLinkedHashMap((LinkedHashMap) o.fieldValues, key, value);
  }
}

static TreeSet<String> toCaseInsensitiveSet(Iterable<String> c) {
  if (isCISet(c)) return (TreeSet) c;
  TreeSet<String> set = caseInsensitiveSet();
  addAll(set, c);
  return set;
}

static TreeSet<String> toCaseInsensitiveSet(String... x) {
  TreeSet<String> set = caseInsensitiveSet();
  addAll(set, x);
  return set;
}

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 Throwable getException(Runnable r) {
  try {
    callF(r);
    return null;
  } catch (Throwable e) {
    return e;
  }
}

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

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



static 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 int withMargin_defaultWidth = 6;

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

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

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

static JPanel withMargin(final int top, final int left, final int bottom, final int right, final Component c) {
  return swing(new F0<JPanel>() { public JPanel get() { try { 
    JPanel p = new JPanel(new BorderLayout());
    p.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right));
    p.add(c);
    return p;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n    p.setBorder(BorderFactory.creat..."; }});
}

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

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



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

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

static <A, B> void multiMapPut(Map<A, List<B>> map, A a, B b) {
  List<B> l = map.get(a);
  if (l == null)
    map.put(a, l = new ArrayList());
  l.add(b);
}



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

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

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

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

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



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

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

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

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

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

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

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

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

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

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

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

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

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

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

static 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 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 volatile boolean licensed_yes = true;

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

static void licensed_off() {
  licensed_yes = false;
}

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

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

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

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

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

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

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 boolean isInstanceOf(Object o, Class type) {
  return type.isInstance(o);
}

static <A extends Component> A setWindowSize(A c, int w, int h) {
  Window window = getWindow(c);
  if (window != null)
    window.setSize(w, h);
  return c;
}

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

static JRootPane getRootPane(Component c) {
  Component f = (Component) getPossiblyInternalFrame(c);
  return f instanceof RootPaneContainer ? (JRootPane) swingCall(f, "getRootPane") : null;
}

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

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



static <A extends JComponent> A addMargin(final int top, final int left, final int bottom, final int right, final A c) {
  if (c != null) { swing(new Runnable() {  public void run() { try { 
    Border margin = BorderFactory.createEmptyBorder(top, left, bottom, right);
    c.setBorder(jCompoundBorder(c.getBorder(), margin));
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "Border margin = BorderFactory.createEmptyBorder(top, left, bottom, right);\r\n ..."; }}); }
  return c;
}

static <A extends JComponent> A addMargin(int w, A c) {
  return addMargin(w, w, w, w, c);
}


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

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

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

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



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

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

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


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

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

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

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

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

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

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

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

static JPanel centerAndEast(final Component c, final Component e) {
  return swing(new F0<JPanel>() { public JPanel get() { try { 
    JPanel panel = new JPanel(new BorderLayout());
    panel.add(BorderLayout.CENTER, wrap(c));
    panel.add(BorderLayout.EAST, wrap(e));
    return panel;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n    panel.add(BorderLayout.CENT..."; }});
}

static int withLeftMargin_defaultWidth = 6;

static JPanel withLeftMargin(Component c) {
  return withLeftMargin(withLeftMargin_defaultWidth, c);
}

static JPanel withLeftMargin(final int margin, final Component c) {
  return swing(new F0<JPanel>() { public JPanel get() { try { 
    JPanel p = new JPanel(new BorderLayout());
    p.setBorder(BorderFactory.createEmptyBorder(0, margin, 0, 0));
    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 JLabel jboldLabel(String text) {
  return makeLabelBold(jlabel(text));
}

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

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

static ActionListener actionListener(final Object runnable, final Object instanceToHold) {
  if (runnable instanceof ActionListener) return (ActionListener) runnable;
  final Object info = _threadInfo();
  return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
    _threadInheritInfo(info);
     AutoCloseable __1 = holdInstance(instanceToHold); try {
    callF(runnable);
  } finally { _close(__1); }} catch (Throwable __e) { messageBox(__e); }}};
}

static <A> A swingConstruct(final Class<A> c, final Object... args) {
  return swing(new F0<A>() { public A get() { try {  return nuObject(c, args);  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret nuObject(c, args);"; }});
}

static String 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 <A, B> void mapPut(Map<A, B> map, A key, B value) {
  if (map != null && key != null && value != null) map.put(key, value);
}


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


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

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









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


static <A> Iterator<A> iterator(Iterable<A> c) {
  return c == null ? emptyIterator() : c.iterator();
}

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

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

static String userHomeIfNotActual() {
  String home = userHome();
  return eq(home, actualUserHome()) ? null : home;
}

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

static String quote(String s) {
  if (s == null) return "null";
  StringBuilder out = new StringBuilder((int) (l(s)*1.5+2));
  quote_impl(s, out);
  return out.toString();
}
  
static void quote_impl(String s, StringBuilder out) {
  out.append('"');
  int l = s.length();
  for (int i = 0; i < l; i++) {
    char c = s.charAt(i);
    if (c == '\\' || c == '"')
      out.append('\\').append(c);
    else if (c == '\r')
      out.append("\\r");
    else if (c == '\n')
      out.append("\\n");
    else if (c == '\t')
      out.append("\\t");
    else if (c == '\0')
      out.append("\\0");
    else
      out.append(c);
  }
  out.append('"');
}

static boolean startsWithIgnoreCase(String a, String b) {
  return regionMatchesIC(a, 0, b, 0, b.length());
}

static String sendOptQuietly(String bot, String text, Object... args) {
  return sendToLocalBotOptQuietly(bot, text, args);
}

static String fsIOpt(String s) {
  return formatSnippetIDOpt(s);
}

static void cleanKillVM() { try {
  ping();
  assertNotOnAWTThread();
  cleanKillVM_noSleep();
  Object o = new Object();
  synchronized(o) { o.wait(); }
} catch (Exception __e) { throw rethrow(__e); } }

static void cleanKillVM_noSleep() {
  call(getJavaX(), "cleanKill");
}

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 Map vm_generalMap_map;

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

// TODO: cyclic structures involving certain lists & sets

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

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

static Object unstructure(String text, IF1<String, Class> classFinder) {
  return unstructure(text, false, classFinder);
}

static int structure_internStringsLongerThan = 50;
static int unstructure_unquoteBufSize = 100;

static int unstructure_tokrefs; // stats

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

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

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

static Object unstructure_tok(final Producer<String> tok, final boolean allDynamic, final Object _classFinder) {
  final boolean debug = unstructure_debug;
  
  final class X {
    int i = -1;
    final Object classFinder = _classFinder != null ? _classFinder : _defaultClassFinder();
    HashMap<Integer, Object> refs = new HashMap();
    HashMap<Integer, Object> tokrefs = new HashMap();
    HashSet<String> concepts = new HashSet();
    HashMap<String, Class> classesMap = new HashMap();
    List<Runnable> stack = new ArrayList();
    Map<String, String> baseClassMap = new HashMap();
    String curT;
    char[] unquoteBuf = new char[unstructure_unquoteBufSize];
    
    Class findAClass(String fullClassName) {
      return classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName);
    }
    
    String unquote(String s) {
      return unquoteUsingCharArray(s, unquoteBuf); 
    }

    // look at current token
    String t() {
      return curT;
    }
    
    // get current token, move to next
    String tpp() {
      String t = curT;
      consume();
      return t;
    }
    
    void parse(final unstructure_Receiver out) {
      String t = t();
      
      int refID;
      if (structure_isMarker(t, 0, l(t))) {
        refID = parseInt(t.substring(1));
        consume();
      } else refID = -1;
      
      // if (debug) print("parse: " + quote(t));
      
      final int tokIndex = i;  
      parse_inner(refID, tokIndex, new unstructure_Receiver() {
        void set(Object o) {
          if (refID >= 0)
            refs.put(refID, o);
          if (o != null)
            tokrefs.put(tokIndex, o);
          out.set(o);
        }
      });
    }
    
    void parse_inner(int refID, int tokIndex, unstructure_Receiver out) {
      String t = t();
      
      // if (debug) print("parse_inner: " + quote(t));
      
      Class c = classesMap.get(t);
      if (c == null) {
        if (t.startsWith("\"")) {
          String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan);
          out.set(s); return;
        }
        
        if (t.startsWith("'")) {
          out.set(unquoteCharacter(tpp())); return;
        }
        if (t.equals("bigint")) {
          out.set(parseBigInt()); return;
        }
        if (t.equals("d")) {
          out.set(parseDouble()); return;
        }
        if (t.equals("fl")) {
          out.set(parseFloat()); return;
        }
        if (t.equals("sh")) {
          consume();
          t = tpp();
          if (t.equals("-")) {
            t = tpp();
            out.set((short) (-parseInt(t))); return;
          }
          out.set((short) parseInt(t)); return;
        }
        if (t.equals("-")) {
          consume();
          t = tpp();
          out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t))); return;
        }
        if (isInteger(t) || isLongConstant(t)) {
          consume();
          //if (debug) print("isLongConstant " + quote(t) + " => " + isLongConstant(t));
          if (isLongConstant(t)) {
            out.set(parseLong(t)); return;
          }
          long l = parseLong(t);
          boolean isInt = l == (int) l;
          
          out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l)); return;
        }
        if (t.equals("false") || t.equals("f")) {
          consume(); out.set(false); return;
        }
        if (t.equals("true") || t.equals("t")) {
          consume(); out.set(true); return;
        }
        if (t.equals("-")) {
          consume();
          t = tpp();
          out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t))); return;
        }
        if (isInteger(t) || isLongConstant(t)) {
          consume();
          //if (debug) print("isLongConstant " + quote(t) + " => " + isLongConstant(t));
          if (isLongConstant(t)) {
            out.set(parseLong(t)); return;
          }
          long l = parseLong(t);
          boolean isInt = l == (int) l;
          
          out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l)); return;
        }
        
        if (t.equals("File")) {
          consume();
          File f = new File(unquote(tpp()));
          out.set(f); return;
        }
        
        if (t.startsWith("r") && isInteger(t.substring(1))) {
          consume();
          int ref = Integer.parseInt(t.substring(1));
          Object o = refs.get(ref);
          if (o == null)
            throw fail("unsatisfied back reference " + ref);
          out.set(o); return;
        }
      
        if (t.startsWith("t") && isInteger(t.substring(1))) {
          consume();
          int ref = Integer.parseInt(t.substring(1));
          Object o = tokrefs.get(ref);
          if (o == null)
            throw fail("unsatisfied token reference " + ref + " at " + tokIndex);
          out.set(o); return;
        }
        
        if (t.equals("hashset")) { parseHashSet(out); return; }
        if (t.equals("lhs")) { parseLinkedHashSet(out); return; }
        if (t.equals("treeset")) { parseTreeSet(out); return; }
        if (t.equals("ciset")) { parseCISet(out); return; }
        
        if (eqOneOf(t, "hashmap", "hm")) {
          consume();
          parseMap(new HashMap(), out);
          return;
        }
        if (t.equals("lhm")) {
          consume();
          parseMap(new LinkedHashMap(), out);
          return;
        }
        if (t.equals("tm")) {
          consume();
          parseMap(new TreeMap(), out);
          return;
        }
        if (t.equals("cimap")) {
          consume();
          parseMap(ciMap(), out);
          return;
        }
        
        if (t.equals("ll")) {
          consume();
          LinkedList l = new LinkedList();
          if (refID >= 0) refs.put(refID, l);
          { parseList(l, out); return; }
        }

        if (t.equals("syncLL")) { // legacy
          consume();
          { parseList(synchroLinkedList(), out); return; }
        }

        if (t.equals("sync")) {
          consume();
          { parse(new unstructure_Receiver() {
            void set(Object value) {
              if (value instanceof Map) {
                 // Java 7
                if (value instanceof NavigableMap)
                  { out.set(synchroNavigableMap(((NavigableMap) value))); return; }
                
                if (value instanceof SortedMap)
                  { out.set(synchroSortedMap(((SortedMap) value))); return; }
                { out.set(synchroMap((Map) value)); return; }
              } else
                { out.set(synchroList((List) value)); return; }
            }
          }); return; }
        }
        
        if (t.equals("{")) {
          parseMap(out); return;
        }
        if (t.equals("[")) {
          ArrayList l = new ArrayList();
          if (refID >= 0) refs.put(refID, l);
          this.parseList(l, out); return;
        }
        if (t.equals("bitset")) {
          parseBitSet(out); return;
        }
        if (t.equals("array") || t.equals("intarray") || t.equals("dblarray")) {
          parseArray(out); return;
        }
        if (t.equals("ba")) {
          consume();
          String hex = unquote(tpp());
          out.set(hexToBytes(hex)); return;
        }
        if (t.equals("boolarray")) {
          consume();
          int n = parseInt(tpp());
          String hex = unquote(tpp());
          out.set(boolArrayFromBytes(hexToBytes(hex), n)); return;
        }
        if (t.equals("class")) {
          out.set(parseClass()); return;
        }
        if (t.equals("l")) {
          parseLisp(out); return;
        }
        if (t.equals("null")) {
          consume(); out.set(null); return;
        }
        
        if (eq(t, "c")) {
          consume();
          t = t();
          assertTrue(isJavaIdentifier(t));
          concepts.add(t);
        }
        
        // custom deserialization (new static method method)
        if (eq(t, "cu")) {
          consume();
          t = tpp();
          assertTrue(isJavaIdentifier(t));
          String fullClassName = "main$" + t;
          Class _c = findAClass(fullClassName);
          if (_c == null) throw fail("Class not found: " + fullClassName);
          parse(new unstructure_Receiver() {
            void set(Object value) {
              
              out.set(call(_c, "_deserialize", value));
            }
          });
          return;
        }
      }
      
      if (eq(t, "j")) {
        consume();
        out.set(parseJava()); return;
      }
      
      if (eq(t, "bc")) {
        consume();
        String c1 = tpp();
        String c2 = tpp();
        baseClassMap.put(c1, c2);
        { parse_inner(refID, i, out); return; }
      }
      
      // add more tokens here

      if (c == null && !isJavaIdentifier(t))
        throw new RuntimeException("Unknown token " + (i+1) + ": " + quote(t));
        
      // any other class name (or package name)
      consume();
      String className, fullClassName;
      
      // Is it a package name?
      if (eq(t(), ".")) {
        consume();
        className = fullClassName = t + "." + assertIdentifier(tpp());
      } else {
        className = t;
        fullClassName = "main$" + t;
      }
      
      if (c == null && !allDynamic) {
        // First, find class
        c = findAClass(fullClassName);
        if (c != null)
          classesMap.put(className, c);
      }
      
      // check for existing base class
      if (c == null && !allDynamic) {
        String baseName = baseClassMap.get(className);
        if (baseName != null) {
          c = findAClass("main$" + baseName);
          if (c != null)
            classesMap.put(className, c);
        }
        
      }
          
      // Check if it has an outer reference
      boolean hasBracket = eq(t(), "(");
      if (hasBracket) consume();
      boolean hasOuter = hasBracket && eq(t(), "this$1");
      
      DynamicObject dO = null;
      Object o = null;
      final String thingName = t;
      if (c != null) {
        o = hasOuter ? nuStubInnerObject(c, classFinder) : nuEmptyObject(c);
        if (o instanceof DynamicObject) dO = (DynamicObject) o;
      } else {
        if (concepts.contains(t) && (c = findAClass("main$Concept")) != null)
          o = dO = (DynamicObject) nuEmptyObject(c);
        else
          dO = new DynamicObject();
        dO.className = className;
        
      }
      
      // Save in references list early because contents of object
      // might link back to main object
      
      if (refID >= 0)
        refs.put(refID, o != null ? o : dO);
      tokrefs.put(tokIndex, o != null ? o : dO);
      
      // NOW parse the fields!
      
      HashMap<String, Object> fields = new HashMap(); // no longer preserving order (why did we do this?)
      Object _o = o;
      DynamicObject _dO = dO;
      if (hasBracket) {
        stack.add(new Runnable() {  public void run() { try { 
          
          if (eq(t(), ",")) consume();
          if (eq(t(), ")")) {
            consume(")");
            objRead(_o, _dO, fields, hasOuter);
            out.set(_o != null ? _o : _dO);
          } else {
            final String key = unquote(tpp());
            String t = tpp();
            if (!eq(t, "="))
              throw fail("= expected, got " + t + " after " + quote(key) + " in object " + thingName /*+ " " + sfu(fields)*/);
            stack.add(this);
            parse(new unstructure_Receiver() {
              void set(Object value) {
                fields.put(key, value);
                /*ifdef unstructure_debug
                  print("Got field value " + value + ", next token: " + t());
                endifdef*/
                //if (eq(t(), ",")) consume();
              }
            });
          }
        
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "ifdef unstructure_debug\r\n            print(\"in object values, token: \" + t())..."; }});
      } else {
        objRead(o, dO, fields, hasOuter);
        out.set(o != null ? o : dO);
      }
    }
    
    void objRead(Object o, DynamicObject dO, Map<String, Object> fields, boolean hasOuter) {
      
      if (o != null) {
        if (dO != null) {
          
          setOptAllDyn_pcall(dO, fields);
        } else {
          setOptAll_pcall(o, fields);
          
        }
        if (hasOuter)
          fixOuterRefs(o);
      } else for (Map.Entry<String, Object> e : fields.entrySet())
        setDynObjectValue(dO, intern(e.getKey()), e.getValue());

      if (o != null)
        pcallOpt_noArgs(o, "_doneLoading");
    }
    
    void parseSet(final Set set, final unstructure_Receiver out) {
      this.parseList(new ArrayList(), new unstructure_Receiver() {
        void set(Object o) {
          set.addAll((List) o);
          out.set(set);
        }
      });
    }
    
    void parseLisp(final unstructure_Receiver out) {
      
      
      throw fail("class Lisp not included");
    }
    
    void parseBitSet(final unstructure_Receiver out) {
      consume("bitset");
      consume("{");
      final BitSet bs = new BitSet();
      stack.add(new Runnable() {  public void run() { try { 
        if (eq(t(), "}")) {
          consume("}");
          out.set(bs);
        } else {
          stack.add(this);
          parse(new unstructure_Receiver() {
            void set(Object o) {
              bs.set((Integer) o);
              if (eq(t(), ",")) consume();
            }
          });
        }
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (eq(t(), \"}\")) {\r\n          consume(\"}\");\r\n          out.set(bs);\r\n       ..."; }});
    }
    
    void parseList(final List list, final unstructure_Receiver out) {
      tokrefs.put(i, list);
      consume("[");
      stack.add(new Runnable() {  public void run() { try { 
        if (eq(t(), "]")) {
          consume();
          
          out.set(list);
        } else {
          stack.add(this);
          parse(new unstructure_Receiver() {
            void set(Object o) {
              //if (debug) print("List element type: " + getClassName(o));
              list.add(o);
              if (eq(t(), ",")) consume();
            }
          });
        }
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (eq(t(), \"]\")) {\r\n          consume();\r\n          ifdef unstructure_debug\r..."; }});
    }
    
    void parseArray(final unstructure_Receiver out) {
      final String type = tpp();
      consume("{");
      final List list = new ArrayList();
      
      stack.add(new Runnable() {  public void run() { try { 
        if (eq(t(), "}")) {
          consume("}");
          out.set(
            type.equals("intarray") ? toIntArray(list)
            : type.equals("dblarray") ? toDoubleArray(list)
            : list.toArray());
        } else {
          stack.add(this);
          parse(new unstructure_Receiver() {
            void set(Object o) {
              list.add(o);
              if (eq(t(), ",")) consume();
            }
          });
        }
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (eq(t(), \"}\")) {\r\n          consume(\"}\");\r\n          out.set(\r\n           ..."; }});
    }
    
    Object parseClass() {
      consume("class");
      consume("(");
      String name = unquote(tpp());
      consume(")");
      Class c = allDynamic ? null : findAClass(name);
      if (c != null) return c;
      DynamicObject dO = new DynamicObject();
      dO.className = "java.lang.Class";
      name = dropPrefix("main$", name);
      dO.fieldValues.put("name", name);
      return dO;
    }
    
    Object parseBigInt() {
      consume("bigint");
      consume("(");
      String val = tpp();
      if (eq(val, "-"))
        val = "-" + tpp();
      consume(")");
      return new BigInteger(val);
    }
    
    Object parseDouble() {
      consume("d");
      consume("(");
      String val = unquote(tpp());
      consume(")");
      return Double.parseDouble(val);
    }
    
    Object parseFloat() {
      consume("fl");
      String val;
      if (eq(t(), "(")) {
        consume("(");
        val = unquote(tpp());
        consume(")");
      } else {
        val = unquote(tpp());
      }
      return Float.parseFloat(val);
    }
    
    void parseHashSet(unstructure_Receiver out) {
      consume("hashset");
      parseSet(new HashSet(), out);
    }
    
    void parseLinkedHashSet(unstructure_Receiver out) {
      consume("lhs");
      parseSet(new LinkedHashSet(), out);
    }
    
    void parseTreeSet(unstructure_Receiver out) {
      consume("treeset");
      parseSet(new TreeSet(), out);
    }
    
    void parseCISet(unstructure_Receiver out) {
      consume("ciset");
      parseSet(ciSet(), out);
    }
    
    void parseMap(unstructure_Receiver out) {
      parseMap(new TreeMap(), out);
    }
    
    Object parseJava() {
      String j = unquote(tpp());
      Matches m = new Matches();
      if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m))
        return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2)));
      else {
        warn("Unknown Java object: " + j);
        return null;
      }
    }
    
    void parseMap(final Map map, final unstructure_Receiver out) {
      consume("{");
      stack.add(new Runnable() {
        boolean v = false;
        Object key;
        
        public void run() { 
          if (v) {
            v = false;
            stack.add(this);
            if (!eq(tpp(), "="))
              throw fail("= expected, got " + t() + " in map of size " + l(map));

            parse(new unstructure_Receiver() {
              void set(Object value) {
                map.put(key, value);
                
                if (eq(t(), ",")) consume();
              }
            });
          } else {
            if (eq(t(), "}")) {
              consume("}");
              out.set(map);
            } else {
              v = true;
              stack.add(this);
              parse(new unstructure_Receiver() {
                void set(Object o) {
                  key = o;
                }
              });
            }
          } // if v else
        } // run()
      });
    }
    
    /*void parseSub(unstructure_Receiver out) {
      int n = l(stack);
      parse(out);
      while (l(stack) > n)
        stack
    }*/
    
    void consume() { curT = tok.next(); ++i; }
    
    void consume(String s) {
      if (!eq(t(), s)) {
        /*S prevToken = i-1 >= 0 ? tok.get(i-1) : "";
        S nextTokens = join(tok.subList(i, Math.min(i+2, tok.size())));
        fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")");*/
        throw fail(quote(s) + " expected, got " + quote(t()));
      }
      consume();
    }
    
    // outer wrapper function getting first token and unwinding the stack
    void parse_initial(unstructure_Receiver out) {
      consume(); // get first token
      parse(out);
      while (nempty(stack))
        popLast(stack).run();
    }
  }
  
  ThreadLocal<Boolean> tlLoading = dynamicObjectIsLoading_threadLocal();
  Boolean b = tlLoading.get();
  tlLoading.set(true);
  try {
    final Var v = new Var();
    X x = new X();
    x.parse_initial(new unstructure_Receiver() {
      void set(Object o) { v.set(o); }
    });
    unstructure_tokrefs = x.tokrefs.size();
    return v.get();
  } finally {
    tlLoading.set(b);
  }
}

static boolean unstructure_debug = false;

static String loadTextFileFromZipFile(File inZip, String fileName) { try {
  if (!fileExists(inZip)) return null;
  try {
     ZipFile zip = new ZipFile(inZip); try {
    return loadTextFileFromZipFile(zip, fileName);
  } finally { _close(zip); }} catch (Throwable e) {
    throw fail(f2s(inZip), e);
  }
} catch (Exception __e) { throw rethrow(__e); } }
    
static String loadTextFileFromZipFile(ZipFile zip, String fileName) { try {
  ZipEntry entry = zip.getEntry(fileName);
  if (entry == null) return null;
   InputStream fin = zip.getInputStream(entry); try {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  copyStream(fin, baos);
  return fromUTF8(baos.toByteArray());
} finally { _close(fin); }} catch (Exception __e) { throw rethrow(__e); } }

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

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

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

static boolean zipFileContains(File inZip, String fileName) { try {
  ZipFile zip = new ZipFile(inZip);
  try {
    return zipFileContains(zip, fileName);
  } finally {
    zip.close();
  }
} catch (Exception __e) { throw rethrow(__e); } }
    
static boolean zipFileContains(ZipFile zip, String fileName) { try {
  return zip.getEntry(fileName) != null;
} catch (Exception __e) { throw rethrow(__e); } }

static void extractFileFromZip(File inZip, String fileName, File destFile) {
  extractFileFromZipFile(inZip, fileName, destFile);
}


    
static void extractFileFromZip(ZipFile zip, String fileName, File destFile) {
  extractFileFromZipFile(zip, fileName, destFile);
}



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

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

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

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


static boolean _inCore() {
  return false;
}

static Object hotwire_onCompile; // voidfunc(Pair<jarFile, transpiledSource>)
static boolean hotwire_serially = false;
static Lock hotwire_overInternalBot_lock = lock();
static boolean hotwire_compileOnServer = false;

static Class<?> hotwire_overInternalBot(String progID) {
  return hotwire_overInternalBot(progID, "main");
}

static Class<?> hotwire_overInternalBot(String progID, String mainClass) { try {
  Pair<File, String> p;
  try {
    p = hotwire_compile(progID);
  } catch (Throwable e) {
    throw rethrow("Error hotwiring " + progID, e);
  }
  File jar = p.a;
  assertTrue(jar.getAbsolutePath(), jar.isFile());
  
  List<File> files = hotwire_collectJars(jar);

  // make class loader
  JavaXClassLoader classLoader = hotwire_makeClassLoader(files);
  classLoader.progID = progID;
  
  return hotwire_finish(classLoader, progID, p.b, mainClass);
} catch (Exception __e) { throw rethrow(__e); } }

// returns pair(jar, transpiled src)
static Pair<File, String> hotwire_compile(String progID) {
  Pair<File, String> p = hotwire_compileOnServer && !isLocalSnippetID(progID)
    ? compileSnippetThroughServer(progID)
    : CompilerBot.compileSnippet2(progID);
  Lock __0 = hotwire_serially ? hotwire_overInternalBot_lock : null; lock(__0); try {
  callF(hotwire_onCompile, p);
  return p;
} finally { unlock(__0); } }

static void warnIfOddCount(Object... list) {
  if (odd(l(list)))
    printStackTrace("Odd list size: " + list);
}

static Object dm_os() {
  { Object __1= vm_generalMap_get("stefansOS"); if (__1 != null) return __1; }
  return creator();
}

static <A, B> LinkedHashMap<A, B> syncMapPut2_createLinkedHashMap(LinkedHashMap<A, B> map, A key, B value) {
  if (key != null)
    if (value != null) {
      if (map == null) map = new LinkedHashMap();
      synchronized(collectionMutex(map)) { map.put(key, value); }
    } else if (map != null) synchronized(collectionMutex(map)) { map.remove(key); }
  return map;
}

static boolean isCISet(Iterable<String> l) {
  return l instanceof TreeSet && ((TreeSet) l).comparator() == caseInsensitiveComparator();
}

static TreeSet<String> caseInsensitiveSet() {
  return caseInsensitiveSet_treeSet();
}

static TreeSet<String> caseInsensitiveSet(Collection<String> c) {
  return caseInsensitiveSet_treeSet(c);
}

static IterableIterator<String> toLines(File f) {
  return linesFromFile(f);
}

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

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

    start = i;
  }
  return lines;
}

static int toLines_nextLineBreak(String s, int start) {
  int n = s.length();
  for (int i = start; i < n; i++) {
    char c = s.charAt(i);
    if (c == '\r' || c == '\n')
      return i;
  }
  return -1;
}

static CloseableIterableIterator<String> linesFromFile(File f) { return linesFromFile(f, null); }
static CloseableIterableIterator<String> linesFromFile(File f, IResourceHolder resourceHolder) { try {
  if (!f.exists()) return emptyCloseableIterableIterator();
  
  if (ewic(f.getName(), ".gz"))
    return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)), resourceHolder);
  
  return linesFromReader(utf8bufferedReader(f), resourceHolder);
} catch (Exception __e) { throw rethrow(__e); } }

static CloseableIterableIterator<String> linesFromFile(String path) { return linesFromFile(path, null); }
static CloseableIterableIterator<String> linesFromFile(String path, IResourceHolder resourceHolder) {
  return linesFromFile(newFile(path), resourceHolder);
}



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

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

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

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 <A extends Throwable> A printException(A e) {
  printStackTrace(e);
  return e;
}

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



static boolean eqic(char a, char b) {
  if (a == b) return true;
  
    char u1 = Character.toUpperCase(a);
    char u2 = Character.toUpperCase(b);
    if (u1 == u2) return true;
  
  return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}

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


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


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

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

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

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

static 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 RootPaneContainer getPossiblyInternalFrame(Component c) {
  JInternalFrame f = getInternalFrame(c);
  if (f != null) return f;
  return optCast(RootPaneContainer.class, getWindow(c));
}

static Object swingCall(final Object o, final String method, final Object... args) {
  return swing(new F0<Object>() { public Object get() { try {  return call(o, method, args);  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret call(o, method, args);"; }});
}

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

static JComponent componentToJComponent(Component c) {
  if (c instanceof JComponent) return (JComponent) c;
  if (c instanceof JFrame) return ((JFrame) c).getRootPane();
  if (c == null) return null;
  throw fail("boohoo " + getClassName(c));
}


static JScrollPane jscroll(final Component c) {
  return swing(new F0<JScrollPane>() { public JScrollPane get() { try {  return new JScrollPane(c);  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret new JScrollPane(c);"; }});
}

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

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

static Border jCompoundBorder(Border inner, Border outer) {
  if (inner == null) return outer;
  if (outer == null) return inner;
  return BorderFactory.createCompoundBorder(inner, outer);
}

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

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

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

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






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

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

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

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

  int numImages = reader.getNumImages(true);

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

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

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

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

              break;
          }
      }
  }

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

      writer.prepareWriteSequence(null);

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

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

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

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

                  break;
              }
          }

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

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

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

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

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

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



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

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

static double parseDouble(String s) {
  return Double.parseDouble(s);
}

static String shortenSnippetID(String snippetID) {
  if (snippetID.startsWith("#"))
    snippetID = snippetID.substring(1);
  String httpBlaBla = "http://tinybrain.de/";
  if (snippetID.startsWith(httpBlaBla))
    snippetID = snippetID.substring(httpBlaBla.length());
  return "" + parseLong(snippetID);
}

static <A> A proxy(Class<A> intrface, final Object target) {
  if (target == null) return null;
  if (isInstance(intrface, target)) return (A) target;
  return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(),
    new Class[] { intrface },
    new proxy_InvocationHandler(target));
}

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

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

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

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

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

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

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

static JLabel makeLabelBold(final JLabel l) {
  if (l != null) { swing(new Runnable() {  public void run() { try { 
    l.setFont(l.getFont().deriveFont(Font.BOLD));
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "l.setFont(l.getFont().deriveFont(Font.BOLD));"; }}); }
  return l;
}

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 void messageBox(final String msg) {
  if (headless()) print(msg);
  else { swing(new Runnable() {  public void run() { try { 
    JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MES..."; }}); }
}

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

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

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

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

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

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

static 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 Iterator emptyIterator() {
  return Collections.emptyIterator();
}


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 regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
  
  
    return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
  
}

static String sendToLocalBotOptQuietly(String bot, String text, Object... args) {
  if (bot == null) return null;
  text = format(text, args);
   DialogIO channel = findBot(bot); try {
  if (channel == null) return null;
  try {
    channel.readLine();
    channel.sendLine(text);
    String s = channel.readLine();
    return s;
  } catch (Throwable e) {
    e.printStackTrace();
    return null;
  }
} finally { _close(channel); }}

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

static void assertNotOnAWTThread() {
  assertFalse("Can't do this in AWT thread", isAWTThread());
}
  

static Producer<String> javaTokC_noMLS_iterator(final String s) {
  return javaTokC_noMLS_iterator(s, 0);
}

static Producer<String> javaTokC_noMLS_iterator(final String s, final int startIndex) {
  return new Producer<String>() {
    final int l = s.length();
    int i = startIndex;
    
    public String next() {
      if (i >= l) return null;
      
      int j = i;
      char c, d;
      
      // scan for whitespace
      while (j < l) {
        c = s.charAt(j);
        d = j+1 >= l ? '\0' : s.charAt(j+1);
        if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
          ++j;
        else if (c == '/' && d == '*') {
          do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
          j = Math.min(j+2, l);
        } else if (c == '/' && d == '/') {
          do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
        } else
          break;
      }
      
      i = j;
      if (i >= l) return null;
      c = s.charAt(i);
      d = i+1 >= l ? '\0' : s.charAt(i+1);
  
      // scan for non-whitespace
      if (c == '\'' || c == '"') {
        char opener = c;
        ++j;
        while (j < l) {
          if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors
            ++j;
            break;
          } else if (s.charAt(j) == '\\' && j+1 < l)
            j += 2;
          else
            ++j;
        }
      } else if (Character.isJavaIdentifierStart(c))
        do ++j; while (j < l && Character.isJavaIdentifierPart(s.charAt(j)));
      else if (Character.isDigit(c)) {
        do ++j; while (j < l && Character.isDigit(s.charAt(j)));
        if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
      } else
        ++j;
        
      String t = quickSubstring(s, i, j);
      i = j;
      return t;
    }
  };
}


static Producer<String> javaTokC_noMLS_onReader(final BufferedReader r) {
  final class X implements Producer<String> {
    StringBuilder buf = new StringBuilder(); // stores from "i"
    char c, d, e = 'x'; // just not '\0'
    
    X() {
      // fill c, d and e
      nc();
      nc();
      nc();
    }
    
    // get next character(s) into c, d and e
    void nc() { try {
      c = d;
      d = e;
      if (e == '\0') return;
      int i = r.read();
      e = i < 0 ? '\0'
        : i == '\0' ? '_' // shouldn't happen anymore
        : (char) i;
    } catch (Exception __e) { throw rethrow(__e); } }
    
    void ncSave() {
      if (c != '\0') {
        buf.append(c);
        nc();
      }
    }
    
    public String next() {
      // scan for whitespace
      while (c != '\0') {
        if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
          nc();
        else if (c == '/' && d == '*') {
          do nc(); while (c != '\0' && !(c == '*' && d == '/'));
          nc(); nc();
        } else if (c == '/' && d == '/') {
          do nc(); while (c != '\0' && "\r\n".indexOf(c) < 0);
        } else
          break;
      }
      
      if (c == '\0') return null;

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


static Object _defaultClassFinder_value = defaultDefaultClassFinder();

static Object _defaultClassFinder() {
  return _defaultClassFinder_value;
}

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

// returns null on not found
// this is the simple version that is not case-tolerant
static Class findClass_fullName(String name) {
  synchronized(findClass_fullName_cache) {
    if (findClass_fullName_cache.containsKey(name))
      return findClass_fullName_cache.get(name);
      
    Class c;
    try {
      c = Class.forName(name);
    } catch (ClassNotFoundException e) {
      c = null;
    }
    findClass_fullName_cache.put(name, c);
    return c;
  }
}

static String unquoteUsingCharArray(String s, char[] buf) {
  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();
      if (l > buf.length) return unquote(s); // fallback
      int n = 0;
  
      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++;
                  }
              }
              buf[n++] = (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);
              char[] x = Character.toChars(code);
              int lx = x.length;
              for (int j = 0; j < lx; j++)
                buf[n++] = x[j];
              i += 5;
              continue;
          default:
            ch = nextChar; // added by Stefan
          }
          i++;
        }
        buf[n++] = ch;
      }
      return new String(buf, 0, n);
    }
  }
    
  return s; // not quoted - return original
}

static boolean structure_isMarker(String s, int i, int j) {
  if (i >= j) return false;
  if (s.charAt(i) != 'm') return false;
  ++i;
  while (i < j) {
    char c = s.charAt(i);
    if (c < '0' || c > '9') return false;
    ++i;
  }
  return true;
}

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

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

static String internIfLongerThan(String s, int l) {
  return s == null ? null : l(s) >= l ? intern(s) : s;
}

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 char unquoteCharacter(String s) {
  assertTrue(s.startsWith("'") && s.length() > 1);
  return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length()-1 : s.length()) + "\"").charAt(0);
}

static BigInteger parseBigInt(String s) {
  return new BigInteger(s);
}

static float parseFloat(String s) {
  return Float.parseFloat(s);
}

static boolean isLongConstant(String s) {
  if (!s.endsWith("L")) return false;
  s = s.substring(0, l(s)-1);
  return isInteger(s);
}

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

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

static <A> TreeMap<String, A> ciMap() {
  return caseInsensitiveMap();
}

static List parseList(String s) {
  return (List) safeUnstructure(s);
}

static <A> List<A> synchroLinkedList() {
  return Collections.synchronizedList(new LinkedList<A>());
}


static <A, B> NavigableMap<A, B> synchroNavigableMap(NavigableMap<A, B> map) {
  return (NavigableMap) call(Collections.class, "synchronizedNavigableMap", map);
}

static <A, B> SortedMap<A, B> synchroSortedMap(SortedMap<A, B> map) {
  
  
    return Collections.synchronizedSortedMap(map);
  
}

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 boolean[] boolArrayFromBytes(byte[] a, int n) {
  boolean[] b = new boolean[n];
  int m = min(n, l(a)*8);
  for (int i = 0; i < m; i++)
    b[i] = (a[i/8] & 1 << (i & 7)) != 0;
  return b;
}

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

static String assertIdentifier(String s) {
  return assertIsIdentifier(s);
}

static String assertIdentifier(String msg, String s) {
  return assertIsIdentifier(msg, s);
}

static <A> A nuStubInnerObject(Class<A> c) {
  return nuStubInnerObject(c, null);
}

static <A> A nuStubInnerObject(Class<A> c, Object classFinder) { try {
  Class outerType = getOuterClass(c, classFinder);
  Constructor m = c.getDeclaredConstructor(outerType);
  makeAccessible(m);
  return (A) m.newInstance(new Object[] {null});
} catch (Exception __e) { throw rethrow(__e); } }

static Map<Class, Constructor> nuEmptyObject_cache = newDangerousWeakHashMap();

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

  try {
    return (A) ctr.newInstance();
  } catch (InstantiationException e) {
    if (empty(e.getMessage()))
      if ((c.getModifiers() & Modifier.ABSTRACT) != 0)
        throw fail("Can't instantiate abstract class " + className(c), e);
      else
        throw fail("Can't instantiate " + className(c), e);  
    else throw rethrow(e);
  }
} catch (Exception __e) { throw rethrow(__e); } }

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


static void setOptAllDyn_pcall(DynamicObject o, Map<String, Object> fields) {
  if (fields == null || o == null) return;
  HashMap<String, Field> fieldMap = instanceFieldsMap(o);
  for (Map.Entry<String, Object> e : fields.entrySet()) { try {
    String field = e.getKey();
    Object val = e.getValue();
    Field f = fieldMap.get(field);
    if (f != null)
      smartSet(f, o, val);
    else {
      dynamicObject_setRawFieldValue(o, intern(field), val);
      
    }
  } catch (Throwable __e) { _handleException(__e); }}
}

static void setOptAll_pcall(Object o, Map<String, Object> fields) {
  if (fields == null) return;
  for (String field : keys(fields))
    try { setOpt(o, field, fields.get(field)); } catch (Throwable __e) { print(exceptionToStringShort(__e)); }
}

static void setOptAll_pcall(Object o, Object... values) {
  //values = expandParams(c.getClass(), values);
  warnIfOddCount(values);
  for (int i = 0; i+1 < l(values); i += 2) {
    String field = (String) values[i];
    Object value = values[i+1];
    try { setOpt(o, field, value); } catch (Throwable __e) { print(exceptionToStringShort(__e)); }
  }
}

static void fixOuterRefs(Object o) { try {
  if (o == null) return;
  Field[] l = thisDollarOneFields(o.getClass());
  if (l.length <= 1) return;
  Object father = null;
  for (Field f : l) {
    father = f.get(o);
    if (father != null) break;
  }
  if (father == null) return;
  for (Field f : l)
    f.set(o, father);
} catch (Exception __e) { throw rethrow(__e); } }

static String intern(String s) {
  return fastIntern(s);
}

static void pcallOpt_noArgs(Object o, String method) {
  try { callOpt_noArgs(o, method); } catch (Throwable __e) { _handleException(__e); }
}

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

static <A> List<A> subList(int startIndex, int endIndex, List<A> l) {
  return subList(l, startIndex, endIndex);
}

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



static int[] toIntArray(Collection<Integer> l) {
  int[] a = new int[l(l)];
  int i = 0;
  if (a.length != 0) for (int x : l)
    a[i++] = x;
  return a;
}

static double[] toDoubleArray(Collection<Double> l) {
  double[] a = new double[l(l)];
  int i = 0;
  if (a.length != 0) for (double x : l)
    a[i++] = x;
  return a;
}



static TreeSet<String> ciSet() {
  return caseInsensitiveSet();
}

static boolean jmatch(String pat, String s) {
  return jmatch(pat, s, null);
}

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

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

static boolean jmatch(String pat, List<String> toks, Matches matches) {
  List<String> tokpat = javaTok(pat);
  String[] m = match2(tokpat, toks);
  //print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m));
  if (m == null)
    return false;
  else {
    if (matches != null) matches.m = m;
    return true;
  }
}

static boolean warn_on = true;
static ThreadLocal<List<String>> warn_warnings = new ThreadLocal();

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

static void warn(String s, List<String> warnings) {
  warn(s);
  if (warnings != null)
    warnings.add(s);
  addToCollection(warn_warnings.get(), s);
}

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

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

static ThreadLocal<Boolean> dynamicObjectIsLoading_threadLocal() { 
  return DynamicObject_loading;
}

static boolean fileExists(String path) {
  return path != null && new File(path).exists();
}

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

static String fromUTF8(byte[] bytes) {
  return fromUtf8(bytes);
}


static File loadImageAsFile(String snippetIDOrURL) { try {
  if (isURL(snippetIDOrURL))
    throw fail("not implemented");

  if (!isSnippetID(snippetIDOrURL)) throw fail("Not a URL or snippet ID: " + snippetIDOrURL);
  String snippetID = "" + parseSnippetID(snippetIDOrURL);
  
  File file = imageSnippetCacheFile(snippetID);
  if (fileSize(file) > 0) return file;

  String imageURL = snippetImageURL_noHttps(snippetID);
  System.err.println("Loading image: " + imageURL);
  byte[] data = loadBinaryPage(imageURL);

  saveBinaryFile(file, data);
  return file;
} catch (Exception __e) { throw rethrow(__e); } }


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

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

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

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

static void extractFileFromZipFile(File inZip, String fileName, File destFile) { try {
  ZipFile zip = new ZipFile(inZip);
  try {
    extractFileFromZipFile(zip, fileName, destFile);
  } finally {
    zip.close();
  }
} catch (Exception __e) { throw rethrow(__e); } }
    
static void extractFileFromZipFile(ZipFile zip, String fileName, File destFile) { try {
  ZipEntry entry = zip.getEntry(fileName);
  if (entry == null) throw fail("File not found in zip: " + zip + " / " + fileName);
  saveStream(zip.getInputStream(entry), destFile);
} catch (Exception __e) { throw rethrow(__e); } }

static List<File> hotwire_collectJars(File jar) {
  List<String> libIDs = hotwire_libraryIDsFromJar_deleteJarOnFail(jar);
  List<File> files = ll(jar); // main program has to be first entry! (e.g. for hotwire_makeClassLoader_stickyAndSrcLibs)
  for (String libID : libIDs)
    files.add(loadLibraryOrSrcLib(libID));
  return files;
}

static JavaXClassLoader hotwire_makeClassLoader(List<File> files) {
  Collection<String> toShare = hotwire_classesToShare();
  return nempty(toShare)
    ? new JavaXClassLoaderWithParent2(null, files, myClassLoader(), cloneList(toShare))
    : new JavaXClassLoader(null, files);
}

static Class hotwire_finish(ClassLoader classLoader, String progID, String javaSource) {
  return hotwire_finish(classLoader, progID, javaSource, "main");
}

static Class hotwire_finish(ClassLoader classLoader, String progID, String javaSource, String mainClass) { try {
  // load & return main class
  Class<?> theClass = classLoader.loadClass(mainClass);
  
  Class j = getJavaX();
  
  setOpt(theClass, "myJavaSource_code", javaSource);
  
  synchronized(j) { // hopefully this goes well...
    call(j, "setVars", theClass, progID);
    callOpt(j, "addInstance", progID, theClass);
  }
  
  hotwire_copyOver(theClass);
  vmBus_send("hotwireFinished",theClass, mc());
  return theClass;
} catch (Exception __e) { throw rethrow(__e); } }

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

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

// returns (jar, transpiled src)
static Pair<File, String> compileSnippetThroughServer(String progID) {
  String transpiledSrc = getServerTranspiled2(progID);
  String md5 = md5(transpiledSrc + "\n" + progID);
  File jar = CompilerBot.getJarFile(md5);
  if (jar == null || jar.length() <= 22) {
    byte[] jarData = null;
    boolean dontLoad = false;
    
    
    IResourceLoader rl = vm_getResourceLoader();
    if (rl != null) {
      dontLoad = true;
      File jar2 = rl.getSnippetJar(progID, transpiledSrc);
      if (jar2 != null) return pair(jar2, transpiledSrc); 
    }
    
    if (!dontLoad) { try {
      jarData = loadBinaryPage("http://www.botcompany.de/jar/" + psI(progID) + "?md5=" + md5(transpiledSrc));
    } catch (Throwable __e) { _handleException(__e); }}
      
    if (!isJAR(jarData)) {
      if (jarData != null) {
        print(bytesToHex(takeFirstOfByteArray(8, jarData)));
        print("fallback to CompilerBot: " + fromUtf8(takeFirstOfByteArray(80, jarData)));
      }
      return CompilerBot.compileSnippet2(progID);
    }
    saveBinaryFile(jar, jarData);
  }
  return pair(jar, transpiledSrc);
}

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

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

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

static WeakReference<Object> creator_class;

static Object creator() {
  return creator_class == null ? null : creator_class.get();
}

static Comparator<String> caseInsensitiveComparator() {
  
  
  return betterCIComparator();
  
}

static TreeSet<String> caseInsensitiveSet_treeSet() {
  return new TreeSet(caseInsensitiveComparator());
}

static TreeSet<String> caseInsensitiveSet_treeSet(Collection<String> c) {
  return toCaseInsensitiveSet_treeSet(c);
}

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

static <A> CloseableIterableIterator<A> emptyCloseableIterableIterator() {
  return emptyCloseableIterableIterator_instance; 
}

static CloseableIterableIterator<String> linesFromReader(Reader r) { return linesFromReader(r, null); }
static CloseableIterableIterator<String> linesFromReader(Reader r, IResourceHolder resourceHolder) {
  final BufferedReader br = bufferedReader(r);
  return holdResource(resourceHolder, iteratorFromFunction_f0_autoCloseable(new F0<String>() { public String get() { try {  return readLineFromReaderWithClose(br);  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret readLineFromReaderWithClose(br);"; }}, _wrapIOCloseable(r)));
}

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

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


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


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


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



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

static JInternalFrame getInternalFrame(final Object _o) {
  return _o == null ? null : swing(new F0<JInternalFrame>() { public JInternalFrame get() { try { 
    Object o = _o;
    if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o));
    if (!(o instanceof Component)) return null;
    Component c = (Component) o;
    while (c != null) {
      if (c instanceof JInternalFrame) return (JInternalFrame) c;
      c = c.getParent();
    }
    return null;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "O o = _o;\r\n    if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button..."; }});
}

static <A> A optCast(Class<A> c, Object o) {
  return isInstance(c, o) ? (A) o : null;
}

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

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

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

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

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

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

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

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

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

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

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

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

static Map<Class, Constructor> nuObjectWithoutArguments_cache = newDangerousWeakHashMap();

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

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

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


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

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

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

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

  static String format(String pat, Object... args) {
    return format3(pat, args);
  }


static Map<String, Integer> findBot_cache = synchroHashMap();
static int findBot_timeout = 5000;

static DialogIO findBot(String searchPattern) {
  // first split off sub-bot suffix
  String subBot = null;
  int i = searchPattern.indexOf('/');
  if (i >= 0 && (isJavaIdentifier(searchPattern.substring(0, i)) || isInteger(searchPattern.substring(0, i)))) {
    subBot = searchPattern.substring(i+1);
    searchPattern = searchPattern.substring(0, i);
    if (!isInteger(searchPattern))
      searchPattern = "Multi-Port at " + searchPattern + ".";
  }
  
  // assume it's a port if it's an integer
  if (isInteger(searchPattern))
    return talkToSubBot(subBot, talkTo(parseInt(searchPattern)));
    
  if (eq(searchPattern, "remote"))
    return talkToSubBot(subBot, talkTo("second.tinybrain.de", 4999));
    
  Integer port = findBot_cache.get(searchPattern);
  if (port != null) try {
    DialogIO io = talkTo("localhost", port);
    io.waitForLine(/*findBot_timeout*/); // TODO: implement
    String line = io.readLineNoBlock();
    if (indexOfIgnoreCase(line, searchPattern) == 0) {
      call(io, "pushback", line); // put hello string back in
      return talkToSubBot(subBot, io);
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
  
  List<ProgramScan.Program> bots = quickBotScan();
  
  // find top-level bots
  for (ProgramScan.Program p : bots) {
    if (indexOfIgnoreCase(p.helloString, searchPattern) == 0) { // strict matching - start of hello string only, but case-insensitive
      findBot_cache.put(searchPattern, p.port);
      return talkToSubBot(subBot, talkTo("localhost", p.port));
    }
  }
  
  // find sub-bots
  for (ProgramScan.Program p : bots) {
    String botName = firstPartOfHelloString(p.helloString);
    boolean isVM = startsWithIgnoreCase(p.helloString, "This is a JavaX VM.");
    boolean shouldRecurse = startsWithIgnoreCase(botName, "Multi-Port") || isVM;
        
    if (shouldRecurse) try {
      Map<Number, String> subBots = (Map) unstructure(sendToLocalBotQuietly(p.port, "list bots"));
      for (Number vport : subBots.keySet()) {
        String name = subBots.get(vport);
        if (startsWithIgnoreCase(name, searchPattern))
          return talkToSubBot(vport.longValue(), talkTo("localhost", p.port));
      }
    } catch (Throwable __e) { print(exceptionToStringShort(__e)); }
  }
        
  return null;
}

static String quickSubstring(String s, int i, int j) {
  if (i == j) return "";
  return s.substring(i, j);
}

static Object defaultDefaultClassFinder() {
  return new F1<String, Class>() {
    public Class get(String name) {
      { Class c = findClass_fullName(name); if (c != null) return c; }
      if (name.startsWith("loadableUtils.utils$"))
        { Class c = findClass_fullName("main" + name.substring(19)); if (c != null) return c; }
      else if (name.startsWith("main$"))
        { Class c = findClass_fullName("loadableUtils.utils" + name.substring(4)); if (c != null) return c; }
      return null;
    }
  };
}

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

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


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



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

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

static <A> TreeMap<String, A> caseInsensitiveMap() {
  return new TreeMap(caseInsensitiveComparator());
}

static int shorten_default = 100;

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

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

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

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

static int parseHexChar(char c) {
  if (c >= '0' && c <= '9') return charDiff(c, '0');
  if (c >= 'a' && c <= 'f') return charDiff(c, 'a')+10;
  if (c >= 'A' && c <= 'F') return charDiff(c, 'A')+10;
  return -1;
}

static 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 String assertIsIdentifier(String s) {
  if (!isIdentifier(s))
    throw fail("Not an identifier: " + quote(s));
  return s;
}

static String assertIsIdentifier(String msg, String s) {
  if (!isIdentifier(s))
    throw fail(msg + " - Not an identifier: " + quote(s));
  return s;
}

static Class getOuterClass(Class c) {
  return getOuterClass(c, null);
}

static Class getOuterClass(Class c, Object classFinder) { try {
  String s = c.getName();
  int i = s.lastIndexOf('$');
  String name = substring(s, 0, i);
  if (classFinder != null) return (Class) callF(classFinder, name);
  return Class.forName(name);
} catch (Exception __e) { throw rethrow(__e); } }

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


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 Map<Class, Field[]> thisDollarOneFields_cache = newDangerousWeakHashMap();

static Field[] thisDollarOneFields(Class c) {
  synchronized(thisDollarOneFields_cache) {
    Field[] l = thisDollarOneFields_cache.get(c);
    if (l == null)
      thisDollarOneFields_cache.put(c, l = thisDollarOneFields_uncached(c));
    return l;
  }
}

static Field[] thisDollarOneFields_uncached(Class c) {
  List<Field> fields = new ArrayList();
  do {
    for (Field f : c.getDeclaredFields())
      if (f.getName().equals("this$1"))
        fields.add(makeAccessible(f));
    c = c.getSuperclass();
  } while (c != null);
  return toArray(new Field[l(fields)], fields);
}



static Method fastIntern_method;

static String fastIntern(String s) { try {
  if (s == null) return null;
  if (fastIntern_method == null) {
    fastIntern_method = findMethodNamed(javax(), "internPerProgram");
    if (fastIntern_method == null) upgradeJavaXAndRestart();
  }
    
  return (String) fastIntern_method.invoke(null, s);
} catch (Exception __e) { throw rethrow(__e); } }

static Map<Class, HashMap<String, Method>> callOpt_noArgs_cache = newDangerousWeakHashMap();

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

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

// used internally - we are in synchronized block
static HashMap<String, Method> callOpt_noArgs_makeCache(Class c) {
  HashMap<String, Method> map = new HashMap();
  Class _c = c;
  do {
    for (Method m : c.getDeclaredMethods())
      if (m.getParameterTypes().length == 0 
        && !reflection_isForbiddenMethod(m)) {
        makeAccessible(m);
        String name = m.getName();
        if (!map.containsKey(name))
          map.put(name, m);
      }
    _c = _c.getSuperclass();
  } while (_c != null);
  callOpt_noArgs_cache.put(c, map);
  return map;
}

// TODO: extended multi-line strings

static int javaTok_n, javaTok_elements;
static boolean javaTok_opt = false;

static List<String> javaTok(String s) {
  ++javaTok_n;
  ArrayList<String> tok = new ArrayList();
  int l = s == null ? 0 : s.length();
  
  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 && !regionMatches(s, j, "*/"));
            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));
        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)) || s.charAt(j) == '\'')); // 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 < l && !regionMatches(s, j, "]]"));
          j = Math.min(j+2, l);
        } else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
          do ++j; while (j+2 < l && !regionMatches(s, j, "]=]"));
          j = Math.min(j+3, l);
        } else
          ++j;
      
    tok.add(javaTok_substringC(s, i, j));
    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);
}

// match2 matches multiple "*" (matches a single token) wildcards and zero or one "..." wildcards (matches multiple tokens)

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

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


static <A> boolean addToCollection(Collection<A> c, A a) {
  return c != null && c.add(a);
}

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

static <A> List<A> liftLast(int n, List<A> l) {
  int i = l(l)-n;
  List<A> part = cloneSubList(l, i);
  removeSubList(l, i);
  return part;
}

static String fromUtf8(byte[] bytes) { try {
  return bytes == null ? null : new String(bytes, utf8charset());
} catch (Exception __e) { throw rethrow(__e); } }

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

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

static String snippetImageURL_noHttps(String snippetID, String contentType) {
  return snippetImageURL(snippetID, contentType)
    .replace("https://www.botcompany.de:8443/", "http://www.botcompany.de:8080/")
    .replace("https://botcompany.de/", "http://botcompany.de/");
}

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

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

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

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


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

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

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

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


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

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

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

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

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

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

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

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

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


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

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

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

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

// closes the input stream too.
static void saveStream(InputStream in, File out) { try {
  stream2file(in, out);
} catch (Exception __e) { throw rethrow(__e); } }

static List<String> hotwire_libraryIDsFromJar_deleteJarOnFail(File jar) {
  try {
    return hotwire_libraryIDsFromJar(jar);
  } catch (Throwable _e) {
    jar.delete();
  
throw rethrow(_e); }
}

static boolean loadLibraryOrSrcLib_srcLibsEnabled = true;

// to avoid checking src libs too often when booting OS
static ThreadLocal<Map<Long, File>> loadLibraryOrSrcLib_tempCache = new ThreadLocal();

static File loadLibraryOrSrcLib(String snippetID) { try {
  vmBus_send("loadLibraryOrSrcLib",snippetID);
  long id = parseSnippetID(snippetID);
  
  if (loadLibraryOrSrcLib_tempCache.get() != null)
    { File f = loadLibraryOrSrcLib_tempCache.get().get(id); if (f != null) return f; }
  
  boolean srcLib = loadLibraryOrSrcLib_srcLibsEnabled && isMarkedAsSrcLib(snippetID);
  if (srcLib) {
    File f = pairA(hotwire_compile(snippetID));
    mapPut(loadLibraryOrSrcLib_tempCache.get(), id, f);
    return f;
  }
    
  File f = DiskSnippetCache_getLibrary(id);
  if (fileSize(f) != 0) return f;
  try {
    return loadDataSnippetToFile(snippetID);
  } catch (Throwable e) {
    if (loadLibraryOrSrcLib_srcLibsEnabled && nempty(loadSnippet(snippetID))) {
      markAsSrcLib(snippetID);
      return pairA(hotwire_compile(snippetID));
    }
    throw rethrow(e);
  }
} catch (Exception __e) { throw rethrow(__e); } }

static Set<String> hotwire_classesToShare = synchroSet();

static Set<String> hotwire_classesToShare() {
  return hotwire_classesToShare;
}

static ClassLoader myClassLoader() {
  return _getClass(mc()).getClassLoader();
}

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 boolean getServerTranspiled2_allowLocalFallback = true, getServerTranspiled2_localFallbackVerbose = true;

// to avoid checking server for transpilations too often when booting OS
static Map<String, String> getServerTranspiled2_tempCache;

static String getServerTranspiled2(String id) {
  
  IResourceLoader rl = vm_getResourceLoader();
  if (rl != null)
    return rl.getTranspiled(id);
  
  
  return getServerTranspiled2_noResourceLoader(id);
}
  
static String getServerTranspiled2_noResourceLoader(String id) {
  id = fsIOpt(id);
  
  String transpiled = mapGet(getServerTranspiled2_tempCache, id);
  if (transpiled != null) return transpiled;
  //if (getServerTranspiled2_tempCache != null) print("CACHE FAIL on " + id);
  
  transpiled = loadCachedTranspilation(id);
  String md5 = null;
  if (machineIsOffline() || isOfflineMode() || isLocalSnippet(id)) return transpiled;
  if (transpiled != null)
    md5 = md5(transpiled);
  String transpiledSrc;
  try {
    transpiledSrc = getServerTranspiled(formatSnippetID(id), md5);
  } catch (Throwable e) {
    if (!getServerTranspiled2_allowLocalFallback) rethrow(e);
    printExceptionShort(e);
    if (getServerTranspiled2_localFallbackVerbose) print("Fallback to local code");
    return transpiled;
  }
  if (eq(transpiledSrc, "SAME")) {
    if (!isTrue(loadPage_silent.get())) print("SAME");
    return mapPut_returnValue(getServerTranspiled2_tempCache, id, transpiled);
  }
  return mapPut_returnValue(getServerTranspiled2_tempCache, id, transpiledSrc);
}



static String md5(String text) { try {
  if (text == null) return "-";
  return bytesToHex(md5_impl(toUtf8(text))); // 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 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 byte[] isJAR_magic = bytesFromHex("504B0304");

static boolean isJAR(byte[] data) {
  return byteArrayStartsWith(data, isJAR_magic);
}

static boolean isJAR(File f) {
  return isJAR(loadBeginningOfBinaryFile(f, l(isJAR_magic)));
}

  public static String bytesToHex(byte[] bytes) {
    return bytesToHex(bytes, 0, bytes.length);
  }

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


static byte[] takeFirstOfByteArray(byte[] b, int n) {
  return subByteArray(b, 0, n);
}

static byte[] takeFirstOfByteArray(int n, byte[] b) {
  return takeFirstOfByteArray(b, n);
}

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

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

static betterCIComparator_C betterCIComparator_instance;

static betterCIComparator_C betterCIComparator() {
  if (betterCIComparator_instance == null)
    betterCIComparator_instance = new betterCIComparator_C();
  return betterCIComparator_instance;
}

final static class betterCIComparator_C implements Comparator<String> {
  public int compare(String s1, String s2) {
    if (s1 == null) return s2 == null ? 0 : -1;
    if (s2 == null) return 1;
  
    int n1 = s1.length();
    int n2 = s2.length();
    int min = Math.min(n1, n2);
    for (int i = 0; i < min; i++) {
        char c1 = s1.charAt(i);
        char c2 = s2.charAt(i);
        if (c1 != c2) {
            c1 = Character.toUpperCase(c1);
            c2 = Character.toUpperCase(c2);
            if (c1 != c2) {
                c1 = Character.toLowerCase(c1);
                c2 = Character.toLowerCase(c2);
                if (c1 != c2) {
                    // No overflow because of numeric promotion
                    return c1 - c2;
                }
            }
        }
    }
    return n1 - n2;
  }
}

static TreeSet<String> toCaseInsensitiveSet_treeSet(Iterable<String> c) {
  if (isCISet(c)) return (TreeSet) c;
  TreeSet<String> set = caseInsensitiveSet_treeSet();
  addAll(set, c);
  return set;
}

static TreeSet<String> toCaseInsensitiveSet_treeSet(String... x) {
  TreeSet<String> set = caseInsensitiveSet_treeSet();
  addAll(set, x);
  return set;
}

static BufferedReader bufferedReader(Reader r) { return bufferedReader(r, 8192); }
static BufferedReader bufferedReader(Reader r, int bufSize) {
  return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r, bufSize), r);
}

static <A extends AutoCloseable> A holdResource(IResourceHolder holder, A a) {
  { if (holder != null) holder.add(a); }
  return a;
}

static <A> CloseableIterableIterator<A> iteratorFromFunction_f0_autoCloseable(final F0<A> f, final AutoCloseable closeable) {
  class IFF2 extends CloseableIterableIterator<A> {
    A a;
    boolean done = false;
    
    public boolean hasNext() {
      getNext();
      return !done;
    }
    
    public A next() {
      getNext();
      if (done) throw fail();
      A _a = a;
      a = null;
      return _a;
    }
    
    void getNext() {
      if (done || a != null) return;
      a = f.get();
      done = a == null;
    }
    
    public void close() throws Exception {
      if (closeable != null) closeable.close();
    }
  };
  return new IFF2();
}

static String readLineFromReaderWithClose(BufferedReader r) { try {
  String s = r.readLine();
  if (s == null) r.close();
  return s;
} catch (Exception __e) { throw rethrow(__e); } }

static AutoCloseable _wrapIOCloseable(final AutoCloseable c) {
  return c == null ? null : new AutoCloseable() { public String toString() { return "c.close();\r\n    _registerIO(c, null, false);"; } public void close() throws Exception { c.close();
    _registerIO(c, null, false);
  }};
}


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

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

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

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

static URLConnection loadPage_openConnection(URL url) {
  URLConnection con = openConnection(url);
  int timeout = toInt(loadPage_forcedTimeout_byThread.get());
  if (timeout == 0) timeout = loadPage_forcedTimeout;
  if (timeout != 0)
    setURLConnectionTimeouts(con, loadPage_forcedTimeout);
  else
    setURLConnectionDefaultTimeouts(con, loadPage_defaultTimeout);
  return con;
}

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

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

static boolean byteArrayStartsWith(byte[] a, byte[] b) {
  if (a == null || b == null) return false;
  if (a.length < b.length) return false;
  for (int i = 0; i < b.length; i++)
    if (a[i] != b[i])
      return false;
  return true;
}

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

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

  static String format3(String pat, Object... args) {
    if (args.length == 0) return pat;
    
    List<String> tok = javaTokPlusPeriod(pat);
    int argidx = 0;
    for (int i = 1; i < tok.size(); i += 2)
      if (tok.get(i).equals("*"))
        tok.set(i, format3_formatArg(argidx < args.length ? args[argidx++] : "null"));
    return join(tok);
  }
  
  static String format3_formatArg(Object arg) {
    if (arg == null) return "null";
    if (arg instanceof String) {
      String s = (String) arg;
      return isIdentifier(s) || isNonNegativeInteger(s) ? s : quote(s);
    }
    if (arg instanceof Integer || arg instanceof Long) return String.valueOf(arg);
    return quote(structure(arg));
  }
  


static DialogIO talkToSubBot(final long vport, final DialogIO io) {
  return talkToSubBot(String.valueOf(vport), io);
}

static DialogIO talkToSubBot(final String subBot, final DialogIO io) {
  if (subBot == null) return io;
  return new talkToSubBot_IO(subBot, io);
}

static class talkToSubBot_IO extends DialogIO {
  String subBot;
  DialogIO io;
  
  talkToSubBot_IO(String subBot, DialogIO io) {
  this.io = io;
  this.subBot = subBot;}
  
  // delegate all but sendLine
  boolean isStillConnected() { return io.isStillConnected(); }
  String readLineImpl() { return io.readLineImpl(); }
  boolean isLocalConnection() { return io.isLocalConnection(); }
  Socket getSocket() { return io.getSocket(); }
  public void close() { try { io.close(); } catch (Exception __e) { throw rethrow(__e); } }

  void sendLine(String line) {
    io.sendLine(format3("please forward to bot *: *", subBot, line));
  }
}

static DialogIO talkTo(int port) {
  return talkTo("localhost", port);
}

static int talkTo_defaultTimeout = 10000; // This is the CONNECT timeout
static int talkTo_timeoutForReads = 0; // Timeout waiting for answers (0 = no timeout)

static ThreadLocal<Map<String, DialogIO>> talkTo_byThread = new ThreadLocal();

static DialogIO talkTo(String ip, int port) { try {
  String full = ip + ":" + port;
  Map<String, DialogIO> map = talkTo_byThread.get();
  if (map != null && map.containsKey(full)) return map.get(full);
  
  if (isLocalhost(ip) && port == vmPort()) return talkToThisVM();

  return new talkTo_IO(ip, port);
} catch (Exception __e) { throw rethrow(__e); } }

static class talkTo_IO extends DialogIO { 
  String ip;
  int port;
  Socket s;
  Writer w;
  BufferedReader in;
  
  talkTo_IO(String ip, int port) {
  this.port = port;
  this.ip = ip; try {
    s = new Socket();
    try {
      if (talkTo_timeoutForReads != 0)
        s.setSoTimeout(talkTo_timeoutForReads);
      s.connect(new InetSocketAddress(ip, port), talkTo_defaultTimeout);
    } catch (Throwable e) {
      throw fail("Tried talking to " + ip + ":" + port, e);
    }
  
    w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
    in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
  } catch (Exception __e) { throw rethrow(__e); } }
  
  boolean isLocalConnection() {
    return s.getInetAddress().isLoopbackAddress();
  }
  
  boolean isStillConnected() {
    return !(eos || s.isClosed());
  }
  
  void sendLine(String line) { try {
    Lock __0 = lock; lock(__0); try {
    w.write(line + "\n");
    w.flush();
  } finally { unlock(__0); } } catch (Exception __e) { throw rethrow(__e); } }
  
  String readLineImpl() { try {
    return in.readLine();
  } catch (Exception __e) { throw rethrow(__e); } }
  
  public void close() {
    try {
      if (!noClose) s.close();
    } catch (IOException e) {
      // whatever
    }
  }
  
  Socket getSocket() {
    return s;
  }
}

// works on lists and strings and null

static int indexOfIgnoreCase(List<String> a, String b) {
  return indexOfIgnoreCase(a, b, 0);
}

static int indexOfIgnoreCase(List<String> a, String b, int i) {
  int n = a == null ? 0 : a.size();
  for (; i < n; i++)
    if (eqic(a.get(i), b)) return i;
  return -1;
}

static int indexOfIgnoreCase(String a, String b) {
  return indexOfIgnoreCase_manual(a, b);
  /*Matcher m = Pattern.compile(b, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher(a);
  if (m.find()) return m.start(); else ret -1;*/
}

static int indexOfIgnoreCase(String a, String b, int i) {
  return indexOfIgnoreCase_manual(a, b, i);
}

static List<ProgramScan.Program> quickBotScan() {
  return ProgramScan.quickBotScan();
}

static List<ProgramScan.Program> quickBotScan(int[] preferredPorts) {
  return ProgramScan.quickBotScan(preferredPorts);
}

static List<ProgramScan.Program> quickBotScan(String searchPattern) {
  List<ProgramScan.Program> l = new ArrayList<ProgramScan.Program>();
  for (ProgramScan.Program p : ProgramScan.quickBotScan())
    if (indexOfIgnoreCase(p.helloString, searchPattern) == 0)
      l.add(p);
  return l;
}


static String firstPartOfHelloString(String s) {
  int i = s.lastIndexOf('/');
  return i < 0 ? s : rtrim(s.substring(0, i));
}

static String sendToLocalBotQuietly(String bot, String text, Object... args) {
  text = format3(text, args);
  
   DialogIO channel = newFindBot2(bot); try {
  if (channel == null)
    throw fail(quote(bot) + " not found");
  try {
    channel.readLine();
    channel.sendLine(text);
    String s = channel.readLine();
    return s;
  } catch (Throwable e) {
    e.printStackTrace();
    return null;
  }
} finally { _close(channel); }}

static String sendToLocalBotQuietly(int port, String text, Object... args) {
  text = format3(text, args);
   DialogIO channel = talkTo(port); try {
  try {
    channel.readLine();
    channel.sendLine(text);
    String s = channel.readLine();
    return s;
  } catch (Throwable e) {
    e.printStackTrace();
    return null;
  }
} finally { _close(channel); }}

static char lastChar(String s) {
  return empty(s) ? '\0' : s.charAt(l(s)-1);
}

static <A> A[] dropLast(A[] a) { return dropLast(a, 1); }
static <A> A[] dropLast(A[] a, int n) {
  if (a == null) return null;
  n = Math.min(n, a.length);
  A[] b = arrayOfSameType(a, a.length-n);
  System.arraycopy(a, 0, b, 0, b.length);
  return b;
}

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

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

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

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

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

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


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

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

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

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

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

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

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

static String prependIfNempty(String prefix, String s) {
  return empty(s) ? unnull(s) : prefix + s;
}

static Object[] toArray(Collection c) {
  return toObjectArray(c);
}

static <A> A[] toArray(Iterable<A> c, Class<A> type) {
  A[] a = arrayOfType(l(c), type);
  if (a.length == 0) return a;
  asList(c).toArray(a);
  return a;
}

// array must have correct length and will be filled
static <A> A[] toArray(A[] array, Collection c) {
  if (array == null || c == null) return null;
  asList(c).toArray(array);
  return array;
}

// This is a bit rough... finds static and non-static methods.

static Method findMethodNamed(Object obj, String method) {
  if (obj == null) return null;
  if (obj instanceof Class)
    return findMethodNamed((Class) obj, method);
  return findMethodNamed(obj.getClass(), method);
}

static Method findMethodNamed(Class c, String method) {
  while (c != null) {
    for (Method m : c.getDeclaredMethods())
      if (m.getName().equals(method)) {
        makeAccessible(m);
        return m;
      }
    c = c.getSuperclass();
  }
  return null;
}

static void upgradeJavaXAndRestart() {
  
    run("#1001639");
    restart();
    sleep();
  
  
}

static boolean reflection_isForbiddenMethod(Method m) {
  return m.getDeclaringClass() == Object.class
    && eqOneOf(m.getName(), "finalize", "clone", "registerNatives");
}

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

static boolean regionMatches(String a, int offsetA, String b) {
  return regionMatches(a, offsetA, b, 0, l(b));
}

static String javaTok_substringN(String s, int i, int j) {
  if (i == j) return "";
  if (j == i+1 && s.charAt(i) == ' ') return " ";
  return s.substring(i, j);
}

static String javaTok_substringC(String s, int i, int j) {
  return s.substring(i, j);
}

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

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

static boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
  return t.length() == j-i
    && s.regionMatches(i, t, 0, j-i); // << could be left out, but that's brave
}

static boolean equalsIgnoreCase(String a, String b) {
  return eqic(a, b);
}

static boolean equalsIgnoreCase(char a, char b) {
  return eqic(a, b);
}

static <A> List<A> cloneSubList(List<A> l, int startIndex, int endIndex) {
  return newSubList(l, startIndex, endIndex);
}

static <A> List<A> cloneSubList(List<A> l, int startIndex) {
  return newSubList(l, startIndex);
}

static void removeSubList(List l, int from, int to) {
  if (l != null) subList(l, from, to).clear();
}

static void removeSubList(List l, int from) {
  if (l != null) subList(l, from).clear();
}



static Charset utf8charset_cache;
static Charset utf8charset() { if (utf8charset_cache == null) utf8charset_cache = utf8charset_load(); return utf8charset_cache; }

static Charset utf8charset_load() {
  return Charset.forName("UTF-8");
}

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

static void setHeaders(URLConnection con) throws IOException {
  
  String computerID = getComputerID_quick();
  if (computerID != null) try {
    con.setRequestProperty("X-ComputerID", computerID);
    con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version"));
  } catch (Throwable e) {
    //printShortException(e);
  }
  
}

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

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

static volatile boolean muricaPassword_pretendNotAuthed = false;

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

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

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

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

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

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

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

static String loadTextFile(Reader reader) throws IOException {
  StringBuilder builder = new StringBuilder();
  try {
    char[] buffer = new char[1024];
    int n;
    while (-1 != (n = reader.read(buffer)))
      builder.append(buffer, 0, n);
  } finally {
    reader.close();
  }
  return str(builder);
}

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

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


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


static void copyStreamWithPrints(InputStream in, OutputStream out, String pat) { try {
  byte[] buf = new byte[65536];
  int total = 0;
  while (true) {
    int n = in.read(buf);
    if (n <= 0) return;
    out.write(buf, 0, n);
    if ((total+n)/100000 > total/100000)
      print(pat.replace("{*}", str(roundDownTo(100000, total))));
    total += n;
  }
} catch (Exception __e) { throw rethrow(__e); } }

static 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 List<String> hotwire_libraryIDsFromJar(File jar) {
  String dehlibs = unnull(loadTextFileFromZip(jar, "libraries"));
  return regexpExtractAll("\\d+", dehlibs);
}

static boolean isMarkedAsSrcLib(String snippetID) {
  if (snippetID == null) return false;
  
  
  IResourceLoader rl = vm_getResourceLoader();
  if (rl != null)
    return isJavaxCompilableSnippetType(rl.getSnippetType(snippetID));
  
  
  return fileExists(javaxCodeDir("srclibs/" + psI(snippetID)));
}

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

static boolean preferCached = false;
static boolean loadSnippet_debug = false;
static ThreadLocal<Boolean> loadSnippet_silent = new ThreadLocal();
static ThreadLocal<Boolean> loadSnippet_publicOnly = new ThreadLocal();
static int loadSnippet_timeout = 30000;



static String loadSnippet(String snippetID) { try {
  if (snippetID == null) return null;
  return loadSnippet(parseSnippetID(snippetID), preferCached);
} catch (Exception __e) { throw rethrow(__e); } }

static String loadSnippet(String snippetID, boolean preferCached) throws IOException {
  return loadSnippet(parseSnippetID(snippetID), preferCached);
}

static  IF1<Long, String> loadSnippet;
static String loadSnippet(long snippetID) { return loadSnippet != null ? loadSnippet.get(snippetID) : loadSnippet_base(snippetID); }
final static String loadSnippet_fallback(IF1<Long, String> _f, long snippetID) { return _f != null ? _f.get(snippetID) : loadSnippet_base(snippetID); }
static String loadSnippet_base(long snippetID) { try {
  return loadSnippet(snippetID, preferCached);
} catch (Exception __e) { throw rethrow(__e); } }

static String loadSnippet(long snippetID, boolean preferCached) throws IOException {
  if (isLocalSnippetID(snippetID))
    return loadLocalSnippet(snippetID);
    
  
  IResourceLoader rl = vm_getResourceLoader();
  if (rl != null)
    return rl.loadSnippet(fsI(snippetID));
  
  
  return loadSnippet_noResourceLoader(snippetID, preferCached);
}

static String loadSnippet_noResourceLoader(long snippetID, boolean preferCached) throws IOException {
  String text;
  
  // boss bot (old concept)
  /*text = getSnippetFromBossBot(snippetID);
  if (text != null) return text;*/
  
  initSnippetCache();
  text = DiskSnippetCache_get(snippetID);
  
  if (preferCached && text != null)
    return text;
  
  try {
    if (loadSnippet_debug && text != null) System.err.println("md5: " + md5(text));
    String url = tb_mainServer() + "/getraw.php?id=" + snippetID + "&utf8=1";
    if (nempty(text)) url += "&md5=" + md5(text);
    if (!isTrue(loadSnippet_publicOnly.get()))
      url += standardCredentials();
    
    String text2 = loadSnippet_loadFromServer(url);
    
    boolean same = eq(text2, "==*#*==");
    if (loadSnippet_debug) print("loadSnippet: same=" + same);
    if (!same) text = text2;
  } catch (RuntimeException e) {
    e.printStackTrace();
    throw new IOException("Snippet #" + snippetID + " not found or not public");
  }

  try {
    initSnippetCache();
    DiskSnippetCache_put(snippetID, text);
  } catch (IOException e) {
    System.err.println("Minor warning: Couldn't save snippet to cache ("  + DiskSnippetCache_getDir() + ")");
  }

  return text;
}

static File DiskSnippetCache_dir;

public static void initDiskSnippetCache(File dir) {
  DiskSnippetCache_dir = dir;
  dir.mkdirs();
}

public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException {
  return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null);
}

private static File DiskSnippetCache_getFile(long snippetID) {
  return new File(DiskSnippetCache_dir, "" + snippetID);
}

public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException {
  saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet);
}

public static File DiskSnippetCache_getDir() {
  return DiskSnippetCache_dir;
}

public static void initSnippetCache() {
  if (DiskSnippetCache_dir == null)
    initDiskSnippetCache(getGlobalCache());
}

static String loadSnippet_loadFromServer(String url) {
  Integer oldTimeout = setThreadLocal(loadPage_forcedTimeout_byThread, loadSnippet_timeout);
  try {
    return isTrue(loadSnippet_silent.get()) ? loadPageSilently(url) : loadPage(url);
  } finally {
    loadPage_forcedTimeout_byThread.set(oldTimeout);
  }
}


static void markAsSrcLib(String snippetID) {
  saveTextFile(javaxCodeDir("srclibs/" + psI(snippetID)), "");
}

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

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

static void setOptIfNotNull(Object o, String field, Object value) {
  if (value != null) setOpt(o, field, value);
}

static Object mainBot;

static Object getMainBot() {
  return mainBot;
}

static String loadCachedTranspilation(String id) { try {
  return loadTextFilePossiblyGZipped(getCachedTranspilationFile(id));
} catch (Throwable __e) { return null; } }


static boolean machineIsOffline() {
  return isFalse(callF(vmGeneralMap_get("areWeOnline")));
}

static boolean isOfflineMode() {
  return eq("1", trim(loadProgramTextFile("#1005806", "offline-mode")));
}

static boolean isLocalSnippet(String snippetID) {
  return isLocalSnippetID(snippetID);
}



static boolean isLocalSnippet(long snippetID) {
  return isLocalSnippetID(snippetID);
}

static String getServerTranspiled(String snippetID) {
  return getServerTranspiled(snippetID, null);
}

static boolean getServerTranspiled_printStackTrace = false;

// returns "SAME" if md5 matches
static String getServerTranspiled(String snippetID, String expectedMD5) { try {
  if (getServerTranspiled_printStackTrace) printStackTrace();
  long id = parseSnippetID(snippetID);
  /*S t = getTranspilationFromBossBot(id);
  if (t != null) return t;*/
  
  String text = loadPage_utf8(tb_mainServer() + "/tb-int/get-transpiled.php?raw=1&withlibs=1&id=" + id + "&utf8=1"
    + (l(expectedMD5) > 1 ? "&md5=" + urlencode(expectedMD5) : "")
    + standardCredentials());
  if (nempty(text) && neq(text, "SAME"))
    saveTranspiledCode(snippetID, text);
  return text;
} catch (Exception __e) { throw rethrow(__e); } }

static void printExceptionShort(Throwable e) { printExceptionShort("", e); }
static void printExceptionShort(String prefix, Throwable e) {
  print(prefix, exceptionToStringShort(e));
}

static <A, B> B mapPut_returnValue(Map<A, B> map, A key, B value) {
  mapPut(map, key, value);
  return value;
}

static byte[] toUtf8(String s) { try {
  return s.getBytes(utf8charset());
} catch (Exception __e) { throw rethrow(__e); } }

static boolean md5OfFile_verbose = false;

static String md5OfFile(String path) {
  return md5OfFile(newFile(path));
}

static String md5OfFile(File f) { try {
  if (!f.exists()) return "-";
  
  if (md5OfFile_verbose)
    print("Getting MD5 of " + f);
  
  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 byte[] subByteArray(byte[] b, int start) {
  return subByteArray(b, start, l(b));
}
  
static byte[] subByteArray(byte[] b, int start, int end) {
  start = max(start, 0); end = min(end, l(b));
  if (start == 0 && end == l(b)) return b;
  if (start >= end) return new byte[0];
  byte[] x = new byte[end-start];
  System.arraycopy(b, start, x, 0, end-start);
  return x;
}

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



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 <A> A printWithTime(A a) {
  return printWithTime("", a);
}

static <A> A printWithTime(String s, A a) {
  print(hmsWithColons() + ": " + s, a);
  return a;
}

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


static InputStream urlConnection_getInputStream(URLConnection con) throws IOException {
  UnknownHostException lastException = null;
  for (int _repeat_0 = 0; _repeat_0 < 2; _repeat_0++)  {
    try {
      if (con instanceof HttpURLConnection)
        if (((HttpURLConnection) con).getResponseCode() == 500)
          throw new IOException(joinNemptiesWithColonSpace("Server code 500", tryToReadErrorStreamFromURLConnection(((HttpURLConnection) con))));
      return con.getInputStream();
    } catch (UnknownHostException e) {
      lastException = e;
      print("Retrying because of: " + e);
      continue;
    }
  }
  throw lastException;
}

static String toHex(byte[] bytes) {
  return bytesToHex(bytes);
}

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


static byte[] utf8(String s) {
  return toUtf8(s);
}

static Matcher regexpMatcher(String pat, String s) {
  return compileRegexp(pat).matcher(unnull(s));
}

static URLConnection setURLConnectionTimeouts(URLConnection con, long timeout) {
  con.setConnectTimeout(toInt(timeout));
  con.setReadTimeout(toInt(timeout));
  if (con.getConnectTimeout() != timeout || con.getReadTimeout() != timeout)
    print("Warning: Timeouts not set by JDK.");
  return con;
}

static URLConnection setURLConnectionDefaultTimeouts(URLConnection con, long timeout) {
  if (con.getConnectTimeout() == 0) {
    con.setConnectTimeout(toInt(timeout));
    if (con.getConnectTimeout() != timeout)
      print("Warning: URL connect timeout not set by JDK.");
  }
  if (con.getReadTimeout() == 0) {
    con.setReadTimeout(toInt(timeout));
    if (con.getReadTimeout() != timeout)
      print("Warning: URL read timeout not set by JDK.");
  }
  return con;
}

static 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 boolean isMD5(String s) {
  return l(s) == 32 && isLowerHexString(s);
}

// This is made for NL parsing.
// It's javaTok extended with "..." token, "$n" and "#n" and
// special quotes (which are converted to normal ones).

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

    // scan for non-whitespace
    if (c == (char) 0x201C || c == (char) 0x201D) c = '"'; // normalize quotes
    if (c == '\'' || c == '"') {
      char opener = c;
      ++j;
      while (j < l) {
        char _c = s.charAt(j);
        if (_c == (char) 0x201C || _c == (char) 0x201D) _c = '"'; // normalize quotes
        if (_c == opener) {
          ++j;
          break;
        } else if (s.charAt(j) == '\\' && j+1 < l)
          j += 2;
        else
          ++j;
      }
      if (j-1 >= i+1) {
        tok.add(opener + s.substring(i+1, j-1) + opener);
        i = j;
        continue;
      }
    } else if (Character.isJavaIdentifierStart(c))
      do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\'')); // for things like "this one's"
    else if (Character.isDigit(c))
      do ++j; while (j < l && Character.isDigit(s.charAt(j)));
    else if (cc.equals("[[")) {
      do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
      j = Math.min(j+2, l);
    } else if (cc.equals("[=") && 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 if (s.substring(j, Math.min(j+3, l)).equals("..."))
      j += 3;
    else if (c == '$' || c == '#')
      do ++j; while (j < l && Character.isDigit(s.charAt(j)));
    else
      ++j;

    tok.add(s.substring(i, j));
    i = j;
  }
  
  if ((tok.size() % 2) == 0) tok.add("");
  return tok;
}


static boolean isNonNegativeInteger(String s) {
  int n = l(s);
  if (n == 0) return false;
  int i = 0;
  while (i < n) {
    char c = s.charAt(i);
    if (c < '0' || c > '9') return false;
    ++i;
  }
  return true;
}

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) { structureToPrintWriter(o, out, new structure_Data()); }
static void structureToPrintWriter(Object o, PrintWriter out, structure_Data d) {
  d.out = out;
  structure_go(o, d);
}

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

// info on how to serialize objects of a certain class
static class structure_ClassInfo {
  Class c;
  List<Field> fields;
  Method customSerializer;
  IVF1<Object> serializeObject; // can be set by caller of structure function
  boolean special, nullInstances;
}

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

  IdentityHashMap<Object, Integer> seen = new IdentityHashMap();
  //new BitSet refd;
  HashMap<String, Integer> strings = new HashMap();
  HashSet<String> concepts = new HashSet();
  HashMap<Class, structure_ClassInfo> infoByClass = 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; }
  
  // called when a new class is detected
  // can be overridden by clients
  structure_ClassInfo newClass(Class c) {
    structure_ClassInfo info = new structure_ClassInfo();
    info.c = c;
    infoByClass.put(c, info);
    if ((info.customSerializer = findMethodNamed(c, "_serialize"))
      != null) info.special = true;
      
    if (storeBaseClasses) {
      Class sup = c.getSuperclass();
      if (sup != Object.class) {
        append("bc ");
        append(shortClassName(c));
        out.print(" ");
        append(shortClassName(sup));
        out.print(" ");
      }
    }
    
    return info;
  }
  
  void setFields(structure_ClassInfo info, List<Field> fields) { 
    info.fields = fields;
  }
}

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;
  
  structure_ClassInfo info = d.infoByClass.get(c);
  if (info == null)
    info = d.newClass(c);

  List<Field> lFields = info.fields;
  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 "); 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 Set) {
      /*O set2 = unwrapSynchronizedSet(o);
      if (set2 != o) {
        d.append("sync");
        o = set2;
      } TODO */
      
      if (((Set) o) instanceof TreeSet) {
        d.append(isCISet_gen(((Set) o)) ? "ciset" : "treeset");
        structure_1(new ArrayList(((Set) o)), d);
        return;
      }
      
      // assume it's a HashSet or LinkedHashSet
      d.append(((Set) o) instanceof LinkedHashSet ? "lhs" : "hashset");
      structure_1(new ArrayList(((Set) o)), d);
      return;
    }
    
    String name = c.getName();
    
    if (o instanceof Collection
      && !isJavaXClassName(name)
      /* && neq(name, "main$Concept$RefL") */) {
      
      // it's a list
    
      if (name.equals("java.util.Collections$SynchronizedList")
        || name.equals("java.util.Collections$SynchronizedRandomAccessList")) {
        d.append("sync ");
        { structure_1(unwrapSynchronizedList(((List) o)), d); return; }
      }
      else if (name.equals("java.util.LinkedList")) d.append("ll");
      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 (o instanceof TreeMap)
        d.append(isCIMap_gen(((TreeMap) o)) ? "cimap" : "tm");
      else if (name.equals("java.util.Collections$SynchronizedMap")
        || name.equals("java.util.Collections$SynchronizedSortedMap")
        || name.equals("java.util.Collections$SynchronizedNavigableMap")) {
        d.append("sync "); 
        { structure_1(unwrapSynchronizedMap(((Map) o)), d); return; }
      }
      
      d.append("{");
      final int l = d.n;
      final Iterator it = ((Map) o).entrySet().iterator();
      
      d.stack.add(new Runnable() {
        boolean v = false;
        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 = ", "*/; // sep is not used yet
  
      if (o instanceof int[]) {
        //ret "intarray " + quote(intArrayToHex((int[]) o));
        atype = "intarray";
        //sep = " ";
      } else if (o instanceof double[]) {
        atype = "dblarray";
        //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");
    }*/
    
    if (info.special) {
      if (info.customSerializer != null) {
        // custom serialization (_serialize method)
        Object o2 = invokeMethod(info.customSerializer, o);
        d.append("cu ");
        String shortName = dropPrefix("main$", name);
        d.append(shortName);
        d.out.append(' ');
        structure_1(o2, d);
        return;
      } else if (info.nullInstances) { d.append("null"); return; }
      else if (info.serializeObject != null)
        { info.serializeObject.get(o); return; }
      else throw fail("unknown special type");
    }
    
    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();
    }
    
    // TODO: S fieldOrder = getOpt(c, "_fieldOrder");
    lFields = asList(fields);
    
    // Render this$1 first because unstructure needs it for constructor call.
    
    int n = l(lFields);
    for (int i = 0; i < n; i++) {
      Field f = lFields.get(i);
      if (f.getName().equals("this$1")) {
        lFields.remove(i);
        lFields.add(0, f);
        break;
      }
    }
  
    
    d.setFields(info, 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); // TODO: drop loadableUtils also
  if (startsWithDigit(shortName)) shortName = name; // for anonymous classes
    
  // 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) {
    putAll(fv, (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);
  d.n += countDots(shortName)*2; // correct token count
  
  
  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 boolean isLocalhost(String ip) {
  return isLoopbackIP(ip) || eqic(ip, "localhost");
}

static int vmPort() {
  return myVMPort();
}

static DialogIO talkToThisVM() {
  return new talkToThisVM_IO();
}

static class talkToThisVM_IO extends DialogIO { 
  List<String> answers = ll(thisVMGreeting());
  
  boolean isLocalConnection() { return true; }
  boolean isStillConnected() { return true; }
  int getPort() { return vmPort(); }
  
  void sendLine(String line) {
    answers.add(or2(sendToThisVM_newThread(line), "?"));
  }
  
  String readLineImpl() { try {
    return popFirst(answers);
  } catch (Exception __e) { throw rethrow(__e); } }
  
  public void close() {}
  Socket getSocket() { return null; }
}

static int indexOfIgnoreCase_manual(String a, String b) {
  return indexOfIgnoreCase_manual(a, b, 0);
}

static int indexOfIgnoreCase_manual(String a, String b, int i) {
  int la = strL(a), lb = strL(b);
  if (la < lb) return -1;
  int n = la-lb;
  
  loop: for (; i <= n; i++) {
    for (int j = 0; j < lb; j++) {
      char c1 = a.charAt(i+j), c2 = b.charAt(j);
      if (!eqic(c1, c2))
        continue loop;
    }
    return i;
  }
  return -1;
}

public static String rtrim(String s) {
  if (s == null) return null;
  int i = s.length();
  while (i > 0 && " \t\r\n".indexOf(s.charAt(i-1)) >= 0)
    --i;
  return i < s.length() ? s.substring(0, i) : s;
}

static Map<String, Integer> newFindBot2_cache = synchroHashMap();
static boolean newFindBot2_verbose = false;

static DialogIO newFindBot2(String name) {
  Integer port = newFindBot2_cache.get(name);
  if (port != null) {
    if (newFindBot2_verbose)
      print("newFindBot2: testing " + name + " => " + port);
    DialogIO io = talkTo(port);
    String q = format("has bot *", name);
    String s = io.ask(q);
    if (match("yes", s)) {
      io = talkToSubBot(name, io);
      call(io, "pushback", "?"); // put some hello string in (yes, this should be improved.)
      return io;
    }
    // bot not there anymore - remove cache entry
    newFindBot2_cache.remove(name);
    if (newFindBot2_verbose)
      print("newFindBot2: dropping " + name + " => " + port);
  }
  
  DialogIO io = findBot(name);
  if (io != null) {
    newFindBot2_cache.put(name, io.getPort());
    if (newFindBot2_verbose)
      print("newFindBot2: remembering " + name + " => " + port);
  }
  return io;
}

static <A> A[] arrayOfSameType(A[] a, int n) {
  return newObjectArrayOfSameType(a, n);
}

static char stringToChar(String s) {
  if (l(s) != 1) throw fail("bad stringToChar: " + s);
  return firstChar(s);
}

static Class run(String progID, String... args) {
  Class main = hotwire(progID);
  callMain(main, args);
  return main;
}

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

static volatile boolean sleep_noSleep = false;

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

static void sleep() { try {
  if (sleep_noSleep) throw fail("nosleep");
  print("Sleeping.");
  sleepQuietly();
} catch (Exception __e) { throw rethrow(__e); } }

static <A> List<A> newSubList(List<A> l, int startIndex, int endIndex) {
  return cloneList(subList(l, startIndex, endIndex));
}

static <A> List<A> newSubList(List<A> l, int startIndex) {
  return cloneList(subList(l, startIndex));
}

static String getComputerID_quick() {
  return computerID();
}

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

static ThreadLocal<VF1<File>> checkFileNotTooBigToRead_tl = new ThreadLocal();

static void checkFileNotTooBigToRead(File f) {
  callF(checkFileNotTooBigToRead_tl.get(), f);
}

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

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

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

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

static List<String> regexpExtractAll(String pat, String s) {
  if (s == null) return null;
  Matcher m = regexpMatcher(pat, s);
  List<String> out = new ArrayList();
  while (m.find())
    out.add(m.group());
  return out;
}

static boolean isJavaxCompilableSnippetType(int type) {
  return isJavaxCompilableSnippetTypeExceptInclude(type)
    || type == javaxIncludeSnippetType();
}

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 File javaxCodeDir(String sub) {
  return newFile(javaxCodeDir(), sub);
}

static String loadLocalSnippet(String snippetID) {
  return loadLocalSnippet(psI(snippetID));
}

static String loadLocalSnippet(long snippetID) {
  return loadTextFile(localSnippetFile(snippetID));
}

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

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 getCachedTranspilationFile(String id) {
  return newFile(getCodeProgramDir(id), "Transpilation");
}


static Object vmGeneralMap_get(Object key) {
  return vm_generalMap_get(key);
}

static String loadProgramTextFile(String name) {
  return loadTextFile(getProgramFile(name));
}

static String loadProgramTextFile(String progID, String name) {
  return loadTextFile(getProgramFile(progID, name));
}

static String loadProgramTextFile(String progID, String name, String defaultText) {
  return loadTextFile(getProgramFile(progID, name), defaultText);
}

static String loadPage_utf8(URL url) {
  return loadPage_utf8(url.toString());
}

static String loadPage_utf8(String url) {
   AutoCloseable __1 = tempSetTL(loadPage_charset, "UTF-8"); try {
  return loadPage(url);
} finally { _close(__1); }}

static String loadPage_utf8(URLConnection con, URL url, boolean addHeaders) throws IOException {
   AutoCloseable __2 = tempSetTL(loadPage_charset, "UTF-8"); try {
  return loadPage(con, url, addHeaders);
} finally { _close(__2); }}

static String urlencode(String x) {
  try {
    return URLEncoder.encode(unnull(x), "UTF-8");
  } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); }
}

static void saveTranspiledCode(String progID, String code) {
  File dir = getCodeProgramDir(progID);
  new File(dir, "Transpilation").delete();
  saveGZTextFile(new File(dir, "Transpilation.gz"), code);
}



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 String round(String s) {
  return roundBracket(s);
}



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

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


static String joinNemptiesWithColonSpace(String... strings) {
  return joinNempties(": ", strings);
}

static String joinNemptiesWithColonSpace(Collection<String> strings) {
  return joinNempties(": ", strings);
}

static String tryToReadErrorStreamFromURLConnection(URLConnection conn) { try {
  if (conn instanceof HttpURLConnection)
    return stream2string(((HttpURLConnection) conn).getErrorStream()); // TODO: ensure some max length
  return null;
} catch (Throwable __e) { return null; } }

static 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 <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 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 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 boolean isCISet_gen(Iterable<String> l) {
  return l instanceof TreeSet && className(((TreeSet) l).comparator()).contains("CIComp");
}

static boolean isJavaXClassName(String s) {
  return startsWithOneOf(s, "main$", "loadableUtils.");
}

static <A> List<A> unwrapSynchronizedList(List<A> l) {
  
  if (eqOneOf(className(l),
    "java.util.Collections$SynchronizedList",
    "java.util.Collections$SynchronizedRandomAccessList"))
    return (List) get_raw(l, "list");
  return l;
}

static boolean isCIMap_gen(Map map) {
  return map instanceof TreeMap && className(((TreeMap) map).comparator()).contains("CIComp");
}

static <A, B> Map<A, B> unwrapSynchronizedMap(Map<A, B> map) {
  if (eqOneOf(className(map),
    "java.util.Collections$SynchronizedMap",
    "java.util.Collections$SynchronizedSortedMap",
    "java.util.Collections$SynchronizedNavigableMap"))
    return (Map) get_raw(map, "m");
  return map;
}

static String boolArrayToHex(boolean[] a) {
  return bytesToHex(boolArrayToBytes(a));
}

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)
        makeAccessible(f);
    }
  }
  return fields;
}

static boolean startsWithDigit(String s) {
  return nempty(s) && isDigit(s.charAt(0));
}

static <A, B> Map<A, B> putAll(Map<A, B> a, Map<? extends A,? extends B> b) {
  if (a != null && b != null) a.putAll(b);
  return a;
}



static <A, B> Map<A, B> putAll(Map<A, B> a, Object... b) {
  if (a != null)
    litmap_impl(a, b);
  return a;
}


static int countDots(String s) {
  int n = l(s), count = 0;
  for (int i = 0; i < n; i++) if (s.charAt(i) == '.') ++count;
  return count;
}

static boolean isLoopbackIP(String ip) {
  return eq(ip, "127.0.0.1");
}

static int myVMPort() {
  List records =  (List) (get(getJavaX(), "record_list"));
  Object android = last(records);
  return or0((Integer) get(android, "port"));
}

static String thisVMGreeting() {
  List record_list =  (List) (get(getJavaX(), "record_list"));
  Object android = first(record_list); // Should be of class Android3
  return getString(android, "greeting");
}

static String sendToThisVM_newThread(String s, Object... args) {
  final String _s = format(s, args);
  try {
    return (String) evalInNewThread(new F0<Object>() { public Object get() { try { 
      return callStaticAnswerMethod(getJavaX(), _s);
     } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret callStaticAnswerMethod(getJavaX(), _s);"; }});
  } catch (Throwable e) {
    e = getInnerException(e);
    printStackTrace(e);
    return str(e);
  }
}

static <A> A popFirst(List<A> l) {
  if (empty(l)) return null;
  A a = first(l);
  l.remove(0);
  return a;
}

static <A> A popFirst(Collection<A> l) {
  if (empty(l)) return null;
  A a = first(l);
  l.remove(a);
  return a;
}

static <A> List<A> popFirst(int n, List<A> l) {
  List<A> part = cloneSubList(l, 0, n);
  removeSubList(l, 0, n);
  return part;
}

static boolean match(String pat, String s) {
  return match3(pat, s);
}

static boolean match(String pat, String s, Matches matches) {
  return match3(pat, s, matches);
}

static boolean match(String pat, List<String> toks, Matches matches) {
  return match3(pat, toks, matches);
}

static <A> A[] newObjectArrayOfSameType(A[] a) { return newObjectArrayOfSameType(a, a.length); }
static <A> A[] newObjectArrayOfSameType(A[] a, int n) {
  return (A[]) Array.newInstance(a.getClass().getComponentType(), n);
}

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

static Object sleepQuietly_monitor = new Object();

static void sleepQuietly() { try {
  assertFalse(isAWTThread());
  synchronized(sleepQuietly_monitor) { sleepQuietly_monitor.wait(); }
} catch (Exception __e) { throw rethrow(__e); } }

static String _computerID;
static Lock computerID_lock = lock();

public static String computerID() {
  if (_computerID == null) {
    Lock __0 = computerID_lock; lock(__0); try {
    if (_computerID != null) return _computerID;
    File file = computerIDFile();
    _computerID = loadTextFile(file.getPath());
    if (_computerID == null) {
      // legacy load
      _computerID = loadTextFile(userDir(".tinybrain/computer-id"));
      if (_computerID == null)
        _computerID = makeRandomID(12, new SecureRandom());
      saveTextFile(file, _computerID);
    }
  } finally { unlock(__0); } }
  return _computerID;
}

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

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

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

static File programDir_mine; // set this to relocate program's data

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

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

static File programDir(String snippetID, String subPath) {
  return new File(programDir(snippetID), subPath);
}

static boolean isJavaxCompilableSnippetTypeExceptInclude(int type) {
  return isJavaxApplicationSnippetType(type)
    || isJavaxModuleSnippetType(type)
    || type == snippetType_dynModule();
}

static int javaxIncludeSnippetType() {
  return 42;
}

static File localSnippetFile(long snippetID) {
  return localSnippetsDir(snippetID + ".text");
}

static File localSnippetFile(String snippetID) {
  return localSnippetFile(parseSnippetID(snippetID));
}

static String standardCredentialsUser() {
  return trim(loadTextFile(
    oneOfTheFiles(
      javaxSecretDir("tinybrain-username"),
      userDir(".tinybrain/username"))));
}

static String standardCredentialsPass() {
  return trim(loadTextFile(
    oneOfTheFiles(
      javaxSecretDir("tinybrain-userpass"),
      userDir(".tinybrain/userpass"))));
}

static String loadGZTextFile(File file) { try {
  if (!file.isFile()) return null;
  ping();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
   InputStream fis = new FileInputStream(file); try {
  GZIPInputStream gis = newGZIPInputStream(fis);
  byte[] buffer = new byte[1024];
  int len;
  while ((len = gis.read(buffer)) != -1) baos.write(buffer, 0, len);
  baos.close();
  return fromUtf8(baos.toByteArray()); // TODO: use a Reader
} finally { _close(fis); }} catch (Exception __e) { throw rethrow(__e); } }

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 <A> AutoCloseable tempSetTL(ThreadLocal<A> tl, A a) {
  return tempSetThreadLocal(tl, a);
}

static void saveGZTextFile(File file, String contents) { saveGZTextFile(file, contents, "UTF-8"); }
static void saveGZTextFile(File file, String contents, String encoding) { try {
  File parentFile = file.getParentFile();
  if (parentFile != null)
    parentFile.mkdirs();
  String tempFileName = file.getPath() + "_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());
    GZIPOutputStream gos = new GZIPOutputStream(fileOutputStream);
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(gos, encoding);
    PrintWriter printWriter = new PrintWriter(outputStreamWriter);
    printWriter.print(contents);
    printWriter.close();
    gos.close();
    fileOutputStream.close();
  }
  
  if (file.exists() && !file.delete())
    throw new IOException("Can't delete " + file.getPath());

  if (contents != null)
    if (!tempFile.renameTo(file))
      throw new IOException("Can't rename " + tempFile + " to " + file);
} catch (Exception __e) { throw rethrow(__e); } }



static String roundBracket(String s) {
  return "(" + s + ")";
}

static String joinNempties(String sep, Object... strings) {
  return joinStrings(sep, strings);
}

static String joinNempties(String sep, Iterable strings) {
  return joinStrings(sep, strings);
}

static String stream2string(InputStream in) {
  return utf8streamToString(in);
}

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

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

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



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 byte[] boolArrayToBytes(boolean[] a) {
  byte[] b = new byte[(l(a)+7)/8];
  for (int i = 0; i < l(a); i++)
    if (a[i])
      b[i/8] |= 1 << (i & 7);
  return b;
}

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

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

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

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

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

static boolean isDigit(char c) {
  return Character.isDigit(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 double last(double[] 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 <A> A last(Collection<A> l) {
  if (l == null) return null;
  if (l instanceof List) return (A) last(((List) l));
  if (l instanceof SortedSet) return (A) last(((SortedSet) l));
  Iterator<A> it = iterator(l);
  A a = null;
  while  (it.hasNext()) { ping(); a = it.next(); }
  return a;
}

static <A> A last(SortedSet<A> l) {
  return l == null ? null : l.last();
}







static String getString(Map map, Object key) {
  return map == null ? null : (String) map.get(key);
}

static String getString(List l, int idx) {
  return (String) get(l, idx);
}

static String getString(Object o, Object key) {
  if (o instanceof Map) return getString((Map) o, key);
  if (key instanceof String)
    return (String) getOpt(o, (String) key);
  throw fail("Not a string key: " + getClassName(key));
}

static String getString(String key, Object o) {
  return getString(o, (Object) key);
}

static Object evalInNewThread(final Object f) {
  final Flag flag = new Flag();
  final Var var = new Var();
  final Var<Throwable> exception = new Var();
  { startThread(new Runnable() {  public void run() { try {  try {
      var.set(callF(f));
    } catch (Throwable e) {
      exception.set(e);
    }
    flag.raise();
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "try {\r\n      var.set(callF(f));\r\n    } catch (Throwable e) {\r\n      exception..."; }}); }
  flag.waitUntilUp();
  if (exception.has()) throw rethrow(exception.get());
  return var.get();
}

static String callStaticAnswerMethod(List bots, String s) {
  for (Object c : bots) try {
    String answer = callStaticAnswerMethod(c, s);
    if (!empty(answer)) return answer;
  } catch (Throwable e) {
    print("Error calling " + getProgramID(c));
    e.printStackTrace();
  }
  return null;
}

static String callStaticAnswerMethod(Object c, String s) {
  String answer = (String) callOpt(c, "answer", s, litlist(s));
  if (answer == null)
    answer = (String) callOpt(c, "answer", s);
  return emptyToNull(answer);
}

static String callStaticAnswerMethod(String s) {
  return callStaticAnswerMethod(mc(), s);
}

static String callStaticAnswerMethod(String s, List<String> history) {
  return callStaticAnswerMethod(mc(), s, history);
}

static String callStaticAnswerMethod(Object c, String s, List<String> history) {
  String answer = (String) callOpt(c, "answer", s, history);
  if (answer == null)
    answer = (String) callOpt(c, "answer", s);
  return emptyToNull(answer);
}

static boolean match3(String pat, String s) {
  return match3(pat, s, null);
}

static boolean match3(String pat, String s, Matches matches) {
  if (pat == null || s == null) return false;
  return match3(pat, parse3_cachedInput(s), matches);
}
  
static boolean match3(String pat, List<String> toks, Matches matches) {
  List<String> tokpat = parse3_cachedPattern(pat);
  return match3(tokpat, toks, matches);
}

static boolean match3(List<String> tokpat, List<String> toks, Matches matches) {
  String[] m = match2(tokpat, toks);
  //print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m));
  if (m == null) return false;
  if (matches != null) matches.m = m; return true;
}

static File computerIDFile() {
  return javaxDataDir("Basic Info/computer-id.txt");
}

static String makeRandomID(int length) {
  return makeRandomID(length, defaultRandomGenerator());
}

static String makeRandomID(int length, Random random) {
  char[] id = new char[length];
  for (int i = 0; i < id.length; i++)
    id[i] = (char) ((int) 'a' + random.nextInt(26));
  return new String(id);
}

static String makeRandomID(Random r, int length) {
  return makeRandomID(length, r);
}

static boolean sameSnippetID(String a, String b) {
  if (!isSnippetID(a) || !isSnippetID(b)) return false;
  return parseSnippetID(a) == parseSnippetID(b);
}

static volatile String caseID_caseID;

static String caseID() { return caseID_caseID; }

static void caseID(String id) {
  caseID_caseID = id;
}

static boolean isJavaxApplicationSnippetType(int type) {
  return type == snippetType_javaxSource() || type == snippetType_JavaXDesktop();
}

static boolean isJavaxModuleSnippetType(int type) {
  return type == snippetType_javaxModule() || type == snippetType_javaxDesktopModule();
}

static int snippetType_dynModule() {
  return 57;
}

static File localSnippetsDir() {
  return javaxDataDir("Personal Programs");
}

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

static File oneOfTheFiles(String... paths) {
  if (paths != null) for (String path : paths)
    if (fileExists(path))
      return newFile(path);
  return null;
}

static File oneOfTheFiles(File... files) {
  return oneOfTheFiles(asList(files));
}

static File oneOfTheFiles(Iterable<File> files) {
  if (files != null) for (File f : files)
    if (fileExists(f))
      return f;
  return null;
}



static String joinStrings(String sep, Object... strings) {
  return joinStrings(sep, Arrays.asList(strings));
}

static String joinStrings(String sep, Iterable strings) {
  StringBuilder buf = new StringBuilder();
  for (Object o : unnull(strings)) { 
    String s = strOrNull(o);
    if (nempty(s)) {
      if (nempty(buf)) buf.append(sep);
      buf.append(s);
    }
  }
  return str(buf);
}

static String utf8streamToString(InputStream in) {
  return readerToString(utf8bufferedReader(in));
}

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

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

// starts searching from i-1
static <A> int lastIndexOf(List<A> l, int i, A a) {
  if (l == null) return -1;
  for (i = min(l(l), i)-1; i >= 0; i--)
    if (eq(l.get(i), a))
      return i;
  return -1;
}

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

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

static String emptyToNull(String s) {
  return eq(s, "") ? null : s;
}

static <A, B> Map<A, B> emptyToNull(Map<A, B> map) {
  return empty(map) ? null : map;
}



static Map<String, List<String>> parse3_cachedInput_cache = synchronizedMRUCache(1000);

static List<String> parse3_cachedInput(String s) {
  List<String> tok = parse3_cachedInput_cache.get(s);
  if (tok == null) parse3_cachedInput_cache.put(s, tok = parse3(s));
  return tok;
}





static Map<String, List<String>> parse3_cachedPattern_cache = synchronizedMRUCache(1000);

static synchronized List<String> parse3_cachedPattern(String s) {
  List<String> tok = parse3_cachedPattern_cache.get(s);
  if (tok == null) parse3_cachedPattern_cache.put(s, tok = parse3(s));
  return tok;
}



static Random defaultRandomGenerator() {
  return ThreadLocalRandom.current();
}

static int snippetType_javaxSource() {
  return 34;
}

static int snippetType_JavaXDesktop() {
  return 55;
}

static int snippetType_javaxModule() {
  return 54;
}

static int snippetType_javaxDesktopModule() {
  return 58;
}



static String strOrNull(Object o) {
  return o == null ? null : str(o);
}

static String readerToString(Reader r) { try {
  try {
    StringBuilder buf = new StringBuilder();
    int n = 0;
    while (true) {
      int ch = r.read();
      if (ch < 0)
        break;
      buf.append((char) ch);
      ++n;
      //if ((n % loadPage_verboseness) == 0) print("  " + n + " chars read");
    }
    return buf.toString();
  } finally {
    r.close();
  }  
} catch (Exception __e) { throw rethrow(__e); } }

static <A, B> Map<A, B> synchronizedMRUCache(int maxSize) {
  return synchroMap(new MRUCache(maxSize));
}

static List<String> parse3(String s) {
  return dropPunctuation(javaTokPlusPeriod(s));
}



static List<String> dropPunctuation_keep = ll("*", "<", ">");

static List<String> dropPunctuation(List<String> tok) {
  tok = new ArrayList<String>(tok);
  for (int i = 1; i < tok.size(); i += 2) {
    String t = tok.get(i);
    if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !dropPunctuation_keep.contains(t)) {
      tok.set(i-1, tok.get(i-1) + tok.get(i+1));
      tok.remove(i);
      tok.remove(i);
      i -= 2;
    }
  }
  return tok;
}

static String dropPunctuation(String s) {
  return join(dropPunctuation(nlTok(s)));
}



static List<String> nlTok(String s) {
  return javaTokPlusPeriod(s);
}



// immutable, has strong refs
final static class _MethodCache {
  final Class c;
  final HashMap<String, List<Method>> cache = new HashMap();
  
  _MethodCache(Class c) {
  this.c = c; _init(); }
  
  void _init() {
    Class _c = c;
    while (_c != null) {
      for (Method m : _c.getDeclaredMethods())
        if (!isAbstract(m) && !reflection_isForbiddenMethod(m))
          multiMapPut(cache, m.getName(), makeAccessible(m));
      _c = _c.getSuperclass();
    }
    
    // add default methods - this might lead to a duplication
    // because the overridden method is also added, but it's not
    // a problem except for minimal performance loss.
    for (Class intf : allInterfacesImplementedBy(c))
      for (Method m : intf.getDeclaredMethods())
        if (m.isDefault() && !reflection_isForbiddenMethod(m))
          multiMapPut(cache, m.getName(), makeAccessible(m));

    
  }
  
  // Returns only matching methods
  Method findMethod(String method, Object[] args) { try {
    List<Method> m = cache.get(method);
    
    if (m == null) return null;
    int n = m.size();
    for (int i = 0; i < n; i++) {
      Method me = m.get(i);
      if (call_checkArgs(me, args, false))
        return me;
    }
    return null;
  } catch (Exception __e) { throw rethrow(__e); } }
  
  Method findStaticMethod(String method, Object[] args) { try {
    List<Method> m = cache.get(method);
    if (m == null) return null;
    int n = m.size();
    for (int i = 0; i < n; i++) {
      Method me = m.get(i);
      if (isStaticMethod(me) && call_checkArgs(me, args, false))
        return me;
    }
    return null;
  } catch (Exception __e) { throw rethrow(__e); } }
}static abstract class VF1<A> implements IVF1<A> {
  public abstract void get(A a);
}static class Matches {
  String[] m;
  
  Matches() {}
  Matches(String... m) {
  this.m = m;}
  
  String get(int i) { return i < m.length ? m[i] : null; }
  String unq(int i) { return unquote(get(i)); }
  
  String tlc(int i) { return unq(i).toLowerCase(); }
  boolean bool(int i) { return "true".equals(unq(i)); }
  String rest() { return m[m.length-1]; } // for matchStart
  int psi(int i) { return Integer.parseInt(unq(i)); }
  
  public String toString() { return "Matches(" + joinWithComma(quoteAll(asList(m))) + ")"; }
  
  public int hashCode() { return _hashCode(toList(m)); }
  public boolean equals(Object o) { return o instanceof Matches && arraysEqual(m, ((Matches) o).m); }
}
static class Var<A> implements IVar<A>, ISetter<A> {
  Var() {}
  Var(A v) {
  this.v = v;}

  
  A v; // you can access this directly if you use one thread
  
  public synchronized void set(A a) {
    if (v != a) {
      v = a;
      notifyAll();
    }
  }
  
  public synchronized A get() { return v; }
  public synchronized boolean has() { return v != null; }
  public synchronized void clear() { v = null; }
  
  public String toString() { return str(this.get()); }
}static interface IResourceLoader {
  String loadSnippet(String snippetID);
  String getTranspiled(String snippetID); // with libs
  int getSnippetType(String snippetID);
  String getSnippetTitle(String snippetID);
  File loadLibrary(String snippetID);
  
  default File pathToJavaXJar() { return pathToJavaxJar_noResourceLoader(); }
  
  // may return null, then caller compiles themselves
  default File getSnippetJar(String snippetID, String transpiledSrc) { return null; }
}static class proxy_InvocationHandler implements InvocationHandler {
  Object target;
  
  proxy_InvocationHandler() {}
  proxy_InvocationHandler(Object target) {
  this.target = target;}
  
  public Object invoke(Object proxy, Method method, Object[] args) {
    return call(target, method.getName(), unnull(args));
  }
}static class CompilerBot {
  static boolean verbose = false;

  static File compileSnippet(String snippetID) {
    return compileSnippet(snippetID, "");
  }
  
  static Pair<File, String> compileSnippet2(String snippetID) {
    return compileSnippet2(snippetID, "");
  }
  
  // returns jar path
  static File compileSnippet(String snippetID, String javaTarget) {
    return compileSnippet2(snippetID, javaTarget).a;
  }
  
  // returns jar path, Java source
  static Pair<File, String> compileSnippet2(String snippetID, String javaTarget) {
    String transpiledSrc = getServerTranspiled2(snippetID);
    if (transpiledSrc == null) throw fail("Snippet not found or not public: " + snippetID);
    int i = transpiledSrc.indexOf('\n');
    String libs = transpiledSrc.substring(0, Math.max(0, i));
    if (verbose)
      print("Compiling snippet: " + snippetID + ". Libs: " + libs);
    transpiledSrc = transpiledSrc.substring(i+1);
    return pair(compile(transpiledSrc, libs, javaTarget, snippetID), transpiledSrc);
  }

  static File compile(String src) {
    return compile(src, "");
  }
  
  static File compile(String src, String libs) {
    return compile(src, libs, null);
  }

  static File compile(String src, String dehlibs, String javaTarget) {
    return compile(src, dehlibs, javaTarget, null);
  }
  
  static File compile(String src, String dehlibs, String javaTarget, String progID) {
    if (verbose)
      print("Compiling " + l(src) + " chars");
      
    // Note: This is different from the calculation in x30
    // (might lead to programs being compiled twice)
    String md5 = md5(dehlibs + "\n" + src + "\n" + fsIOpt(progID));
    File jar = getJarFile(md5);
    if (jar == null || jar.length() <= 22) {
      // have to compile
      
      //print("Have to compile: " + progID + " / " + md5);
      
      List<String> mainClass = findMainClass(javaTok(src));
      boolean canRename = mainClass != null && useDummyMainClasses() && isSnippetID(progID) && !tok_classHasModifier(mainClass, "public");
      if (verbose)
        print("useRenaming: " + useDummyMainClasses() + ", canRename: " + canRename + ", progID: " + progID);

      javaCompileToJar_optionalRename(src, dehlibs, jar, canRename ? progID : null, progID);
    } else {
      if (verbose)
        print("Getting classes from cache (" + jar.getAbsolutePath() + ", " + jar.length() + " bytes)");
      touchFile(jar); // so we can find the unused ones easier
    }
    
    return jar;
  }

  // look in non-virtual JavaX-Caches first (important for packaged programs)
  static File getJarFile(String md5) {
    assertTrue(isMD5(md5));
    String sub = "JavaX-Caches/#1002203/" + md5 + ".jar";
    File f = actualUserDir(sub);
    return fileExists(f) ? f : userDir(sub);
  }
}static class Pair<A, B> implements Comparable<Pair<A, B>> {
  A a;
  B b;

  Pair() {}
  Pair(A a, B b) {
  this.b = b;
  this.a = a;}
  
  public int hashCode() {
    return hashCodeFor(a) + 2*hashCodeFor(b);
  }
  
  public boolean equals(Object o) {
    if (o == this) return true;
    if (!(o instanceof Pair)) return false;
    Pair t = (Pair) o;
    return eq(a, t.a) && eq(b, t.b);
  }
  
  public String toString() {
    return "<" + a + ", " + b + ">";
  }
  
  public int compareTo(Pair<A, B> p) {
    if (p == null) return 1;
    int i = ((Comparable<A>) a).compareTo(p.a);
    if (i != 0) return i;
    return ((Comparable<B>) b).compareTo(p.b);
  }
}static interface IResourceHolder {
  <A extends AutoCloseable> A add(A a);
}static class JavaXClassLoader extends URLClassLoader {
  String progID;
  List<File> files;
  Set<String> triedToLoad = synchroSet();
  Set<Class> loadedClasses = synchroSet();
  boolean retired = false;
  Object retiredMarker;
  
  JavaXClassLoader(String progID, List<File> files) {
    this(progID, files, getSystemClassLoader());
  }
  
  JavaXClassLoader(String progID, List<File> files, ClassLoader parent) {
    super(new URL[0], parent);
    this.progID = progID;
    this.files = files;
    
    { try {
      for (File f : files)
        addURL(f.toURI().toURL());
    } catch (Exception __e) { throw rethrow(__e); } }
    
    fixACCInClassLoader(this);
  }
  
  protected Class<?> findClass(String name) throws ClassNotFoundException {
    boolean triedBefore = !triedToLoad.add(name);
    try {
      Class<?> c = super.findClass(name);
      loadedClasses.add(c);
      if (eq(name, "main"))
        callOpt(javax(), "registerAMainClass", c);
      return c;
    } catch (ClassNotFoundException e) {
      throw new ClassNotFoundException("Class " + name + " not found in " + joinWithComma(map("f2s", files)) + " (progID=" + progID + ")"
        + (triedBefore ? ", tried to load before" : ""), e);
    }
  }
  
  public String toString() {
    return "JavaXClassLoader[" + systemHashCodeHex(this) + "] - " + progID;
  }
}
static class ProgramScan {
  static int threads = isWindows() ? 500 : 10;
  static int timeout = 5000; // hmm...
  static String ip = "127.0.0.1";
  
  // This range is not used anymore anyway
  static int quickScanFrom = 10000, quickScanTo = 10999;

  static int maxNumberOfVMs_android = 4; // Android will always only have one if we don't screw up
  static int maxNumberOfVMs_nonAndroid = 50; // 100;
  static int maxNumberOfVMs;
  
  static boolean verbose = false;
  
  static class Program {
    int port;
    String helloString;
    
    Program(int port, String helloString) {
  this.helloString = helloString;
  this.port = port;}
  }
  
  static List<Program> scan() { try {
    return scan(1, 65535);
  } catch (Exception __e) { throw rethrow(__e); } }
  
  static List<Program> scan(int fromPort, int toPort) {
    return scan(fromPort, toPort, new int[0]);
  }
  
  static List<Program> scan(int fromPort, int toPort, int[] preferredPorts) { try {
    Set<Integer> preferredPortsSet = new HashSet<Integer>(asList(preferredPorts));
    int scanSize = toPort-fromPort+1;
    String name = toPort < 10000 ? "bot" : "program";
    int threads = isWindows() ? min(500, scanSize) : min(scanSize, 10);
    final ExecutorService es = Executors.newFixedThreadPool(threads);
    if (verbose) print(firstToUpper(name) + "-scanning " + ip + " with timeout " + timeout + " ms in " + threads + " threads.");
    startTiming();
    List<Future<Program>> futures = new ArrayList();
    List<Integer> ports = new ArrayList();
    for (int port : preferredPorts) {
      futures.add(checkPort(es, ip, port, timeout));
      ports.add(port);
    }
    for (int port = fromPort; port <= toPort; port++)
      if (!preferredPortsSet.contains(port) && !forbiddenPort(port)) {
        futures.add(checkPort(es, ip, port, timeout));
        ports.add(port);
      }
    es.shutdown();
    List<Program> programs = new ArrayList();
    long time = now();
    int i = 0;
    for (final Future<Program> f : futures) {
      if (verbose) print("Waiting for port " + get(ports, i++) + " at time " + (now()-time));
      Program p = f.get();
      if (p != null)
        programs.add(p);
    }
    //stopTiming("Port Scan " + scanSize + ", " + n(threads, "threads") + ": ", 250);
    if (verbose) print("Found " + programs.size() + " " + name + "(s) on " + ip);
    return programs;
  } catch (Exception __e) { throw rethrow(__e); } }

  static Future<Program> checkPort(final ExecutorService es, final String ip, final int port, final int timeout) {
    return es.submit(new Callable<Program>() {
        @Override public Program call() {
          try {
            Socket socket = new Socket();
            try {
              socket.setSoTimeout(timeout);
              socket.connect(new InetSocketAddress(ip, port), timeout);
              //if (verbose) print("Connected to " + ip + ":" + port);
              BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), "UTF-8"));
              String hello = or(in.readLine(), "?");
              return new Program(port, hello);
            } finally {
              socket.close();
            }
          } catch (Exception ex) {
            return null;
          }
        }
     });
  }
  
  static List<Program> quickScan() {
    return scan(quickScanFrom, quickScanTo);
  }
  
  static List<Program> quickBotScan() {
    return quickBotScan(new int[0]);
  }
  
  static List<Program> quickBotScan(int[] preferredPorts) {
    if (maxNumberOfVMs == 0)
      maxNumberOfVMs = isAndroid() ? maxNumberOfVMs_android : maxNumberOfVMs_nonAndroid;
    return scan(4999, 5000+maxNumberOfVMs-1, preferredPorts);
  }
}static abstract class DialogIO implements AutoCloseable {
  String line;
  boolean eos, loud, noClose;
  Lock lock = lock();
  
  abstract String readLineImpl();
  abstract boolean isStillConnected();
  abstract void sendLine(String line);
  abstract boolean isLocalConnection();
  abstract Socket getSocket();

  int getPort() { Socket s = getSocket(); return s == null ? 0 : s.getPort(); }
  
  boolean helloRead = false;
  int shortenOutputTo = 500;
  
  String readLineNoBlock() {
    String l = line;
    line = null;
    return l;
  }
  
  boolean waitForLine() { try {
    ping();
    if (line != null) return true;
    //print("Readline");
    line = readLineImpl();
    //print("Readline done: " + line);
    if (line == null) eos = true;
    return line != null;
  } catch (Exception __e) { throw rethrow(__e); } }
  
  String readLine() {
    waitForLine();
    helloRead = true;
    return readLineNoBlock();
  }
  
  String ask(String s, Object... args) {
    if (loud) return askLoudly(s, args);
    if (!helloRead) readLine();
    if (args.length != 0) s = format3(s, args);
    sendLine(s);
    return readLine();
  }
  
  String askLoudly(String s, Object... args) {
    if (!helloRead) readLine();
    if (args.length != 0) s = format3(s, args);
    print("> " + shorten(s, shortenOutputTo));
    sendLine(s);
    String answer = readLine();
    print("< " + shorten(answer, shortenOutputTo));
    return answer;
  }
  
  void pushback(String l) {
    if (line != null)
      throw fail();
    line = l;
    helloRead = false;
  }
}

static abstract class DialogHandler {
  abstract void run(DialogIO io);
}static abstract class F0<A> {
  abstract A get();
}static abstract class F1<A, B> {
  abstract B get(A a);
}// you still need to implement hasNext() and next()
static abstract class IterableIterator<A> implements Iterator<A>, Iterable<A> {
  public Iterator<A> iterator() {
    return this;
  }
  
  public void remove() {
    unsupportedOperation();
  }
}/** this class is fully thread-safe */
static class Flag implements Runnable {
  private boolean up = false;

  /** returns true if flag was down before (i.e. flag was actually raised right now) */
  public synchronized boolean raise() {
    if (!up) {
      up = true;
      notifyAll();
      return true;
    } else
      return false;
  }

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

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

  public synchronized boolean isUp() {
    return up;
  }
  
  boolean get() { return isUp(); }

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

  // currently does a semi-active wait with latency = 50 ms
  public void waitForThisOr(Flag otherFlag) { try {
    while (!isUp() && !otherFlag.isUp())
      Thread.sleep(50);
  } catch (Exception __e) { throw rethrow(__e); } }
  
  public void run() { raise(); }
}static class BetterLabel extends JLabel {
  boolean autoToolTip = true;
  
  BetterLabel() {
    // Listeners given out to componentPopupMenu must not directly
    // reference the outer object (-> weak map problem).
    final WeakReference < BetterLabel > me = new WeakReference<>(this);
    componentPopupMenu(this, BetterLabel_menuItems(me));
  }
  
  BetterLabel(String text) {
    this();
    this.setText(text);
  }
  
  public void setText(String text) {
    super.setText(text);
    if (autoToolTip)
      if (!swic(text, "<html>")) // HTML labels make super-huge, confusing tool tips
        setToolTipText(nullIfEmpty(text));
  }
}

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

  MRUCache() {}
  MRUCache(int maxSize) {
  this.maxSize = maxSize;}
  
  protected boolean removeEldestEntry(Map.Entry eldest) {
    return size() > maxSize;
  }
  
  Object _serialize() {
    return ll(maxSize, cloneLinkedHashMap(this));
  }
  
  static MRUCache _deserialize(List l) {
    MRUCache m = new MRUCache();
    m.maxSize = (int) first(l);
    m.putAll((LinkedHashMap) second(l));
    return m;
  }
}static interface IF0<A> {
  A get();
}static abstract class CloseableIterableIterator<A> extends IterableIterator<A> implements AutoCloseable {
  public void close() throws Exception {}
}static class JavaXClassLoaderWithParent2 extends JavaXClassLoader {
  ClassLoader virtualParent;
  List<String> classesToSkip; // classes that should be taken from parent

  JavaXClassLoaderWithParent2(String progID, List<File> files, ClassLoader virtualParent, List<String> classesToSkip) {
    super(progID, files);
    this.virtualParent = virtualParent;
    this.classesToSkip = classesToSkip;
  }
  
  protected Class<?> findClass(String name) throws ClassNotFoundException {
    if (shouldDelegate(name)) {
      Class<?> c = virtualParent.loadClass(name);
      if (c != null) return c;
    }
    return super.findClass(name);
  }
    
  boolean shouldDelegate(String name) {
    for (String s : classesToSkip)
      if (eq(name, s) || startsWith(name, s + "$"))
        return true;
    return false;
  }
}static interface Producer<A> {
  public A next(); // null when end
}static ThreadLocal<Boolean> DynamicObject_loading = new ThreadLocal();

static class DynamicObject {
  String className; // just the name, without the "main$"
  
  // string key = dynamic field
  // interface key = dynamic interface
  LinkedHashMap/*<S, O>*/ fieldValues; // dropped the type parameters 2021/5/19 to allow for dynamic interfaces
  
  DynamicObject() {}
  // className = just the name, without the "main$"
  DynamicObject(String className) {
  this.className = className;}
  
  Map<String, Object> _map() { return fieldValues; }
  
  public String toString() {
    return getClass() == DynamicObject.class ? "dyn " + className
      : super.toString();
  }
}static interface IF1<A, B> {
  B get(A a);
}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 interface IVF1<A> {
  void get(A a);
}static interface IVar<A> extends IF0<A> {
  void set(A a);
  A get();
  
  default boolean has() { return get() != null; }
  default void clear() { set(null); }
  
}

static interface ISetter<A> {
 void set(A a);
}


static boolean isAbstract(Class c) {
  return (c.getModifiers() & Modifier.ABSTRACT) != 0;
}

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

static Set<Class> allInterfacesImplementedBy(Class c) {
  if (c == null) return null;
  HashSet<Class> set = new HashSet();
  allInterfacesImplementedBy_find(c, set);
  return set;
}

static void allInterfacesImplementedBy_find(Class c, Set<Class> set) {
  if (c.isInterface() && !set.add(c)) return;
  do {
    for (Class intf : c.getInterfaces())
      allInterfacesImplementedBy_find(intf, set);
  } while ((c = c.getSuperclass()) != null);
}

static Method findMethod(Object o, String method, Object... args) {
  return findMethod_cached(o, method, args);
}

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

static Method findStaticMethod(Class c, String method, Object... args) {
  Class _c = c;
  while (c != null) {
    for (Method m : c.getDeclaredMethods()) {
      if (!m.getName().equals(method))
        continue;

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

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

static boolean findStaticMethod_checkArgs(Method m, Object[] args) {
  Class<?>[] types = m.getParameterTypes();
  if (types.length != args.length)
    return false;
  for (int i = 0; i < types.length; i++)
    if (!(args[i] == null || isInstanceX(types[i], args[i])))
      return false;
  return true;
}


static List<String> quoteAll(Collection<String> l) {
  List<String> x = new ArrayList();
  for (String s : l)
    x.add(quote(s));
  return x;
}

static int _hashCode(Object a) {
  return a == null ? 0 : a.hashCode();
}

static <A> ArrayList<A> toList(A[] a) { return asList(a); }
static ArrayList<Integer> toList(int[] a) { return asList(a); }
static <A> ArrayList<A> toList(Set<A> s) { return asList(s); }
static <A> ArrayList<A> toList(Iterable<A> s) { return asList(s); }

static boolean arraysEqual(Object[] a, Object[] b) {
  if (a.length != b.length) return false;
  for (int i = 0; i < a.length; i++)
    if (neq(a[i], b[i])) return false;
  return true;
}

// TODO: use actualUserHome()?
// (there was a problem with onLocallyInferiorJavaX() always triggering inside #1013896)

static File pathToJavaxJar() {
  
  IResourceLoader rl = vm_getResourceLoader();
  if (rl != null)
    return rl.pathToJavaXJar();
  
  
  return pathToJavaxJar_noResourceLoader();
}
  
static File pathToJavaxJar_noResourceLoader() { try {
  int x = latestInstalledJavaX();
  File xfile = new File(userHome(), ".javax/x" + Math.max(x, 30) + ".jar");
  if (!xfile.isFile()) {
    print("Saving " + f2s(xfile));
    String url = x30JarServerURL();
    byte[] data = loadBinaryPage(url);
    if (data.length < 1000000)
      throw fail("Could not load " + url);
    saveBinaryFile(xfile.getPath(), data);
  }
  return xfile;
} catch (Exception __e) { throw rethrow(__e); } }

// returns actual CNC
static List<String> findMainClass(List<String> tok) {
  for (List<String> c : reversedList(allClasses(tok))) {
    String name = getClassDeclarationName(c);
    if (eq(name, "main") || name.startsWith("x"))
      return c;
  }
  return findBlock("m {", tok);
}

static boolean useDummyMainClasses() {
  return true;
  //ret eq("1", trim(loadTextFile(getProgramFile(#1008755, "use-dummy-main-classes"))));
}

static boolean tok_classHasModifier(List<String> classDecl, String modifier) {
  if (classDecl == null) return false;
  int i = classDecl.indexOf("class");
  return subList(classDecl, 0, i).contains(modifier);
}

// before you use this, add a RAM disk cleaner
static boolean javaCompileToJar_useRAMDisk = false;

static File javaCompileToJar_optionalRename(String src, File destJar, String progIDForRename) {
  return javaCompileToJar_optionalRename(src, "", destJar, progIDForRename);
}

static synchronized File javaCompileToJar_optionalRename(String src, String dehlibs, File destJar, String progIDForRename) {
  return javaCompileToJar_optionalRename(src, dehlibs, destJar, progIDForRename, null);
}

// returns path to jar
static synchronized File javaCompileToJar_optionalRename(String src, String dehlibs, File destJar, String progIDForRename, String progID) {
  String javaTarget = null; // use default target
  
  //print("Compiling " + l(src) + " chars");
  String dummyClass = "main";
  if (progIDForRename != null) {
    dummyClass = dummyMainClassName(progIDForRename);
    src += "\nclass " + dummyClass + "{}";
  }
  String md5 = md5(src);
  File jar = destJar;

  Class j = getJavaX();
  if (javaTarget != null)
    setOpt(j, "javaTarget", javaTarget);
  //setOpt(j, "verbose", true);
  File srcDir = tempDir();
  String className = "main";
  String fileName = dummyClass + ".java";
  List<String> tok = javaTok(src);
  String packageName = tok_packageName(tok);
  if (packageName != null)
    fileName = packageName.replace(".", "/") + "/" + tok_firstClassName(tok) + ".java";
  File mainJava = new File(srcDir, fileName);
  //print("main java: " + mainJava.getAbsolutePath());
  saveTextFile(mainJava, src);
  File classesDir = javaCompileToJar_useRAMDisk ? tempDirPossiblyInRAMDisk() : tempDir();
  //print("Compiling to " + f2s(classesDir));
  try {
    List<File> libraries = new ArrayList();
    
    Matcher m = Pattern.compile("\\d+").matcher(dehlibs);
    while (m.find()) {
      String libID = m.group();
      //print("libID=" + quote(libID));
      assertTrue(isSnippetID(libID));
      libraries.add(loadLibraryOrSrcLib(libID));
    }
    
    libraries.add(pathToJavaxJar());
      
    String compilerOutput;
    try {
      compilerOutput = (String) call(j, "compileJava", srcDir, libraries, classesDir);
    } catch (Throwable e) {
      compilerOutput = (String) get(getJavaX(), "javaCompilerOutput");
      //fail("Compile Error. " + cleanJavaCompilerOutput(compilerOutput) + " " + e);
      compilerOutput = indentx("> ", cleanJavaCompilerOutput(compilerOutput));
      if (!swic(e.getMessage(), "Java compiler returned errors."))
        compilerOutput = appendWithNewLine(compilerOutput, str(e));
      //printStackTrace(e);
      throw fail(compilerOutput, e);
    }
    
    compilerOutput = cleanJavaCompilerOutput("Annotation processing got disabled, since it requires a 1.6 compliant JVM");

    if (nempty(compilerOutput)) {
      print("Compiler said: " + compilerOutput);
      //fail("Compile Error. " + compilerOutput);
    }
  
    // sanity test
    if (!anyFileWithExtensionInDir(classesDir, ".class")) {
      printWithIndent("SRC> ", src);
      throw fail("No classes generated (was compiling " + nChars(src) + ")");
    }
        
    // add sources to .jar
    saveTextFile(new File(classesDir, "main.java"), src);
    
    // add information about libraries to jar
    if (nempty(dehlibs))
      saveTextFile(new File(classesDir, "libraries"), dehlibs);
      
    // add prog id to jar
    saveTextFile(new File(classesDir, "progID"), progID);
  
    //print("Zipping: " + classesDir.getAbsolutePath() + " to " + jar.getAbsolutePath());
    dir2zip_recurse_verbose = false;
    int n = dir2zip_recurse(classesDir, jar); // cache on success only
    //print("Files zipped: " + n);
  
    return jar;
  } finally {
    if (isInRAMDisk(classesDir)) deleteDirectory(classesDir);
  }
}


// will create the file or update its last modified timestamp
static void touchFile(File file) { try {
  closeRandomAccessFile(newRandomAccessFile(mkdirsForFile(file), "rw"));
} catch (Exception __e) { throw rethrow(__e); } }

static int hashCodeFor(Object a) {
  return a == null ? 0 : a.hashCode();
}

static void fixACCInClassLoader(Object o) {
  try {
    AccessControlContext acc = vm_globalACC();
    if (acc != null)
      replaceACCInClassLoader(o, acc);
  } catch (Throwable __e) { _handleException(__e); }
}

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

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

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

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


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

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


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

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

// map: func(key, value) -> list element
static List map(Map map, Object f) {
  List x = new ArrayList();
  if (map != null) for (Object _e : map.entrySet()) {
    Map.Entry e = (Map.Entry) _e;
    x.add(callF(f, e.getKey(), e.getValue()));
  }
  return x;
}

static <A, B, C> List<C> map(Map<A, B> map, IF2<A, B, C> f) {
  return map(map, (Object) f);
}

static String systemHashCodeHex(Object o) {
  return intToHex(identityHashCode(o));
}

public static boolean isWindows() {
  return System.getProperty("os.name").contains("Windows");
}

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

static long stopTiming_defaultMin = 10;

static long startTiming_startTime;
static void startTiming() {
  startTiming_startTime = now();
}

static void stopTiming() {
  stopTiming(null);
}

static void stopTiming(String text) {
  stopTiming(text, stopTiming_defaultMin);
}

static void stopTiming(String text, long minToPrint) {
  long time = now()-startTiming_startTime;
  if (time >= minToPrint) {
    text = or2(text, "Time: ");
    print(text + time + " ms");
  }
}

static boolean forbiddenPort(int port) {
  return port == 5037; // adb
}


static volatile boolean readLine_noReadLine = false;

static String readLine_lastInput;
static String readLine_prefix = "[] ";

static String readLine() {
  if (readLine_noReadLine) return null;
  String s = readLineHidden();
  if (s != null) {
    readLine_lastInput = s;
    print(readLine_prefix + s);
  }
  return s;
}

static UnsupportedOperationException unsupportedOperation() {
  throw new UnsupportedOperationException();
}



static ThreadLocal<MouseEvent> componentPopupMenu_mouseEvent;

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

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

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

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

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

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



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

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

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

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

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

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

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

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

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

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

static void addMenuItem(JMenuBar menuBar, String text, Runnable action) {
  addMenuItem(menuBar, jmenuItem(text, action));
}

static void addMenuItem(JMenuBar menuBar, JMenuItem menuItem) {
  addDirectMenuItem(menuBar, menuItem);
}



static String copyTextToClipboard(Object _text) {
  String text = str(_text);
  StringSelection selection = new StringSelection(text);
  Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
  vmBus_send("newClipboardContents", text);
  return text;
}

static <A, B> LinkedHashMap<A, B> cloneLinkedHashMap(Map<A, B> map) {
  return map == null ? new LinkedHashMap() : new LinkedHashMap(map);
}

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

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

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


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





static <A> A second(Producer<A> p) {
  if (p == null) return null;
  if (p.next() == null) return null;
  return p.next();
}


static char second(String s) {
  return charAt(s, 1);
}



static <A> A set(A o, String field, Object value) {
  if (o == null) return null;
  if (o instanceof Class) set((Class) o, field, value);
  else try {
    Field f = set_findField(o.getClass(), field);
    makeAccessible(f);
    smartSet(f, o, value);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
  return o;
}

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

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



static Method findMethod_cached(Object o, String method, Object... args) { try {
  if (o == null) return null;
  if (o instanceof Class) {
    _MethodCache cache = callOpt_getCache(((Class) o));
    List<Method> methods = cache.cache.get(method);
    if (methods != null) for (Method m : methods)
      if (isStaticMethod(m) && findMethod_checkArgs(m, args, false))
        return m;
    return null;
  } else {
    _MethodCache cache = callOpt_getCache(o.getClass());
    List<Method> methods = cache.cache.get(method);
    if (methods != null) for (Method m : methods)
      if (findMethod_checkArgs(m, args, false))
        return m;
    return null;
  }
} catch (Exception __e) { throw rethrow(__e); } }


static int latestInstalledJavaX() {
  File[] files = new File(userHome(), ".javax").listFiles();
  int v = 0;
  if (files != null) for (File f : files) {
    Matcher m = regexpMatcher("x(\\d\\d\\d?)\\.jar", f.getName());
    if (m.matches())
      v = Math.max(v, Integer.parseInt(m.group(1)));
  }
  return v;
}

static String x30JarServerURL() {
  return "http://botcompany.de:8081/x30.jar";
}

static <A> List<A> reversedList(Iterable<A> l) {
  List<A> x = cloneList(l);
  Collections.reverse(x);
  return x;
}

static HashSet<String> allClasses_keywords = lithashset("class", "interface", "enum", "sclass", "sinterface", "record", "srecord", "strecord", "asclass", "concept");

// lists returned are actual CNC (N/C/N/.../C/N) - and connected to
// original list
// only returns the top level classes
static List<List<String>> allClasses(List<String> tok) {
  List<List<String>> l = new ArrayList();
  int n = tok.size();
  HashSet<String> _allClasses_keywords = allClasses_keywords;
  for (int i = 1; i < n; i += 2) {
    String t = tok.get(i);
    if ("{".equals(t)) // skip functions
      i = findEndOfBlock(tok, i)-1;
    else if (_allClasses_keywords.contains(t)
      && (tok_isJavaxMetaCommandLeftOf(tok, i) ||
        !eqGetOneOf(tok, i-2, ".", "include"))) {
      int j = i;
      while (j < n && !tok.get(j).equals("{"))
        j += 2;
      j = findEndOfBlock(tok, j)+1;
      i = leftScanModifiers(tok, i);
      l.add(tok.subList(i-1, Math.min(n, j)));
      i = j-2;
    }
  }
  return l;
}

static List<List<String>> allClasses(String text) {
  return allClasses(javaTok(text));
}

static String getClassDeclarationName(List<String> tok) {
  if (tok != null)
    for (int i = 1; i+2 < tok.size(); i += 2)
      if (allClasses_keywords.contains(tok.get(i)) && isIdentifier(tok.get(i+2))) {
        if (eqGet(tok, i+2, "noeq")) i += 2;
        return tok.get(i+2);
      }
  return null;
}


static List<String> findBlock(String pat, List<String> tok) {
  List<String> tokpat = javaTok(pat);
  int i = findCodeTokens(tok, toStringArray(codeTokensOnly(tokpat)));
  //print("index of block " + quote(pat) + ": " + i);
  if (i < 0) return null;
  int bracketIdx = i+tokpat.size()-3;
  assertEquals("{", tok.get(bracketIdx));
  int endIdx = findEndOfBlock(tok, bracketIdx);
  return subList(tok, i-1, endIdx+1); // make it actual CNC
}

static String dummyMainClassName(String progID) {
  return "m" + psI(progID);
}

  static File tempDir() {
    return makeTempDir();
  }

static String tok_packageName(List<String> tok) {
  int i = jfind(tok, "package");
  if (i < 0) return "";
  i += 2;
  int j = jfind(tok, i, ";");
  if (j < 0) return "";
  return join(codeTokensOnly(subList(tok, i-1, j)));
}

static String tok_firstClassName(List<String> tok) {
  int i = jfind(tok, "class <id>");
  return i < 0 ? null : tok.get(i+2);
}

static File tempDirPossiblyInRAMDisk() {
  File f = linux_fileInRamDisk(aGlobalID());
  if (f != null) { f.mkdirs(); return f; }
  return makeTempDir();
}

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

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

static String indentx(String indent, String s) {
  return dropSuffix(indent, indent(indent, s));
}

static String cleanJavaCompilerOutput(String s) {
  return dropPrefixTrim("Annotation processing got disabled, since it requires a 1.6 compliant JVM", s);
}


static String appendWithNewLine(String a, String b) {
  if (empty(b)) return a;
  if (empty(a)) return b;
  return addSuffix(a, "\n") + b;
}

static boolean anyFileWithExtensionInDir(File dir, String ext) {
  return nempty(filesWithExtension(ext, findAllFiles_noDirs(dir)));
}

static <A> A printWithIndent(A o) {
  return printIndent(o);
}



static <A> A printWithIndent(String indent, A o) {
  return printIndent(indent, o);
}



static void printWithIndent(int indent, Object o) {
  printIndent(indent, o);
}

static String nChars(long n) { return n2(n, "char"); }
static String nChars(String s) { return nChars(l(s)); }

static boolean dir2zip_recurse_verbose = false;

static int dir2zip_recurse(File inDir, File zip) {
  return dir2zip_recurse(inDir, zip, "");
}

// TODO: the zero files case?
static int dir2zip_recurse(File inDir, File zip, String outPrefix) { try {
  mkdirsForFile(zip);
  FileOutputStream fout = newFileOutputStream(zip);
  ZipOutputStream outZip = new ZipOutputStream(fout);
  try {
    return dir2zip_recurse(inDir, outZip, outPrefix, 0);
  } finally {
    outZip.close();
  }
} catch (Exception __e) { throw rethrow(__e); } }

static int dir2zip_recurse(File inDir, ZipOutputStream outZip) {
  return dir2zip_recurse(inDir, outZip, "", 0);
}

static int dir2zip_recurse(File inDir, ZipOutputStream outZip, String outPrefix, int level) { try {
  if (++level >= 20) throw fail("woot? 20 levels in zip?");
  
  List<File> files = new ArrayList();
  for (File f : listFiles(inDir))
    files.add(f);

  int n = 0;
  sortFilesByName(files);
  for (File f : files) {
    if (f.isDirectory()) {
      print("dir2zip_recurse: Scanning " + f.getAbsolutePath());
      n += dir2zip_recurse(f, outZip, outPrefix + f.getName() + "/", level);
    } else {
      if (dir2zip_recurse_verbose) print("Copying " + f.getName());
      outZip.putNextEntry(new ZipEntry(outPrefix + f.getName()));
      InputStream fin = new FileInputStream(f);
      copyStream(fin, outZip);
      fin.close();
      ++n;
    }
  }
  return n;
} catch (Exception __e) { throw rethrow(__e); } }


static boolean isInRAMDisk(File f) {
  return startsWithOneOf(f2s(f), "/dev/shm/", "/run/shm/");
}

static void deleteDirectory(File dir) {
  deleteDirectory(dir, false, false);
}

static void deleteDirectory(File dir, boolean verbose, boolean testRun) {
  deleteAllFilesInDirectory(dir, verbose, testRun);
  if (verbose) print((testRun ? "Would delete " : "Deleting ") + dir.getAbsolutePath());
  if (!testRun)
    dir.delete();
}


static void closeRandomAccessFile(RandomAccessFile f) {
  if (f != null) try {
    f.close();
    callJavaX("dropIO", f);
  } catch (Throwable e) {
    printStackTrace(e);
  }
}

static RandomAccessFile newRandomAccessFile(File path, String mode) { try {
  boolean forWrite = mode.indexOf('w') >= 0;
  if (forWrite) mkdirsForFile(path);
  RandomAccessFile f = new RandomAccessFile(path, mode);
  
  callJavaX("registerIO", f, path, forWrite);
  
  return f;
} catch (Exception __e) { throw rethrow(__e); } }

static AccessControlContext vm_globalACC() {
  return (AccessControlContext) vm_generalMap_get("Global ACC");
}

static void replaceACCInClassLoader(Object o, AccessControlContext newACC) {
  ClassLoader cl = getClassLoaderOrSame(o);
  if (cl instanceof URLClassLoader) { try {
    setOpt(cl, "acc" , newACC);
    try {
      setOpt((Object) getOpt(cl, "ucp"), "acc" , newACC);
    } catch (Throwable e) {
      
      printShortException("replaceACCInClassLoader: ", e);
      if (java10OrHigher())
        if (addDefaultVMOption("--add-opens java.base/jdk.internal.loader=ALL-UNNAMED"))
          print("Please restart the OS");
    }
  } catch (Throwable __e) { _handleException(__e); }}
}

static String intToHex(int i) {
  return bytesToHex(intToBytes(i));
}

static int identityHashCode(Object o) {
  return System.identityHashCode(o);
}

static String readLineHidden() { try {
  if (get(javax(), "readLine_reader") == null)
    set(javax(), "readLine_reader" , new BufferedReader(new InputStreamReader(System.in, "UTF-8")));
  try {
    return ((BufferedReader) get(javax(), "readLine_reader")).readLine();
  } finally {
    consoleClearInput();
  }
} catch (Exception __e) { throw rethrow(__e); } }

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

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

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

static Object findComponentPopupMenuListener_gen(final JComponent c) {
  return c == null ? null : swing(new F0<Object>() { public Object get() { try { 
    return firstWithClassShortNamed("componentPopupMenu_Adapter", c.getMouseListeners());
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret firstWithClassShortNamed('componentPopupMenu_Adapter, c.getMouseListeners..."; }});
}

static boolean internalFrameActive(Component c) {
  final JInternalFrame f = getInternalFrame(c);
  return f != null && swing(new F0<Boolean>() { public Boolean get() { try {  return f.isSelected();  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret f.isSelected();"; }});
}

static 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 jmenuItem_newThreads = false;

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

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

static MenuItem menuItem(String text, final Object r) {
  MenuItem mi = new MenuItem(text);
  mi.addActionListener(actionListener(r));
  return mi;
}

static void addDirectMenuItem(JMenuBar mb, String text, Object action) {
  if (mb != null) { swing(new Runnable() {  public void run() { try { 
    addDirectMenuItem(mb, directJMenuItem(text, action));
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "addDirectMenuItem(mb, directJMenuItem(text, action));"; }}); }
}

static void addDirectMenuItem(Component c, String text, Object action) {
  addDirectMenuItem(addMenuBar(c), text, action);
}

static void addDirectMenuItem(JMenuBar mb, JMenuItem menuItem) {
  if (mb != null) { swing(new Runnable() {  public void run() { try { 
    mb.add(menuItem);
    revalidate(mb);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "mb.add(menuItem);\r\n    revalidate(mb);"; }}); }
}

static char charAt(String s, int i) {
  return s != null && i >= 0 && i < s.length() ? s.charAt(i) : '\0';
}



// 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, n = cnc.size();
  while (j < n) {
    String t = cnc.get(j);
    if ("{".equals(t)) ++level;
    else if ("}".equals(t)) --level;
    if (level == 0)
      return j+1;
    j += 2;
  }
  return n;
}

// i points at C token after suspected meta command
static boolean tok_isJavaxMetaCommandLeftOf(List<String> tok, int i) {
  int j = i-2*4-1;
  if (j >= 0 && jfind(subList(tok, j, i), "set flag <id> .") == 1) return true;
  return false;
}

static <A> boolean eqGetOneOf(List<A> l, int i, A... options) {
  return eqOneOf(get(l, i), options);
}

static int leftScanModifiers(List<String> tok, int i) {
  List<String> mod = getJavaModifiers();
  while (i > 1 && mod.contains(tok.get(i-2)))
    i -= 2;
  return i;
}


static boolean eqGet(List l, int i, Object o) {
  return eq(get(l, i), o);
}

static <A, B> boolean eqGet(Map<A, B> map, A key, Object o) {
  return eq(mapGet(map, key), o);
}

static int findCodeTokens(List<String> tok, String... tokens) {
  return findCodeTokens(tok, 1, false, tokens);
}

static int findCodeTokens(List<String> tok, boolean ignoreCase, String... tokens) {
  return findCodeTokens(tok, 1, ignoreCase, tokens);
}

static int findCodeTokens(List<String> tok, int startIdx, boolean ignoreCase, String... tokens) {
  return findCodeTokens(tok, startIdx, ignoreCase, tokens, null);
}

static HashSet<String> findCodeTokens_specials = lithashset("*", "<quoted>", "<id>", "<int>", "\\*");
static int findCodeTokens_bails, findCodeTokens_nonbails;

static interface findCodeTokens_Matcher {
  boolean get(String token);
}

static int findCodeTokens(List<String> tok, int startIdx, boolean ignoreCase, String[] tokens, Object condition) {
  int end = tok.size()-tokens.length*2+2, nTokens = tokens.length;
  int i = startIdx | 1;
  
  // bail out early if first token not found (works great with IndexedList)
  String firstToken = tokens[0];
  if (!ignoreCase && !findCodeTokens_specials.contains(firstToken)) {
    
    
    // quickly scan for first token
    while (i < end && !firstToken.equals(tok.get(i)))
      i += 2;
  }
  
  findCodeTokens_Matcher[] matchers = new findCodeTokens_Matcher[nTokens];
  for (int j = 0; j < nTokens; j++) {
    String p = tokens[j];
    findCodeTokens_Matcher matcher;
    if (p.equals("*"))
      matcher = t -> true;
    else if (p.equals("<quoted>"))
      matcher = t -> isQuoted(t);
    else if (p.equals("<id>"))
      matcher = t -> isIdentifier(t);
    else if (p.equals("<int>"))
      matcher = t -> isInteger(t);
    else if (p.equals("\\*"))
      matcher = t -> t.equals("*");
    else if (ignoreCase)
      matcher = t -> eqic(p, t);
    else
      matcher = t -> t.equals(p);
    matchers[j] = matcher;
  }
 
  outer: for (; i < end; i += 2) {
    for (int j = 0; j < nTokens; j++)
      if (!matchers[j].get(tok.get(i+j*2)))
        continue outer;

    if (condition == null || checkTokCondition(condition, tok, i-1)) // pass N index
      return i;
  }
  return -1;
}

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 List<String> codeTokensOnly(List<String> tok) {
  int n = l(tok);
  List<String> l = emptyList(n/2);
  for (int i = 1; i < n; i += 2)
    l.add(tok.get(i));
  return l;
}

  static File makeTempDir() {
    return (File) call(getJavaX(), "TempDirMaker_make");
  }

static int jfind(String s, String in) {
  return jfind(javaTok(s), in);
}

static int jfind(List<String> tok, String in) {
  return jfind(tok, 1, in);
}

static int jfind(List<String> tok, int startIdx, String in) {
  return jfind(tok, startIdx, in, null);
}

static int jfind(List<String> tok, String in, Object condition) {
  return jfind(tok, 1, in, condition);
}

static int jfind(List<String> tok, String in, ITokCondition condition) { return jfind(tok, 1, in, condition); }
static int jfind(List<String> tok, int startIndex, String in, ITokCondition condition) {
  return jfind(tok, startIndex, in, toTokCondition(condition));
}

static int jfind(List<String> tok, int startIdx, String in, Object condition) {
  //LS tokin = jfind_preprocess(javaTok(in));
  return jfind(tok, startIdx, javaTokForJFind_array(in), condition);
}

// assumes you preprocessed tokin
static int jfind(List<String> tok, List<String> tokin) {
  return jfind(tok, 1, tokin);
}

static int jfind(List<String> tok, int startIdx, List<String> tokin) {
  return jfind(tok, startIdx, tokin, null);
}

static int jfind(List<String> tok, int startIdx, String[] tokinC, Object condition) {
  return findCodeTokens(tok, startIdx, false, tokinC, condition);
}

static int jfind(List<String> tok, int startIdx, List<String> tokin, Object condition) {
  return jfind(tok, startIdx, codeTokensAsStringArray(tokin), condition);
}

static List<String> jfind_preprocess(List<String> tok) {
  for (String type : litlist("quoted", "id", "int"))
    replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">"));
  replaceSublist(tok, ll("\\", "", "*"), ll("\\*"));
  return tok;
}

static File linux_fileInRamDisk(String name) {
  if (!isLinux()) return null;
  File dir = newFile("/dev/shm");
  if (dir.isDirectory()) return newFile(dir, name);
  return null;
}

static String aGlobalID() {
  return randomID(globalIDLength());
}

static String aGlobalID(Random random) {
  return randomID(random, globalIDLength());
}

static String repeat(char c, int n) {
  n = Math.max(n, 0);
  char[] chars = new char[n];
  for (int i = 0; i < n; i++)
    chars[i] = c;
  return new String(chars);
}

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

static <A> List<A> repeat(int n, A a) {
  return repeat(a, n);
}

static int indent_default = 2;

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

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

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

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

static List<String> indent(String indent, List<String> lines) {
  List<String> l = new ArrayList();
  if (lines != null) for (String s : lines)
    l.add(indent + s);
  return l;
}

static String dropPrefixTrim(String prefix, String s) {
  return trim(dropPrefix(prefix, s));
}

static String addSuffix(String s, String suffix) {
  return s == null || s.endsWith(suffix) ? s : s + suffix;
}

static List<File> filesWithExtension(String ext, List<File> files) {
  return filesEndingWith(files, addPrefixIfNotEmpty2(".", ext));
}

static List<File> findAllFiles_noDirs(List dirs) {
  return findAllFiles_noDirs(asObjectArray(dirs));
}

// dirs are String's or File's
static List<File> findAllFiles_noDirs(Object... dirs) {
  List<File> l = new ArrayList();
  for (Object dir : dirs) {
    if (dir instanceof String && ((String) dir).endsWith("/.")) {
      // "/." means non-recurse
      for (File f : listFiles(dropSuffix("/.", (String) dir)))
        if (f.isFile()) l.add(f);
    } else
      findAllFiles_noDirs_impl(toFile(dir), l);
  }
  return l;
}

static void findAllFiles_noDirs_impl(File dir, List<File> l) {
  for (File f : listFiles(dir)) {
    if (f.isDirectory())
      findAllFiles_noDirs_impl(f, l);
    else
      l.add(f);
  }
}


static <A> A printIndent(A o) {
  print(indentx(str(o)));
  return o;
}

static <A> A printIndent(String indent, A o) {
  print(indentx(indent, str(o)));
  return o;
}

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

static File[] listFiles(File dir) {
  File[] files = dir.listFiles();
  return files == null ? new File[0] : files;
}

static File[] listFiles(String dir) {
  return listFiles(new File(dir));
}

static List<File> sortFilesByName(List<File> l) {
  sort(l, (a, b) -> stdcompare(a.getName(), b.getName()));
  return l;
}

static int deleteAllFilesInDirectory_minPathLength = 10;

static void deleteAllFilesInDirectory(File dir) {
  deleteAllFilesInDirectory(dir, false, false);
}

static void deleteAllFilesInDirectory(File dir, boolean verbose, boolean testRun) {
  dir = getCanonicalFile(dir);
  assertTrue(f2s(dir), l(f2s(dir)) >= deleteAllFilesInDirectory_minPathLength);
  File[] files = dir.listFiles();
  if (files == null) return;
  for (File f : files) {
    if (!isSymLink(f) && f.isDirectory()) // just delete the symlink, don't follow it
      deleteDirectory(f, verbose, testRun);
    else {
      if (verbose)
        print((testRun ? "Would delete " : "Deleting ") + f.getAbsolutePath());
      if (!testRun)
        f.delete();
    }
  }
}


static Object callJavaX(String method, Object... args) {
  return callOpt(getJavaX(), method, args);
}

static ClassLoader getClassLoaderOrSame(Object o) {
  return o instanceof ClassLoader ? (ClassLoader) o : getClassLoader(o);
}

static void printShortException(Throwable e) {
  print(exceptionToStringShort(e));
}

static void printShortException(String s, Throwable e) {
  print(s, exceptionToStringShort(e));
}

static boolean java10OrHigher() {
  return parseFirstInt(javaVersion()) >= 10;
}

static boolean addDefaultVMOption(String option) {
  String s = defaultVMArgs(), old = s;
  if (!s.contains(option)) // rough
    s = trim(s + " " + option);
  if (eq(old, s)) return false;
  { setDefaultVMArgs(s); return true; }
}

static byte[] intToBytes(int i) {
  return new byte[] {
          (byte) (i >>> 24),
          (byte) (i >>> 16),
          (byte) (i >>> 8),
          (byte) i};
}

static void consoleClearInput() {
  consoleSetInput("");
}

static <A> A firstWithClassShortNamed(String shortName, Iterable<A> l) {
  if (l != null) for (A o : l)
    if (eq(shortClassName(o), shortName))
      return o;
  return null;
}

static <A> A firstWithClassShortNamed(String shortName, A[] l) {
  if (l != null) for (A o : l)
    if (eq(shortClassName(o), shortName))
      return o;
  return null;
}

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

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

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

static JMenuItem disableMenuItem(final JMenuItem mi) {
  if (mi != null) { swing(new Runnable() {  public void run() { try {  mi.setEnabled(false); 
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "mi.setEnabled(false);"; }}); }
  return mi;
}

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

static ActionListener actionListenerInNewThread(final Object runnable, final Object instanceToHold) {
  if (runnable instanceof ActionListener) return (ActionListener) runnable;
  return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
    startThread("Action Listener", new Runnable() {  public void run() { try {    
       AutoCloseable __1 = holdInstance(instanceToHold); try {
      callF(runnable);
    } finally { _close(__1); }
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "AutoCloseable __1 = holdInstance(instanceToHold); try {\r\n      callF(runnable..."; }});
  } catch (Throwable __e) { messageBox(__e); }}};
}

static JMenuItem directJMenuItem(Action a) {
  return new JMenuItem(a) {
    public Dimension getMaximumSize() {
      return new Dimension(super.getPreferredSize().width, super.getMaximumSize().height);
    }
  };
}

static JMenuItem directJMenuItem(String text, Object action) {
  return directJMenuItem(abstractAction(text, action));
}


static JMenuBar addMenuBar(final Component c) {
  return swing(new F0<JMenuBar>() { public JMenuBar get() { try { 
    RootPaneContainer f = getPossiblyInternalFrame(c);
    if (f == null) return null;
    JMenuBar bar =  (JMenuBar) (call(f, "getJMenuBar"));
    if (bar == null) {
      setMenuBar(f, bar = new JMenuBar());
      revalidate((Component) f);
    }
    return bar;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "RootPaneContainer f = getPossiblyInternalFrame(c);\r\n    if (f == null) null;\r..."; }});
}

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

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



static List<String> getJavaModifiers_list = litlist("static", "abstract", "public", "private", "protected", "final", "native", "volatile", "synchronized", "transient");

static List<String> getJavaModifiers() {
  return getJavaModifiers_list;
}

// 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 boolean checkTokCondition(Object condition, List<String> tok, int i) {
  if (condition instanceof TokCondition)
    return ((TokCondition) condition).get(tok, i);
  return checkCondition(condition, tok, i);
}

static TokCondition toTokCondition(ITokCondition condition) {
  return condition == null ? null : new TokCondition() {
    boolean get(List<String> tok, int i) {
      return condition.get(tok, i);
    }
  };
}





  static Map<String, String[]> javaTokForJFind_array_cache = synchronizedMRUCache(1000);


static String[] javaTokForJFind_array(String s) {
  String[] tok = javaTokForJFind_array_cache.get(s);
  if (tok == null)
    javaTokForJFind_array_cache.put(s, tok = codeTokensAsStringArray(jfind_preprocess(javaTok(s))));
  return tok;
}



static String[] codeTokensAsStringArray(List<String> tok) {
  int n = max(0, (l(tok)-1)/2);
  String[] out = new String[n];
  for (int i = 0; i < n; i++)
    out[i] = tok.get(i*2+1);
  return out;
}

// syntax 1: replace all occurrences of x in l with y
static <A> List<A> replaceSublist(List<A> l, List<A> x, List<A> y) {
  if (x == null) return l;
  
  int i = 0;
  while (true) {
    i = indexOfSubList(l, x, i);
    if (i < 0) break;
    
    replaceSublist(l, i, i+l(x), y);
    i += l(y);
  }
  return l;
}

// syntax 2: splice l at fromIndex-toIndex and replace middle part with y
static <A> List<A> replaceSublist(List<A> l, int fromIndex, int toIndex, List<A> y) {
  int n = y.size(), toIndex_new = fromIndex+n;
  if (toIndex_new < toIndex) {
    removeSubList(l, toIndex_new, toIndex);
    copyListPart(y, 0, l, fromIndex, n);
  } else {
    copyListPart(y, 0, l, fromIndex, toIndex-fromIndex);
    if (toIndex_new > toIndex)
      l.addAll(toIndex, subList(y, toIndex-fromIndex));
  }
  return l;
}



static Cache<Boolean> isLinux_cache = new Cache<>(() -> isLinux_load());
static boolean isLinux() { return isLinux_cache.get(); }

static Boolean isLinux_load() {
  return !isWindows() && !isMac() && !isAndroid();
}

static int randomID_defaultLength = 12;

static String randomID(int length) {
  return makeRandomID(length);
}

static String randomID(Random r, int length) {
  return makeRandomID(r, length);
}

static String randomID() {
  return randomID(randomID_defaultLength);
}

static String randomID(Random r) {
  return randomID(r, randomID_defaultLength);
}

static int globalIDLength() {
  return 16;
}

static List<File> filesEndingWith(File dir, String suffix) {
  return listFilesWithSuffix(dir, suffix);
}

static List<File> filesEndingWith(List<File> l, String suffix) {
  List<File> out = new ArrayList();
  for (File f : unnull(l))
    if (!f.isDirectory() && (empty(suffix) || endsWithIgnoreCase(f.getName(), suffix)))
      out.add(f);
  return out;
}

static List<File> filesEndingWith(String suffix, File dir) {
  return filesEndingWith(dir, suffix);
}

static String addPrefixIfNotEmpty2(String prefix, String s) {
  return empty(s) ? "" : addPrefix(prefix, s);
}

static Object[] asObjectArray(Collection l) {
  return toObjectArray(l);
}

static File toFile(Object o) {
  if (o instanceof File) return (File) o;
  if (o instanceof String) return new File((String) o);
  throw fail("Not a file: " + o);
}

static <T> void sort(T[] a, Comparator<? super T> c) {
  if (a != null) Arrays.sort(a, c);
}

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

static void sort(int[] a) { if (a != null) Arrays.sort(a); }

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

static void sort(List a) {
  if (a != null) Collections.sort(a);
}

static File getCanonicalFile(File f) { try {
  return f == null ? null : f.getCanonicalFile();
} catch (Exception __e) { throw rethrow(__e); } }


static boolean isSymLink(File f) {
  
  
  
  return f != null && Files.isSymbolicLink(toPath(f));
  
}

static ClassLoader getClassLoader(Object o) {
  return o == null ? null : _getClass(o).getClassLoader();
}

static int parseFirstInt(String s) {
  return parseInt(jextract("<int>", s));
}

static int parseFirstInt(Iterable<String> l) {
  return parseInt(firstIntegerString(l));
}

static String javaVersion() {
  return System.getProperty("java.version");
}

static String defaultVMArgs() {
  return javaxDefaultVMArgs();
}

static void setDefaultVMArgs(String args) {
  String oldArgs = javaxDefaultVMArgs();
  args = trim(args);
  if (neq(unnull(oldArgs), unnull(args))) {
    print();
    print("Changing default VM arguments from");
    print("  " + oldArgs);
    print("to");
    print("  " + args);
    print();
    saveTextFile(javaxDataDir("default-vm-args"), nullIfEmpty(args));
  }
}

static void consoleSetInput(final String text) {
  
    if (headless()) return;
    setTextAndSelectAll(consoleInputField(), text);
    focusConsole();
  
}

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

static AbstractAction abstractAction(String name, final Object runnable) {
  return new AbstractAction(name) {
    public void actionPerformed(ActionEvent evt) {
      pcallF(runnable);
    }
  };
}

static void setMenuBar(final JMenuBar mb, final RootPaneContainer f) {
  { swing(new Runnable() {  public void run() { try { 
    call(f, "setJMenuBar", mb);
    revalidate((Component) f);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "call(f, \"setJMenuBar\", mb);\r\n    revalidate((Component) f);"; }}); }
}

static void setMenuBar(RootPaneContainer f, JMenuBar mb) {
  setMenuBar(mb, f);
}



static 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 boolean checkCondition(Object condition, Object... args) {
  return isTrue(callF(condition, args));
}

static <A> boolean checkCondition(IF1<A, Boolean> condition, A arg) {
  return isTrue(callF(condition, arg));
}

static <A> int indexOfSubList(List<A> x, List<A> y) {
  return indexOfSubList(x, y, 0);
}

static <A> int indexOfSubList(List<A> x, List<A> y, int i) {
  outer: for (; i+l(y) <= l(x); i++) {
    for (int j = 0; j < l(y); j++)
      if (neq(x.get(i+j), y.get(j)))
        continue outer;
    return i;
  }
  return -1;
}

static <A> int indexOfSubList(List<A> x, A[] y, int i) {
  outer: for (; i+l(y) <= l(x); i++) {
    for (int j = 0; j < l(y); j++)
      if (neq(x.get(i+j), y[j]))
        continue outer;
    return i;
  }
  return -1;
}

static <A, B extends A> void copyListPart(List<B> a, int i1, List<A> b, int i2, int n) {
  if (a == null || b == null) return;
  for (int i = 0; i < n; i++)
    b.set(i2+i, a.get(i1+i));
}

  static boolean isMac() {
    return System.getProperty("os.name").toLowerCase().contains("mac");
	}

static List<File> listFilesWithSuffix(File dir, String suffix) {
  List<File> l = new ArrayList();
  for (File f : listFiles(dir))
    if (!f.isDirectory() && (empty(suffix) || endsWithIgnoreCase(f.getName(), suffix)))
      l.add(f);
  return l;
}

static String addPrefix(String prefix, String s) {
  return s.startsWith(prefix) ? s : prefix + s;
}



static Path toPath(File f) {
  return f == null ? null : f.toPath();
}

// returns from C to C
static String jextract(String pat, String s) {
  return jextract(pat, javaTok(s));
}

static String jextract(String pat, List<String> tok) {
  List<String> tokpat = javaTok(pat);
  jfind_preprocess(tokpat);
  int i = jfind(tok, tokpat);
  if (i < 0) return null;
  int j = i + l(tokpat) - 2;
  return joinSubList(tok, i, j);
}


static String firstIntegerString(Iterable<String> c) {
  Iterator<String> it = c.iterator();
  while (it.hasNext()) {
    String s = it.next();
    if (isInteger(s)) return s;
  }
  return null;
}

static String javaxDefaultVMArgs() {
  File fileNew, fileOld;
  String text = loadTextFile(fileNew = javaxDataDir("default-vm-args"));
  if (text == null) {
    text = loadTextFile(fileOld = programFile("#1005850", "default-vm-args"));
    if (text != null)
      moveFile(fileOld, fileNew);
  }
  return trim(unnull(text));
}

static JTextField setTextAndSelectAll(final JTextField tf, final String text) {
  if (tf != null) { swing(new Runnable() {  public void run() { try { 
    tf.setText(text);
    tf.selectAll();
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "tf.setText(text);\r\n    tf.selectAll();"; }}); }
  return tf;
}

static JTextField consoleInputField() {
  Object console = get(getJavaX(), "console");
  return (JTextField) getOpt(console, "tfInput");
}

static void focusConsole(String s) {
  setConsoleInput(s);
  focusConsole();
}

static void focusConsole() {
  JComponent tf = consoleInputFieldOrComboBox();
  if (tf != null) {
    //print("Focusing console");
    tf.requestFocus();
  }
}



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

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



static File programFile(String name) {
  return prepareProgramFile(name);
}

static File programFile(String progID, String name) {
  return prepareProgramFile(progID, name);
}

static void moveFile(File a, File b) {
  if (!renameFile(a, b))
    throw fail("File move failed: " + a + " to " + b);
}

static void setConsoleInput(String text) {
  consoleSetInput(text);
}

static JComponent consoleInputFieldOrComboBox() {
  Object console = get(getJavaX(), "console");
  JComboBox cb =  (JComboBox) (getOpt(console, "cbInput"));
  if (cb != null) return cb;
  return (JTextField) getOpt(console, "tfInput");
}



static File prepareProgramFile(String name) {
  return mkdirsForFile(getProgramFile(name));
}

static File prepareProgramFile(String progID, String name) {
  return mkdirsForFile(getProgramFile(progID, name));
}

static boolean renameFile(File a, File b) {
  mkdirsForFile(b);
  return a.renameTo(b);
}

static boolean renameFile(File a, String newName) {
  return renameFile(a, fileInSameDir(a, newName));
}



static File fileInSameDir(File f, String newName) {
  return newFile(parentFile(f), newName);
}



static File parentFile(File f) {
  return dirOfFile(f);
}



static File dirOfFile(File f) {
  return f == null ? null : f.getParentFile();
}



static interface IF2<A, B, C> {
  C get(A a, B b);
}static interface ITokCondition {
  boolean get(List<String> tok, int i); // i = N Index
}static abstract class TokCondition {
  abstract boolean get(List<String> tok, int i); // i = N Index
}static class Cache<A> {
  Object maker; // func -> A
  A value;
  long loaded;
  static boolean debug = false;
  long changeCount;
  Lock lock = lock();
  
  Cache() {}
  Cache(Object maker) {
  this.maker = maker;}
  Cache(IF0<A> maker) {
  this.maker = maker;}

  A get() {
    if (hasLock(lock)) return value; // Must be called from within maker
    Lock __0 = lock; lock(__0); try {
    if (loaded == 0) {
      value = make();
      changeCount++;
      loaded = sysNow();
    }
    return value;
  } finally { unlock(__0); } }

  void clear() {
    Lock __1 = lock; lock(__1); try {
    if (debug && loaded != 0)
      print("Clearing cache");
    value = null;
    changeCount++;
    loaded = 0;
  } finally { unlock(__1); } }

  // clear if older than x seconds
  // 0 does not do anything
  void clear(double seconds) {
    Lock __2 = lock; lock(__2); try {
    if (seconds != 0 && loaded != 0 && sysNow() >= loaded+seconds*1000)
      clear();
  } finally { unlock(__2); } }
  
  // override
  void set(A a) {
    Lock __3 = lock; lock(__3); try {
    value = a;
    ++changeCount;
    loaded = sysNow();
  } finally { unlock(__3); } }
  
  A make() {
    return (A) callF(maker);
  }
}

static boolean hasLock(Lock lock) {
  return ((ReentrantLock) lock).isHeldByCurrentThread();
}

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


}