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

class main {

static class OneColorTheoryChecker {
  
  
  ProbabilisticScheduler scheduler = new ProbabilisticScheduler();
  
  static class Theory {
    // values are: withProbability(strengthOfEvidence, probabilityOfTheory)
    MultiMap<String, WithProbability<Double>> examples = new MultiMap();
    double strengthSum, probabilitySum;
    
    double currentProbabilityGuess() {
      return doubleRatio(probabilitySum, strengthSum);
    }
    
    String renderProbabilityGuess() {
      return "Current probability guess (evidence count " + n2(l(examples)) + "): " + formatDouble3X(currentProbabilityGuess()) + " with strength " + formatDouble3(strengthSum);
    }
    
    boolean hasExampleNamed(String name) { return examples.containsKey(name); }
    
    void addEvidence(String desc, double probabilityOfTheory, double strengthOfEvidence) {
      examples.add(desc, withProbability(strengthOfEvidence, probabilityOfTheory));
      probabilitySum += probabilityOfTheory*strengthOfEvidence;
      strengthSum += strengthOfEvidence;
    }
    
    String toStringWithEvidence() {
      return toString() + "\n\n"
        + pnlToString("EVIDENCE", multiMapToPairs(examples));
    }
  }
  
  class OneColorTheory extends Theory implements IFieldsToList{
  String text;
  URecognizer.Cell cell;
  RGB color;
  OneColorTheory() {}
  OneColorTheory(String text, URecognizer.Cell cell, RGB color) {
  this.color = color;
  this.cell = cell;
  this.text = text;}

public boolean equals(Object o) {
if (!(o instanceof OneColorTheory)) return false;
    OneColorTheory __0 =  (OneColorTheory) o;
    return eq(text, __0.text) && eq(cell, __0.cell) && eq(color, __0.color);
}

  public int hashCode() {
    int h = -674300926;
    h = boostHashCombine(h, _hashCode(text));
    h = boostHashCombine(h, _hashCode(cell));
    h = boostHashCombine(h, _hashCode(color));
    return h;
  }
  public Object[] _fieldsToList() { return new Object[] {text, cell, color}; }

    public String toString() {
      return renderProbabilityGuess() + ": " + dollarVarsMeanFields(text, this);
    }
    
    OneColorTheory branch(Object... __) { return this; }
  }
  
  // create the theory object and initiate the reasoning
  // you have to step the scheduler afterwards to get results
  OneColorTheory makeTheory(URecognizer.Cell cell) {
    var color = cell.averageColor();

    var theory = new OneColorTheory("Color of every pixel in $cell is $color.", cell, color);
  
    testOneColorTheory(cell, theory);
    return theory;
  }

  void noteCellColor(URecognizer.Cell cell, OneColorTheory theory) {
    var desc = "Pixel check at " + cell;
    if (theory.hasExampleNamed(desc)) return;
    var strength = doubleRatio(cell.area(), theory.cell.area()); // how much do we have to say about the cell in the theory?
    var p = colorDistanceToProbability(cell.averageColor(), theory.color);
    addExampleToTheory(theory, desc, p, strength);
  }
  
  double colorDistanceToProbability(RGB col1, RGB col2) {
    double sim = colorSimilarity(col1, col2), sqr = sqr(sim);
    printFunctionCall("colorDistanceToProbability", "col1", col1, "col2", col2, "sim", sim, "sqr", sqr);
    return sqr;
  }
  
  void testOneColorTheory(URecognizer.Cell cell, OneColorTheory theory) {  
    noteCellColor(cell, theory);
  
    scheduler.atRelative(dontZoomTooFar(cell), new Runnable() {  public void run() { try { 
      for (var split : usefulSplits(cell))
        scheduler.atRelative(split.probability(), new Runnable() {  public void run() { try { 
          for (var cell : split.get())
            testOneColorTheory(cell, theory.branch("description" , "recursion to " + cell));
        
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "for (var cell : split.get())\r\n            testOneColorTheory(cell, theory.bra..."; }});
    
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "for (var split : usefulSplits(cell))\r\n        scheduler.atRelative(split.prob..."; }});
  }
  
  List<WithProbability<URecognizer.Cell[]>> usefulSplits(URecognizer.Cell cell) {
    return map(__21 -> withProbability1(__21), llNonNulls(cell.split(0, 2), cell.split(1, 2)));
  }
  
  // probability penalty .25 for zooming in 3 steps
  double dontZoomTooFar(URecognizer.Cell cell) {
    return 0.75;
  }
  
  void addExampleToTheory(Theory theory, String desc, double probabilityOfTheory, double strengthOfEvidence) {
    theory.addEvidence(desc, probabilityOfTheory, /* scheduler.currentProbability()* */ strengthOfEvidence);
  }
}
static double doubleRatio(double x, double y) {
  return y == 0 ? 0 : x/y;
}


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

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

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

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

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

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

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

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

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

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

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




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

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

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



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











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








static String formatDouble3X(double d) {
  return formatDoubleX(d, 3);
}



static String formatDouble3(double d) {
  return formatDouble(d, 3);
}



static <A> WithProbability<A> withProbability(double probability, A a) {
  return new WithProbability(probability, a);
}


static String toString(Object o) {
  return strOrNull(o);
}


static <A> String pnlToString(String prefix, Iterable<A> l) {
  return hijackPrint(new Runnable() {  public void run() { try {  pnl(prefix, l) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "pnl(prefix, l)"; }});
}

static <A> String pnlToString(final Iterable<A> l) {
  return hijackPrint(new Runnable() {  public void run() { try {  pnl(l) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "pnl(l)"; }});
}

static <A> String pnlToString(final A[] l) {
  return hijackPrint(new Runnable() {  public void run() { try {  pnl(l) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "pnl(l)"; }});
}

static <A, B> String pnlToString(final Map<A, B> map) {
  return hijackPrint(new Runnable() {  public void run() { try {  pnl(map) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "pnl(map)"; }});
}


static <A, B> String pnlToString(MultiMap<A, B> map) {
  return pnlToString(multiMapToMap(map));
}



static <A, B> List<Pair<A, B>> multiMapToPairs(MultiMap<A, B> mm) {
  List<Pair<A, B>> out = new ArrayList();
  for (A key : keys(mm))
    for (B value : mm.get(key))
      out.add(pair(key, value));
  return out;
}


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




static int boostHashCombine(int a, int b) {
  return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));
}


static int _hashCode(Object a) {
  return a == null ? 0 : a.hashCode();
}


static String dollarVarsMeanFields(String text, Object object) {
  return replaceDollarVars(text, var ->
    !hasFieldNamed(object, var) ? null : str(getOpt(object, var)));
}


static float colorSimilarity(RGB a, RGB b) {
  return 1-colorDistance(a, b);
}

// 0xRRGGBB - result is between 0 and 1
static float colorSimilarity(int a, int b) {
  return 1-colorDistance(a, b);
}


static int sqr(int i) {
  return i*i;
}

static long sqr(long l) {
  return l*l;
}

static double sqr(double d) {
  return d*d;
}

static float sqr(float f) {
  return f*f;
}


static void printFunctionCall(String fname, Object... args) {
  print(formatFunctionCall(fname, args));
}


static 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 List map(Iterable l, Object f) { return map(f, l); }

static List map(Object f, Iterable l) {
  List x = emptyList(l);
  if (l != null) for  (Object o : l)
    { ping(); x.add(callF(f, o)); }
  return x;
}


  static <A, B> List<B> map(Iterable<A> l, F1<A, B> f) { return map(f, l); }

  static <A, B> List<B> map(F1<A, B> f, Iterable<A> l) {
    List x = emptyList(l);
    if (l != null) for  (A o : l)
      { ping(); x.add(callF(f, o)); }
    return x;
  }


static <A, B> List<B> map(IF1<A, B> f, Iterable<A> l) { return map(l, f); }
static <A, B> List<B> map(Iterable<A> l, IF1<A, B> f) {
  List x = emptyList(l);
  if (l != null) for  (A o : l)
    { ping(); x.add(f.get(o)); }
  return x;
}
  
static <A, B> List<B> map(IF1<A, B> f, A[] l) { return map(l, f); }
static <A, B> List<B> map(A[] l, IF1<A, B> f) {
  List x = emptyList(l);
  if (l != null) for  (A o : l)
    { ping(); x.add(f.get(o)); }
  return x;
}
  
static List map(Object f, Object[] l) { return map(f, asList(l)); }
static List map(Object[] l, Object f) { return map(f, l); }

static List map(Object f, Map map) {
  return map(map, f);
}

// map: func(key, value) -> list element
static List map(Map map, Object f) {
  List x = new ArrayList();
  if (map != null) for  (Object _e : map.entrySet()) { ping(); 
    Map.Entry e = (Map.Entry) _e;
    x.add(callF(f, e.getKey(), e.getValue()));
  }
  return x;
}

static <A, B, C> List<C> map(Map<A, B> map, IF2<A, B, C> f) {
  return map(map, (Object) f);
}


static <A> WithProbability<A> withProbability1(A a) {
  return new WithProbability(1, a);
}


static <A> List<A> llNonNulls(A... a) {
  List<A> l = new ArrayList();
  for (A x : a) if (x != null) l.add(x);
  return l;
}




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


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

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

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


static String formatDoubleX(double d, int digits) {
  return formatDoubleFull(d, digits);
}


static String formatDouble(double d, int digits) {
  String format = digits <= 0 ? "0" : "0." + rep(digits, '#');
  return decimalFormatEnglish(format, d);
}



static String strOrNull(Object o) {
  return o == null ? null : str(o);
}


static String hijackPrint(Runnable r) {
  return hijackPrint((Object) r);
}

static String hijackPrint(Object r) {
  final StringBuilder buf = new StringBuilder();
  Object old = interceptPrintInThisThread(new F1<String, Boolean>() {
    public Boolean get(String s) {
      buf.append(s);
      return false;
    }
  });
  try {
    callF(r);
    return str(buf);
  } finally {
    interceptPrintInThisThread(old);
  }
}


static <A extends Iterable> A pnl(A l) { return pnl("", l); }
static <A extends Iterable> A pnl(String prefix, A l) {
  printNumberedLines(prefix, l);
  return l;
}

static <A> A[] pnl(A[] l) { return pnl("", l); }
static <A> A[] pnl(String prefix, A[] l) {
  printNumberedLines(prefix, l);
  return l;
}

static <A extends Map> A pnl(A map) {
  printNumberedLines(map);
  return map;
}

static <A extends Map> A pnl(String prefix, A map) {
  printNumberedLines(prefix, map);
  return map;
}

static String pnl(String s) {
  printNumberedLines(lines(s));
  return s;
}




static <A, B> MultiMap<A, B> pnl(MultiMap<A, B> mm) {
  pnl(mm == null ? null : mm.asMap());
  return mm;
}



static <A, B> Map<A, List<B>> multiMapToMap(MultiMap<A, B> m) {
  return m == null ? null : m.data;
}


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

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




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







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

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


static String replaceDollarVars(String s, Object... params) {
  if (empty(params)) return s;
  Map<String, Object> vars = mapKeys(__22 -> dropDollarPrefix(__22), (Map<String, Object>) litcimap(params));
  return replaceDollarVars_dyn(s, var -> strOrNull(vars.get(var)));
}

static String replaceDollarVars(String s, IF1<String, String> f) {
  return replaceDollarVars_dyn(s, f);
}


static boolean hasFieldNamed(Object o, String field) {
  return hasField(o, field);
}


static 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 float colorDistance(RGB a, RGB b) {
  return rgbDiff(a, b);
}



// 0xRRGGBB - result is between 0 and 1
static float colorDistance(int a, int b) {
  return rgbDiff(a, b);
}


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




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

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

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

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

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

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

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

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

  print_raw(s);
}

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

static void print_autoRotate() {
  
}


static String formatFunctionCall(String fname, Object... args) {
  return fname + "(" + joinWithComma(allToString(args)) + ")";
}

static String formatFunctionCall(String fname, List args) {
  return formatFunctionCall(fname, toObjectArray(args));
}


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


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





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

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

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

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



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


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



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



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



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





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



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


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

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

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

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


// unclear semantics as to whether return null on null

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

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

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

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

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

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

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

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



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






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




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 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 String formatDoubleFull(double d, int digits) {
  String format = digits <= 0 ? "0" : "0." + rep(digits, '0');
  return new java.text.DecimalFormat(format, new java.text.DecimalFormatSymbols(Locale.ENGLISH)).format(d);
}



static String rep(int n, char c) {
  return repeat(c, n);
}

static String rep(char c, int n) {
  return repeat(c, n);
}

static <A> List<A> rep(A a, int n) {
  return repeat(a, n);
}

static <A> List<A> rep(int n, A a) {
  return repeat(n, a);
}



static String decimalFormatEnglish(String format, double d) {
  return decimalFormatEnglish(format).format(d);
}

static java.text.DecimalFormat decimalFormatEnglish(String format) {
  return new java.text.DecimalFormat(format, new java.text.DecimalFormatSymbols(Locale.ENGLISH));
}


// f can return false to suppress regular printing
// call print_raw within f to actually print something
// f preferrably is F1<S, Bool>
static Object interceptPrintInThisThread(Object f) {
  Object old = print_byThread().get();
  print_byThread().set(f);
  return old;
}


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

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

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

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

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

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

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

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

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

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

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

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

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

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


/*static <A> L<A> printNumberedLines(L<A> l) {
  printNumberedLines((Collection<A>) l);
  ret l;
}

static <A> L<A> printNumberedLines(S prefix, L<A> l) {
  printNumberedLines(prefix, (Collection<A>) l);
  ret l;
}*/

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

static void printNumberedLines(String prefix, Map map) {
  printNumberedLines(prefix, mapToLines(map));
}

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

static <A extends Iterable> A printNumberedLines(String prefix, A l) {
  int i = 0;
  if (l != null) for (Object a : l) print(prefix + (++i) + ". " + str(a));
  return l;
}

static void printNumberedLines(Object[] l) { printNumberedLines("", l); }
static void printNumberedLines(String prefix, Object[] l) {
  printNumberedLines(prefix, asList(l));
}

static void printNumberedLines(Object o) {
  printNumberedLines(lines(str(o)));
}


static String lines(Iterable lines) { return fromLines(lines); }
static String lines(Object[] lines) { return fromLines(asList(lines)); }
static List<String> lines(String s) { return toLines(s); }

// convenience map call
static <A> String lines(Iterable<A> l, IF1<A, String> f) {
  return mapToLines(l, f);
}


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


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


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

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




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


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










static Map mapKeys(Object func, Map map) {
  Map m = similarEmptyMap(map); // TODO: this might break when key type changes through func
  for (Object key : keys(map))
    m.put(callF(func, key), map.get(key));
  return m;
}

static Map mapKeys(Map map, Object func) {
  return mapKeys(func, map);
}

static <A, B, C> Map<B, C> mapKeys(Map<A, C> map, IF1<A, B> func) {
  return mapKeys(map, (Object) func);
}

static <A, B, C> Map<B, C> mapKeys(IF1<A, B> func, Map<A, C> map) {
  return mapKeys(map, func);
}


static String dropDollarPrefix(String s) {
  return dropPrefix("$", s);
}


static TreeMap litcimap(Object... x) {
  return litCIMap(x);
}


// f takes variable without $ sign. if it returns null, variable is kept
static String replaceDollarVars_dyn(String s, IF1<String, String> f) {
  if (f == null) return s;
  return regexpReplaceIC(s, "\\$(\\w+)", matcher -> {
    String var = matcher.group(1);
    String val = f.get(var);
    return val == null ? matcher.group() : str(val);
  });
}


static boolean hasField(Object o, String field) {
  return findField2(o, field) != null;
}


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

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

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

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

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

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

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

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

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


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


static 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 float rgbDiff(RGB a, RGB b) {
  return (float) (Math.abs(a.r-b.r) + Math.abs(a.g-b.g) + Math.abs(a.b-b.b))/3;
}

// 0xRRGGBB - result is between 0 and 1
static float rgbDiff(int a, int b) {
  int r1 = (a >> 16) & 0xFF;
  int g1 = (a >> 8) & 0xFF;
  int b1 = a & 0xFF;
  int r2 = (b >> 16) & 0xFF;
  int g2 = (b >> 8) & 0xFF;
  int b2 = b & 0xFF;
  return (Math.abs(r1-r2) + Math.abs(g1-g2) + Math.abs(b1-b2))/(3f*255);
}


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


static void ping_okInCleanUp() {

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

}


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

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

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


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


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


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

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

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


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


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


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

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


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


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

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


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



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


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> 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 boolean isTrue(Object o) {
  if (o instanceof Boolean)
    return ((Boolean) o).booleanValue();
  if (o == null) return false;
  if (o instanceof ThreadLocal) // TODO: remove this
    return isTrue(((ThreadLocal) o).get());
  throw fail(getClassName(o));
}

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


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


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


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


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


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



static <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 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 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 final Map<Class, _MethodCache> callOpt_cache = newDangerousWeakHashMap();

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

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

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


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


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


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

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


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 Object getOptDynOnly(DynamicObject o, String field) {
  if (o == null || o.fieldValues == null) return null;
  return o.fieldValues.get(field);
}


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


static List<String> mapToLines(Map map) {
  List<String> l = new ArrayList();
  for (Object key : keys(map))
    l.add(str(key) + " = " + str(map.get(key)));
  return l;
}

static String mapToLines(Map map, Object f) {
  return lines(map(map, f));
}

static String mapToLines(Object f, Map map) {
  return lines(map(map, f));
}

static String mapToLines(Object f, Iterable l) {
  return lines(map(f, l));
}

static <A> String mapToLines(Iterable<A> l, IF1<A, String> f) {
  return mapToLines((Object) f, l);
}

static <A> String mapToLines(IF1<A, String> f, Iterable<A> l) {
  return mapToLines((Object) f, l);
}

static <A, B> String mapToLines(Map<A, B> map, IF2<A, B, String> f) {
  return lines(map(map, f));
}


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

static String fromLines(String... lines) {
  return fromLines(asList(lines));
}


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

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

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

    start = i;
  }
  return lines;
}

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


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


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

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


static Map similarEmptyMap(Map m) {
  if (m instanceof TreeMap) return new TreeMap(((TreeMap) m).comparator());
  if (m instanceof LinkedHashMap) return new LinkedHashMap();
  
  // default to a hash map
  return new HashMap();
}

static Map similarEmptyMap(Iterable m) {
  if (m instanceof TreeSet) return new TreeMap(((TreeSet) m).comparator());
  if (m instanceof LinkedHashSet) return new LinkedHashMap();
  
  return new HashMap();
}


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


static TreeMap litCIMap(Object... x) {
  TreeMap map = caseInsensitiveMap();
  litmap_impl(map, x);
  return map;
}


// f : Matcher -> S
static String regexpReplaceIC(String s, String pat, Object f) {
  return regexReplaceIC(s, pat, f);
}

static String regexpReplaceIC(String s, String pat, String replacement) {
  return regexReplaceIC(s, pat, replacement);
}

static String regexpReplaceIC(String s, String pat, IF1<Matcher, String> f) {
  return regexReplaceIC(s, pat, f);
}


static Field findField2(Object o, String field) {
  Class c = o.getClass();
  HashMap<String, Field> map;
  synchronized(getOpt_cache) {
    map = getOpt_cache.get(c);
    if (map == null)
      map = getOpt_makeCache(c);
  }
  
  if (map == getOpt_special) {
    if (o instanceof Class)
      return findField2_findStaticField((Class) o, field);
  }
    
  return map.get(field);
}

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


static void 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 Class<?> _getClass(String name) {
  try {
    return Class.forName(name);
  } catch (ClassNotFoundException e) {
    return null; // could optimize this
  }
}

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

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


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

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


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


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

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


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


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


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

static PersistableThrowable lastException() {
  return lastException_lastException;
}

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


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

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

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


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

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

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

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

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

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

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

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

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

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


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


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


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


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

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


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

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


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

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


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

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

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

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

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

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

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


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


//ifclass Symbol



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


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


static Class __javax;

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


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 int isAndroid_flag;

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



static Boolean isHeadless_cache;

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


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

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


static volatile boolean licensed_yes = true;

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

static void licensed_off() {
  licensed_yes = false;
}


static 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 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 <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 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 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 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> TreeMap<String, A> caseInsensitiveMap() {
  return new TreeMap(caseInsensitiveComparator());
}


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

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


// f : Matcher -> S
static String regexReplaceIC(String s, String pat, Object f) {
  return regexReplace(regexpMatcherIC(pat, s), f);
}

static String regexReplaceIC(String s, String pat, String replacement) {
  return regexpReplaceIC_direct(s, pat, replacement);
}


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

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

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

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

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


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

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



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

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


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



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


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


static 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 <A> HashSet<A> litset(A... items) {
  return lithashset(items);
}


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


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

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


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


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


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

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


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


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



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




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


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

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


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


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

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

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


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



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


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






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




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


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


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

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


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


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



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 in == null ? null : bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in));
} catch (Exception __e) { throw rethrow(__e); } }

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


static GZIPInputStream newGZIPInputStream(File f) {
  return gzInputStream(f);
}

static GZIPInputStream newGZIPInputStream(InputStream in) {
  return gzInputStream(in);
}


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 Comparator<String> caseInsensitiveComparator() {
  
  
  return betterCIComparator();
  
}


// f : Matcher -> S
static String regexReplace(String s, String pat, Object f) {
  Matcher m = Pattern.compile(pat).matcher(s);
  return regexReplace(m, f);
}

static String regexReplace(String s, String pat, String replacement) {
  return regexpReplace_direct(s, pat, replacement);
}

static String regexReplace(Matcher m, Object f) {
  StringBuffer buf = new StringBuffer();
  while (m.find())
    m.appendReplacement(buf, m.quoteReplacement(str(callF(f, m))));
  m.appendTail(buf);
  return str(buf);
}

static String regexReplace(String s, String pat, IF1<Matcher, String> f) {
  return regexReplace(s, pat, (Object) f);
}


static Matcher regexpMatcherIC(String pat, String s) {
  return compileRegexpIC(pat).matcher(unnull(s));
}


static String regexpReplaceIC_direct(String s, String pat, String replacement) {
  Matcher m = regexpIC(pat, s);
  StringBuffer buf = new StringBuffer();
  while (m.find())
    m.appendReplacement(buf, replacement);
  m.appendTail(buf);
  return str(buf);
}


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


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


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



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

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


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


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


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


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

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


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


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




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


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


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


static Throwable _storeException_value;

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


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


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


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


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


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



static BufferedReader bufferedReader(Reader r) { return bufferedReader(r, 8192); }
static BufferedReader bufferedReader(Reader r, int bufSize) {
  if (r == null) return null;
  return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r, bufSize), r);
}


static <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 betterCIComparator_C betterCIComparator_instance;

static betterCIComparator_C betterCIComparator() {
  if (betterCIComparator_instance == null)
    betterCIComparator_instance = new betterCIComparator_C();
  return betterCIComparator_instance;
}

final static class betterCIComparator_C implements Comparator<String> {
  public int compare(String s1, String s2) {
    if (s1 == null) return s2 == null ? 0 : -1;
    if (s2 == null) return 1;
  
    int n1 = s1.length();
    int n2 = s2.length();
    int min = Math.min(n1, n2);
    for (int i = 0; i < min; i++) {
        char c1 = s1.charAt(i);
        char c2 = s2.charAt(i);
        if (c1 != c2) {
            c1 = Character.toUpperCase(c1);
            c2 = Character.toUpperCase(c2);
            if (c1 != c2) {
                c1 = Character.toLowerCase(c1);
                c2 = Character.toLowerCase(c2);
                if (c1 != c2) {
                    // No overflow because of numeric promotion
                    return c1 - c2;
                }
            }
        }
    }
    return n1 - n2;
  }
}


static String regexpReplace_direct(String s, String pat, String replacement) {
  Matcher m = regexp(pat, s);
  return regexpReplace_direct(m, replacement);
}
  
static String regexpReplace_direct(Matcher m, String replacement) {
  StringBuffer buf = new StringBuffer();
  while (m.find())
    m.appendReplacement(buf, replacement);
  m.appendTail(buf);
  return str(buf);
}


static Map<String, java.util.regex.Pattern> compileRegexpIC_cache = syncMRUCache(10);

static java.util.regex.Pattern compileRegexpIC(String pat) {
  java.util.regex.Pattern p = compileRegexpIC_cache.get(pat);
  if (p == null) {
    
    try {
      compileRegexpIC_cache.put(pat, p = java.util.regex.Pattern.compile(pat, Pattern.CASE_INSENSITIVE));
    } catch (PatternSyntaxException e) {
      throw rethrow(wrapPatternSyntaxException(e));
    }
  }
  return p;
}


static Matcher regexpIC(Pattern pat, String s) {
  return pat.matcher(unnull(s));
}

static Matcher regexpIC(String pat, String s) {
  return compileRegexpIC(pat).matcher(unnull(s));
}

static Pattern regexpIC(String pat) {
  return compileRegexpIC(pat);
}


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


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 int strL(String s) {
  return s == null ? 0 : s.length();
}


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


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


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



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


static Map vm_generalMap_map;

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


static <A, B> B mapPutOrRemove(Map<A, B> map, A key, B value) {
  if (map != null && key != null)
    if (value != null) return map.put(key, value);
    else return map.remove(key);
  return null;
}


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

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


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




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


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


static 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> syncMRUCache(int size) {
  return synchroMap(new MRUCache(size));
}


static RuntimeException wrapPatternSyntaxException(PatternSyntaxException e) {
  if (e == null) return null;
  String pat = e.getPattern();
  int i = e.getIndex();
  return new RuntimeException("Regular expression error between " + multiLineQuoteWithSpaces(substring(pat, 0, i)) + " and " + multiLineQuoteWithSpaces(substring(pat, i)) + " - " + e.getMessage());
}


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


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


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





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 multiLineQuoteWithSpaces(String s) {
  return multiLineQuote(" " + s + " ");
}




static String multiLineQuote(String s) {
  for (int i = 0; ; i++) {
    String closer = "]" + rep('=', i) + "]";
    if (!contains(s, closer))
      return "[" + rep('=', i) + "[" + s + closer;
  }
}




static boolean contains(Collection c, Object o) {
  return c != null && c.contains(o);
}

static boolean contains(Object[] x, Object o) {
  if (x != null)
    for (Object a : x)
      if (eq(a, o))
        return true;
  return false;
}

static boolean contains(String s, char c) {
  return s != null && s.indexOf(c) >= 0;
}

static boolean contains(String s, String b) {
  return s != null && s.indexOf(b) >= 0;
}

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






static interface IResourceHolder {
  <A extends AutoCloseable> A add(A a);
}
// immutable, has strong refs
// Do not run in a synchronized block - it goes wrong in the presence
// of elaborate classloaders (like in Gazelle BEA)
// see #1102990 and #1102991
final static class _MethodCache {
  final Class c;
  final HashMap<String, List<Method>> cache = new HashMap();
  
  _MethodCache(Class c) {
  this.c = c; _init(); }
  
  void _init() {
    Class _c = c;
    while (_c != null) {
      for (Method m : _c.getDeclaredMethods())
        if (!isAbstract(m) && !reflection_isForbiddenMethod(m))
          multiMapPut(cache, m.getName(), makeAccessible(m));
      _c = _c.getSuperclass();
    }
    
    // add default methods - this might lead to a duplication
    // because the overridden method is also added, but it's not
    // a problem except for minimal performance loss.
    for (Class intf : allInterfacesImplementedBy(c))
      for (Method m : intf.getDeclaredMethods())
        if (m.isDefault() && !reflection_isForbiddenMethod(m))
          multiMapPut(cache, m.getName(), makeAccessible(m));

    
  }
  
  // Returns only matching methods
  Method findMethod(String method, Object[] args) { try {
    List<Method> m = cache.get(method);
    
    if (m == null) return null;
    int n = m.size();
    for (int i = 0; i < n; i++) {
      Method me = m.get(i);
      if (call_checkArgs(me, args, false))
        return me;
    }
    return null;
  } catch (Exception __e) { throw rethrow(__e); } }
  
  Method findStaticMethod(String method, Object[] args) { try {
    List<Method> m = cache.get(method);
    if (m == null) return null;
    int n = m.size();
    for (int i = 0; i < n; i++) {
      Method me = m.get(i);
      if (isStaticMethod(me) && call_checkArgs(me, args, false))
        return me;
    }
    return null;
  } catch (Exception __e) { throw rethrow(__e); } }
}
static abstract class VF1<A> implements IVF1<A> {
  public abstract void get(A a);
}
static class 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 abstract class F0<A> {
  abstract A get();
}
static abstract class F1<A, B> {
  abstract B get(A a);
}
// you still need to implement hasNext() and next()
static abstract class IterableIterator<A> implements Iterator<A>, Iterable<A> {
  public Iterator<A> iterator() {
    return this;
  }
  
  public void remove() {
    unsupportedOperation();
  }
}
static class RGB {
  public float r, g, b; // can't be final cause persistence
  
  RGB() {}
  
  public RGB(float r, float g, float b) {
    this.r = r;
    this.g = g;
    this.b = b;
  }

  public RGB(double r, double g, double b) {
    this.r = (float) r;
    this.g = (float) g;
    this.b = (float) b;
  }
  
  public RGB(double[] rgb) {
    this(rgb[0], rgb[1], rgb[2]);
  }

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

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

  // TODO: 3-char version
  public RGB(String hex) {
    int i = l(hex)-6;
    r = Integer.parseInt(hex.substring(i, i+2), 16)/255f;
    g = Integer.parseInt(hex.substring(i+2, i+4), 16)/255f;
    b = Integer.parseInt(hex.substring(i+4, i+6), 16)/255f;
  }

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

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

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

  int asInt() { return getColor().getRGB() & 0xFFFFFF; }
  int getInt() { return getColor().getRGB() & 0xFFFFFF; }
  int asIntWithAlpha() { return rgbInt(redInt(), greenInt(), blueInt()) | 0xFF000000; }

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

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

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

    RGB rgb = (RGB) o;

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

    return true;
  }

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

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

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

  public String toString() {
    return getHexString();
  }
  
  int redInt() { return iround(r*255); }
  int greenInt() { return iround(g*255); }
  int blueInt() { return iround(b*255); }
}
// 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 class MultiMap<A,B> {
  Map<A, List<B>> data = new HashMap<A, List<B>>();
  
  MultiMap() {}
  MultiMap(boolean useTreeMap) { if (useTreeMap) data = new TreeMap(); }
  MultiMap(MultiMap<A, B> map) { putAll(map); }
  MultiMap(Map<A, List<B>> data) {
  this.data = data;}

  void put(A key, B value) { synchronized(data) {
    List<B> list = data.get(key);
    if (list == null)
      data.put(key, list = _makeEmptyList());
    list.add(value);
  }}

  void add(A key, B value) { put(key, value); }

  void addAll(A key, Collection<B> values) { putAll(key, values); }
  
  void addAllIfNotThere(A key, Collection<B> values) { synchronized(data) {
    for (B value : values)
      setPut(key, value);
  }}
  
  void setPut(A key, B value) { synchronized(data) {
    if (!containsPair(key, value))
      put(key, value);
  }}
  
  boolean containsPair(A key, B value) { synchronized(data) {
    return get(key).contains(value);
  }}
  
  void putAll(Collection<A> keys, B value) { synchronized(data) {
    for (A key : unnullForIteration(keys))
      put(key, value);
  }}

  void putAll(A key, Collection<B> values) { synchronized(data) {
    if (nempty(values)) getActual(key).addAll(values);
  }}

  void putAll(Iterable<Pair<A, B>> pairs) { synchronized(data) {
    for (Pair<A, B> p : unnullForIteration(pairs))
      put(p.a, p.b);
  }}
  
  void removeAll(A key, Collection<B> values) { synchronized(data) {
    for (B value : values)
      remove(key, value);
  }}
  
  List<B> get(A key) { synchronized(data) {
    List<B> list = data.get(key);
    return list == null ? Collections.<B> emptyList() : list;
  }}

  List<B> getOpt(A key) { synchronized(data) {
    return data.get(key);
  }}

  // returns actual mutable live list
  // creates the list if not there
  List<B> getActual(A key) { synchronized(data) {
    List<B> list = data.get(key);
    if (list == null)
      data.put(key, list = _makeEmptyList());
    return list;
  }}
 
  void clean(A key) { synchronized(data) {
    List<B> list = data.get(key);
    if (list != null && list.isEmpty())
      data.remove(key);
  }}

  Set<A> keySet() { synchronized(data) {
    return data.keySet();
  }}

  Set<A> keys() { synchronized(data) {
    return data.keySet();
  }}

  void remove(A key) { synchronized(data) {
    data.remove(key);
  }}

  void remove(A key, B value) { synchronized(data) {
    List<B> list = data.get(key);
    if (list != null) {
      list.remove(value);
      if (list.isEmpty())
        data.remove(key);
    }
  }}

  void clear() { synchronized(data) {
    data.clear();
  }}

  boolean containsKey(A key) { synchronized(data) {
    return data.containsKey(key);
  }}

  B getFirst(A key) { synchronized(data) {
    List<B> list = get(key);
    return list.isEmpty() ? null : list.get(0);
  }}
  
  void addAll(MultiMap<A, B> map) { putAll(map); }
  
  void putAll(MultiMap<A, B> map) { synchronized(data) {
    for (A key : map.keySet())
      putAll(key, map.get(key));
  }}
  
  void putAll(Map<A, B> map) { synchronized(data) {
    if (map != null) for (Map.Entry<A, B> e : map.entrySet())
      put(e.getKey(), e.getValue());
  }}
  
  int keysSize() { synchronized(data) { return l(data); }}
  
  // full size - note: expensive operation
  int size() { synchronized(data) {
    int n = 0;
    for (List l : data.values())
      n += l(l);
    return n;
  }}
  
  // expensive operation
  List<A> reverseGet(B b) { synchronized(data) {
    List<A> l = new ArrayList();
    for (A key : data.keySet())
      if (data.get(key).contains(b))
        l.add(key);
    return l;
  }}
  
  Map<A, List<B>> asMap() { synchronized(data) {
    return cloneMap(data);
  }}
  
  boolean isEmpty() { synchronized(data) { return data.isEmpty(); }}
  
  // override in subclasses
  List<B> _makeEmptyList() {
    return new ArrayList();
  }
  
  // returns live lists
  Collection<List<B>> allLists() {
    synchronized(data) {
      return new ArrayList(data.values());
    }
  }
  Collection<List<B>> values() { return allLists(); }
  
  List<B> allValues() {
    return concatLists(data.values());
  }
  
  Object mutex() { return data; }
  
  public String toString() { return "mm" + str(data); }
}
static abstract class CloseableIterableIterator<A> extends IterableIterator<A> implements AutoCloseable {
  public void close() throws Exception {}
}
static class ProbabilisticScheduler implements IProbabilisticScheduler, Steppable {
  TreeSetWithDuplicates < Entry > entries = new TreeSetWithDuplicates<>(byProbability());

  long stepCount;
  boolean verbose = false;
  
  // must be >= 0. probability 0 is never executed
  double cutoffProbabilityOnAdd = 0;
  double cutoffProbabilityOnExecute = 0;
  
  Comparator<Entry> byProbability() { return (a, b) -> cmp(b.probability, a.probability); }
  
  ThreadLocal<Double> threadProbability = new ThreadLocal();
  
  static class Entry {
  Entry() {}
    double probability;
    Runnable action;
    
    Entry(double probability, Runnable action) {
  this.action = action;
  this.probability = probability;}
    
    public void run() { action.run(); }

    public String toString() {
      return str(new WithProbability(probability, action));
    }
  }
  
  public void at(double probability, Runnable action) { add(probability, action); }
public void add(double probability, Runnable action) {
    if (action == null) return;
    if (probability <= cutoffProbabilityOnAdd) return;
    entries.add(new Entry(probability, action));
  }
  
  public boolean step() {
    return stepFirstUnstepped();
  }
  
  Entry nextSteppable() {
    Entry s = first(entries);
    if (s != null && s.probability <= cutoffProbabilityOnExecute) return null;
    return s;
  }
  
  // returns false when done stepping
  boolean stepFirstUnstepped() {
    Entry s = nextSteppable(); if (s == null) return false;
    if (verbose) print("Current scheduler probability: " + s.probability);
    entries.remove(s);
    ++stepCount;
     AutoCloseable __1 = tempSetTL(threadProbability, s.probability); try {
    s.run();
    return true;
  } finally { _close(__1); }}
  
  void reset() {
    entries.clear();
  }

  public void run() {
    stepAll(this);
  }
  
  void run(int maxSteps) {
    stepMax(maxSteps, this);
  }

  void printStats() {
    Entry first = entries.first(), last = entries.last();
    Entry next = nextSteppable();
    print("ProbabilisticScheduler. "
      + nEntries(entries)
      + ", highest probability in queue: " + (first == null ? "-" : first.probability)
      + ", lowest probability in queue: " + (last == null ? "-" : last.probability)
      + ", cutoff probability: " + cutoffProbabilityOnAdd + "/" + cutoffProbabilityOnExecute
      + ", " + (next == null ? "done" : "next step: " + next.action));
  }
  
  // Get probability of this thread's Runnable.
  // Or 1.0 when we are coming from "outside" (so you don't _have_ to
  // run your first step through the scheduler).
  public double current() { return currentProbability(); }
public double currentProbability() {
    return or(threadProbability.get(), 1.0);
  }
  
  IProbabilisticScheduler freeze() {
    double prob = currentProbability();
    return new IProbabilisticScheduler() {
      public void at(double probability, Runnable action) {
        ProbabilisticScheduler.this.at(prob*probability, action);
      }
      
      public double currentProbability() {
        return prob;
      }
      
      public long stepCount() { return stepCount; }
    };
  }
  
  double remainingProbability() {
    Entry s = nextSteppable();
    return s == null ? 0.0 : s.probability;
  }
  
  public long stepCount() { return stepCount; }
}
static interface IFieldsToList {
  Object[] _fieldsToList();
}
static interface IF2<A, B, C> {
  C get(A a, B b);
}

static interface IF1<A, B> {
  B get(A a);
}
static class PersistableThrowable extends DynamicObject {
  String className;
  String msg;
  String stacktrace;
  
  PersistableThrowable() {}
  PersistableThrowable(Throwable e) {
    if (e == null)
      className = "Crazy Null Error";
    else {
      className = getClassName(e).replace('/', '.');
      msg = e.getMessage();
      stacktrace = getStackTrace_noRecord(e);
    }
  }
  
  public String toString() {
    return nempty(msg) ? className + ": " + msg : className;
  }
}
// U for stands for the "Ultra-Fast Recognition" family of recognizers
static class URecognizer {
  IIntegralImage image;
  
  URecognizer() {}
  URecognizer(IIntegralImage image) {
  this.image = image;}
  URecognizer(BufferedImage image) {
    this.image = new IntegralImage(image);
  }
  
  // returns 0, 1 or 2
  int posterizeToInt(double x) {
    return ifloor(clampZeroToOne(x)*3);
  }

  // returns 0, .5 or 1
  double posterizeInPlace(double x) {
    return posterizeToInt(x)*.5;
  }
  
  class Cell {
    // Which part of the image we are looking at (x/y)
    // dimension 0 = x, dimension 1 = y
    DoubleRange[] clip = new DoubleRange[2];
  
    // color transformations in place
    DoubleRange[] colorClips = new DoubleRange[3];
  
    Cell copy() {
      return copyTo(new Cell());
    }
    
    Cell copyTo(Cell c) {
      arrayCopy(clip, c.clip);
      arrayCopy(colorClips, c.colorClips);
      return c;
    }
  
    Rect rectInImage() {
      return rectMinSize(1, 1, toRect_floor(doubleRectFromRanges(clip[0], clip[1])));
    }
    
    double area() { return rectArea(rectInImage()); }
  
    // get color of cell
  
    double color(int channel) {
      double color = ii_averageBrightnessOfArea(image, rectInImage(), channel);
      return transformBetweenDoubleRanges(color, colorClips[channel], zeroToOne());
    }
    
    // unposterized color of all 3 channels
    double[] colors() {
      double[] c = new double[3];
      for (int i = 0; i < 3; i++)
        c[i] = color(i);
      return c;
    }
    
    RGB averageColor() { return rgb(); }
RGB rgb() {
      return new RGB(colors());
    }
    
    public String toString() {
      return rectInImage() + ", color: " + map(asList(colors()), x -> formatDoubleX(x, 4));
    }
  
    int posterizedIntColor(int channel) {
      return posterizeToInt(color(channel));
    }
  
    // get sub-cells
    
    Cell[] cellArray(int n) {
      return new Cell[n];
    }
    
    Cell[] split(int dimension) { return split(dimension, 3); }
Cell[] split(int dimension, int n) {
      Cell[] cells = cellArray(n);
      for (int i = 0; i < n; i++) cells[i] = slice(dimension, doubleRatio(i, n), doubleRatio(i+1, n));
      return cells;
    }
  
    Cell slice(int dimension, double a, double b) {
      Cell c = copy();
      c.clip[dimension] = transformBetweenDoubleRanges(new DoubleRange(a, b), zeroToOne(), clip[dimension]);
      return c;
    }
    
    // index = 0 to 2
    Cell third(int dimension, int index) {
      return slice(dimension, index/3.0, (index+1)/3.0);
    }
    
    // convert to B/W
    
    BWCell channel(int channel) {
      BWCell c = new BWCell();
      copyTo(c);
      c.colorToBW = rgb -> rgb[channel];
      return c;
    }
    
    BWCell brightness() {
      BWCell c = new BWCell();
      copyTo(c);
      return c;
    }
    
    double averageBrightness() {
      return brightness().color();
    }
  }

  class BWCell extends Cell {
    IF1<double[], Double> colorToBW = rgb -> (rgb[0]+rgb[1]+rgb[2])/3;
    
    double color() {
      return colorToBW.get(colors());
    }
    
    BWCell copy() {
      BWCell c = new BWCell();
      copyTo(c);
      return c;
    }
    
    void copyTo(BWCell c) {
      super.copyTo(c);
      c.colorToBW = colorToBW;
    }
    
    public String toString() {
      return rectInImage() + ", Color: " + formatDoubleX(color(), 4);
    }
  
    // lift methods
    
    BWCell[] cellArray(int n) {
      return new BWCell[n];
    }
    
    BWCell slice(int dimension, double a, double b) {
      return (BWCell) super.slice(dimension, a, b);
    }
    
    BWCell[] split(int dimension) {
      return (BWCell[]) super.split(dimension);
    }
    
    BWCell third(int dimension, int index) {
      return (BWCell) super.third(dimension, index);
    }
  }
  
  // make the root cell
  Cell cell() { return rootCell(); }
Cell rootCell() {
    Cell c = new Cell();
    c.clip[0] = doubleRange(0, image.getWidth());
    c.clip[1] = doubleRange(0, image.getHeight());
    for (int i = 0; i < 3; i++) c.colorClips[i] = doubleRange(0, 255);
    return c;
  }
  
  int outlierPosition(BWCell[] cells) {
    double a = cells[0].color();
    double b = cells[1].color();
    double c = cells[2].color();
    double ab = abs(a-b), bc = abs(b-c), ac = abs(a-c);
    if (bc < min(ab, ac)) return 0; // b and c close together
    if (ac < min(ab, bc)) return 1; // a and c close together
    if (ab < min(ac, bc)) return 2; // a and b close together
    return -1; // unknown
  }
}
static class Fail extends RuntimeException implements IFieldsToList{
  Object[] objects;
  Fail() {}
  Fail(Object... objects) {
  this.objects = objects;}
  public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + objects + ")"; }public Object[] _fieldsToList() { return new Object[] {objects}; }
}
static class WithProbability<A> extends Var<A> implements Comparable<WithProbability<A>> {
  double probability; // assumed between 0 and 1
  
  WithProbability() {}
  WithProbability(double probability, A a) { super(a);
  this.probability = probability; }
  
  public String toString() {
    return "p=" + renderedProbability() + ": " + str(get());
  }
  
  String renderedProbability() {
    return formatDouble_noLeadingZero(probability, 2);
  }
  
  double probability() { return probability; }
  
  public int hashCode() {
    return boostHashCombine(main.hashCode(probability), main.hashCode(get()));
  }
  
  public boolean equals(Object o) {
    if (o instanceof WithProbability) {
      return probability == ((WithProbability) o).probability && eq(get(), ((WithProbability) o).get());
    }
    return false;
  }
  
  // Higher probability comes first!
  public int compareTo(WithProbability<A> wp) {
    return wp == null ? 1
      : cmp(wp.probability, probability);
  }
}
static 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 IProbabilisticScheduler {
  // schedule an action at an absolute probability
  void at(double probability, Runnable action);
  
  // schedule an action at a probability relative to
  // currentProbability()
  default void atRelative(double probability, Runnable action) {
    at(currentProbability()*probability, action);
  }
  
  double currentProbability();
  long stepCount();
}
final static class DoubleRange {
  double start, end;
  
  DoubleRange() {}
  DoubleRange(double start, double end) {
  this.end = end;
  this.start = start;}
  
  public boolean equals(Object o) { return stdEq2(this, o); }
public int hashCode() { return stdHash2(this); }
  
  double length() { return end-start; }
  
  static String _fieldOrder = "start end";
  
  public String toString() { return "[" + start + ";" + end + "]"; }
}
final static class Rect {
  int x, y, w, h;
  
  Rect() {}
  Rect(Rectangle r) {
    x = r.x;
    y = r.y;
    w = r.width;
    h = r.height;
  }
  Rect(int x, int y, int w, int h) {
  this.h = h;
  this.w = w;
  this.y = y;
  this.x = x;}
  Rect(Pt p, int w, int h) {
  this.h = h;
  this.w = w; x = p.x; y = p.y; }
  Rect(Rect r) { x = r.x; y = r.y; w = r.w; h = r.h; }
  
  Rectangle getRectangle() {
    return new Rectangle(x, y, w, h);
  }
  
  public boolean equals(Object o) { return stdEq2(this, o); }
public int hashCode() { return stdHash2(this); }
  
  public String toString() {
    return x + "," + y + " / " + w + "," + h;
  }
  
  int x1() { return x; }
  int y1() { return y; }
  int x2() { return x + w; }
  int y2() { return y + h; }
  
  boolean contains(Pt p) {
    return contains(p.x, p.y);
  }
  
  boolean contains(int _x, int _y) {
    return _x >= x && _y >= y && _x < x+w && _y < y+h;
  }
  
  boolean empty() { return w <= 0 || h <= 0; }
}
final static class IntegralImage implements IIntegralImage {
  int w, h;
  int[] data; // 3 ints per pixel
  
  IntegralImage(RGBImage img) {
    init(img);
  }
  
  void init(RGBImage img) {
    w = img.w();
    h = img.h();
    if (longMul(w, h) > 8000000) throw fail("Image too big: " + w + "*" + h);
    data = new int[w*h*3];
    int i = 0;
    for (int y = 0; y < h; y++) {
      int sumR = 0, sumG = 0, sumB = 0;
      for (int x = 0; x < w; x++) {
        int rgb = img.getInt(x, y);
        sumR += (rgb >> 16) & 0xFF;
        sumG += (rgb >> 8) & 0xFF;
        sumB += rgb & 0xFF;
        data[i] = y > 0 ? sumR + data[i-w*3] : sumR;
        data[i+1] = y > 0 ? sumG + data[i-w*3+1] : sumG;
        data[i+2] = y > 0 ? sumB + data[i-w*3+2] : sumB;
        i += 3;
      }
    }
  }
  
  IntegralImage(MakesBufferedImage img) {
    if (img instanceof RGBImage)
      init(((RGBImage) img));
    else
      init(toBufferedImage(img));
  }
  
  IntegralImage(BufferedImage img) {
    init(img);
  }
  
  void init(BufferedImage img) {
    w = img.getWidth();
    h = img.getHeight();
    if (longMul(w, h) > 8000000) throw fail("Image too big: " + w + "*" + h);
    int[] pixels = pixelsOfBufferedImage(img);
    data = new int[w*h*3];
    int i = 0, j = 0, sumR = 0, sumG = 0, sumB = 0;
    for (int x = 0; x < w; x++) {
      int rgb = pixels[j++];
      data[i++] = (sumR += (rgb >> 16) & 0xFF);
      data[i++] = (sumG += (rgb >> 8) & 0xFF);
      data[i++] = (sumB += rgb & 0xFF);
    }
    for (int y = 1; y < h; y++) {
      sumR = sumG = sumB = 0;
      for (int x = 0; x < w; x++) {
        int rgb = pixels[j++];
        sumR += (rgb >> 16) & 0xFF;
        sumG += (rgb >> 8) & 0xFF;
        sumB += rgb & 0xFF;
        data[i] = sumR + data[i-w*3];
        data[i+1] = sumG + data[i-w*3+1];
        data[i+2] = sumB + data[i-w*3+2];
        i += 3;
      }
    }
  }
  
  // gets the integral value at x/y for given RGB channel
  public double get(int x, int y, int channel) { return getIntegralValue(x, y, channel); }
public double getIntegralValue(int x, int y, int channel) {
    return x < 0 || y < 0 || x >= w || y >= h ? 0
      : data[(y*w+x)*3+channel];
  }
  
  // gets sum of the 3 channels
  public double get(int x, int y) { return getIntegralValue(x, y); }
public double getIntegralValue(int x, int y) {
    if (x < 0 || y < 0 || x >= w || y >= h) return 0;
    int i = (y*w+x)*3;
    return data[i]+data[i+1]+data[i+2];
  }
  
  public String toString() {
    return "IntegralImage " + w + "*" + h + ", brightness: " + averageBrightness();
  }
  
  public BufferedImage getBufferedImage() { return integralImageToBufferedImage(this); }
  public int getWidth() { return w; }
  public int getHeight() { return h; }
  int w() { return w; }
  int h() { return h; }
  
  // serialization
  
  Object _serialize() { return litobjectarray(w, h, data); }
  static IntegralImage _deserialize(Object[] l) { return new IntegralImage((int) l[0], (int) l[1], (int[]) l[2]); }
  IntegralImage(int w, int h, int[] data) {
  this.data = data;
  this.h = h;
  this.w = w;}
}
// TreeSet variant allowing multiple elements which are considered
// equal by the comparator but not by eq().
// All operations O(log n) with n being the number of _different_ elements.
static class TreeSetWithDuplicates<A> extends AbstractSet<A> {
  NavigableSet<CompactLinkedHashSet<A>> sets;
  Comparator<A> comparator;
  int size;
  
  TreeSetWithDuplicates() { this((Comparator<A>) null); }
  
  TreeSetWithDuplicates(Comparator<A> comparator) {
  this.comparator = comparator;
    sets = new TreeSet<CompactLinkedHashSet<A>>(
      comparator == null
        ? (setA, setB) -> cmp(main.first(setA), main.first(setB))
        : (setA, setB) -> comparator.compare(main.first(setA), main.first(setB))
    );
  }
  protected TreeSetWithDuplicates(NavigableSet<CompactLinkedHashSet<A>> sets) {
  this.sets = sets;}
  
  /*swappable*/ CompactLinkedHashSet<A> makeInnerSet() {
    return new CompactLinkedHashSet();
  }
  
  public boolean add(A a) {
    var probe = probe(a);
    CompactLinkedHashSet<A> found = navigableSet_find(sets, probe);
    if (found != null) {
      if (!found.add(a)) return false;
    } else
      sets.add(probe);
    ++size;
    return true;
  }
  
  public boolean remove(Object a) {
    CompactLinkedHashSet<A> newSet = makeInnerSet();
    newSet.add((A) a);
    CompactLinkedHashSet<A> found = navigableSet_find(sets, newSet);
    if (found == null) return false;
    if (l(found) == 1)
      sets.remove(found);
    else
      found.remove(a);
    --size;
    return true;
  }
  
  A first() {
    return main.first(main.first(sets));
  }
  
  A last() {
    var last = sets.last();
    return last == null ? null : last.last();
  }
  
  public IterableIterator<A> iterator() {
    return nestedIterator(sets, __1 -> __1.iterator());
  }
  
  public int size() { return size; }
  
  // may return null
  Set<A> tiedForFirst() { return main.first(sets); }
  
  CompactLinkedHashSet<A> probe(Object a) {
    return addAndReturnCollection(makeInnerSet(), (A) a);
  }
  
  public boolean contains(Object a) {
    return navigableSet_find(sets, probe(a)) != null;
  }
}
static class 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 IVF1<A> {
  void get(A a);
}
static interface Steppable {
  public boolean step(); // return false if done
}
static interface IIntegralImage extends MakesBufferedImage {
  public int getWidth();
  public int getHeight();

  // get value for 1 channel
  // normal range [0; pixelCount*256)
  public double getIntegralValue(int x, int y, int channel);
    
  // gets value of the 3 channels
  // normal range [0; pixelCount*256*3)
  default double getIntegralValue(int x, int y) {
    return getIntegralValue(x, y, 0)
      + getIntegralValue(x, y, 1)
      + getIntegralValue(x, y, 2);
  }
  
  default double rectSum(int x1, int y1, int x2, int y2, int channel) {
    double bottomLeft  = getIntegralValue(x1-1, y2-1, channel);
    double bottomRight = getIntegralValue(x2-1, y2-1, channel);
    double topLeft     = getIntegralValue(x1-1, y1-1, channel);
    double topRight    = getIntegralValue(x2-1, y1-1, channel);
    return bottomRight+topLeft-topRight-bottomLeft;
  }
  
  default double rectSum(int x1, int y1, int x2, int y2) {
    double bottomLeft  = getIntegralValue(x1-1, y2-1);
    double bottomRight = getIntegralValue(x2-1, y2-1);
    double topLeft     = getIntegralValue(x1-1, y1-1);
    double topRight    = getIntegralValue(x2-1, y1-1);
    return bottomRight+topLeft-topRight-bottomLeft;
  }
  
  default IIntegralImage clip(int x, int y, int w, int h) {
    return new IIVirtualClip(this, x, y, w, h);
  }
  
  default double averageBrightness() {
    int w = getWidth(), h = getHeight();
    return doubleRatio(getIntegralValue(w-1, h-1), w*h*3*255.0);
  }
}


static class IIVirtualClip extends Meta implements IIntegralImage {
  RegisteredReference < IIntegralImage > fullImage = new RegisteredReference<>(this);
  int x1, y1, w, h;
  
  IIVirtualClip() {}
  IIVirtualClip(IIntegralImage fullImage, int x1, int y1, int w, int h) {
    this.fullImage.set(fullImage);
  this.h = h;
  this.w = w;
  this.y1 = y1;
  this.x1 = x1;
  }
  
  public int getWidth() { return w; }
  public int getHeight() { return h; }

  public double getIntegralValue(int x, int y, int channel) {
    return fullImage.get().getIntegralValue(x+x1, y+y1, channel);
  }
    
  public double getIntegralValue(int x, int y) {
    return fullImage.get().getIntegralValue(x+x1, y+y1);
  }
  
  public BufferedImage getBufferedImage() {
    return clipBufferedImage(fullImage.get().getBufferedImage(), x1, y1, w, h);
  }
}
static class Pt implements Comparable<Pt> {
  int x, y;
  
  Pt() {}
  Pt(Point p) {
    x = p.x;
    y = p.y;
  }
  Pt(int x, int y) {
  this.y = y;
  this.x = x;}
  
  Point getPoint() {
    return new Point(x, y);
  }
  
  public boolean equals(Object o) {
    return o instanceof Pt && x == ((Pt) o).x && y == ((Pt) o).y;
  }
  
  public int hashCode() {
    return boostHashCombine(x, y);
  }
  
  // compare in scan order
  public int compareTo(Pt p) {
    if (y != p.y) return cmp(y, p.y);
    return cmp(x, p.x);
  }
  
  public String toString() {
    return x + ", " + y;
  }
}
static interface ISetter<A> {
 void set(A a);
}

// -has fast nextElement() and prevElement()
// -design allows for more functions like reordering the list
// -Saves up to 34% in space over LinkedHashSet
//    (e.g. 22% for a set of 1,000 Ints)
static class CompactLinkedHashSet<A> extends AbstractSet<A> {
  UnsynchronizedCompactHashSet<Entry<A>> entries = new UnsynchronizedCompactHashSet();
  Entry<A> head, tail;
  
  static class Entry<A> {
    A value;
    Entry<A> prev, next;
    
    public int hashCode() {
      return main.hashCode(value);
    }
    
    // "magic" equals function for CompactHashSet lookup without temp object
    public boolean equals(Object o) {
      return o == this || eq(value, o);
    }
  }
  
  public boolean add(A a) {
    if (entries.contains(a)) return false;
    Entry<A> n = new Entry();
    n.value = a;
    n.prev = tail;
    if (tail != null) tail.next = n;
    tail = n;
    if (head == null) head = n;
    entries.add(n);
    return true;
  }
  
  public boolean remove(Object a) {
    return remove(entries.find(a));
  }
  
  public boolean remove(Entry<A> node) {
    if (node == null) return false;
    if (node.next != null) node.next.prev = node.prev; else tail = node.prev;
    if (node.prev != null) node.prev.next = node.next; else head = node.next;
    entries.remove(node);
    return true;
  }
  
  public int size() { return entries.size(); }
  
  public IterableIterator<A> iterator() {
    return new IterableIterator<A>() {
      Entry<A> entry = head;
      public boolean hasNext() { return entry != null; }
      public A next() {
        A a = entry.value;
        entry = entry.next;
        return a;
      }
    };
  }
  
  public boolean contains(Object a) {
    return entries.contains(a);
  }
  
  public A prevElement(A a) {
    Entry<A> e = entries.find(a);
    if (e == null || e.prev == null) return null;
    return e.prev.value;
  }
  
  public A nextElement(A a) {
    Entry<A> e = entries.find(a);
    if (e == null || e.next == null) return null;
    return e.next.value;
  }
  
  public A first() { return head == null ? null : head.value; }
  public A last() { return tail == null ? null : tail.value; }
}
static interface IVar<A> extends IF0<A> {
  void set(A a);
  A get();
  
  default boolean has() { return get() != null; }
  default void clear() { set(null); }
  
}
static class RGBImage implements MakesBufferedImage {
  transient BufferedImage bufferedImage;
  File file;
  int width, height;
  int[] pixels;

  RGBImage() {}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public File getFile() {
    return file;
  }

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

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

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

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

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

  public int[] getPixels() {
    return pixels;
  }
  
  void setPixel(int x, int y, int r, int g, int b) {
    if (x >= 0 && y >= 0 && x < width && y < height)
      pixels[y*width+x] = (limitToUByte(r) << 16) | (limitToUByte(g) << 8) | limitToUByte(b);
  }

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

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

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

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

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

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

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

    RGBImage rgbImage = (RGBImage) o;

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

    return true;
  }

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

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

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

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

  public int numPixels() {
    return width*height;
  }
  
  void uncacheBufferedImage() {
    bufferedImage = null;
  }
}

static interface MakesBufferedImage extends WidthAndHeight {
  BufferedImage getBufferedImage();
  
  public default void drawAt(Graphics2D g, int x, int y) {
    g.drawImage(getBufferedImage(), x, y, null);
  }
}


// Meta - a "minimal" approach to adding meta-level to Java objects

static class Meta implements IMeta {
  // We allocate one extra field for each Java object to make it
  // reasoning-compatible. We couldn't go for 0 extra fields and
  // there are no half fields in Java... so there you go.
  // Also, if you don't use any meta data, you are probably not
  // reasoning about anything. The point of reasoning in JavaX is
  // to attach information to objects directly used in the program.
  
  // Possible information contained in the meta field:
  //   Origin, destination, security level, sender, cost center,
  //   purpose, list of reifications, ...
  
  // So here it is. The field.
  // We also have IMeta to retrofit foreign classes (rare but
  // probably useful)
  
  // generic meta value of any kind (e.g. Map with extra field values
  // for the object).
  // volatile to avoid synchronization; but you can also synchronize on
  // _tempMetaMutex() which is usually the object itself. Still considering
  // whether that is actually a good idea.
  volatile Object meta;
  
  // ...and the interface methods
  public void _setMeta(Object meta) { this.meta = meta; }
  public Object _getMeta() { return meta; }
}
static interface IF0<A> {
  A get();
}
static class RegisteredReference<A> implements IRef<A> {
  Meta owner; // all we require is a meta field
  A value;
  
  RegisteredReference() {
    //if (!dynamicObjectIsLoading()) registerRef();
  }
  
  /*void registerRef {
    vmBus_send registeringReference(this);
  }*/
  
  // Note that the single-argument constructor takes an owner, not a value
  RegisteredReference(Meta owner) {
    this(owner, null);
  }
  
  RegisteredReference(Meta owner, A value) {
  this.value = value;
  this.owner = owner;
    index();
    //registerRef();
  }
  
  // get owning object (source)
  Meta owner() { return owner; }

  // get target
  public A get() { return value; }
  boolean has() { return value != null; }
  
  boolean set(A a) {
    if (a == value) return false;
    unindex();
    value = a;
    index();
    return true;
  }
  
  void setIfEmpty(A a) {
    if (!has()) set(a);
  }
  
  void set(IRef<A> ref) { set(ref == null ? null : ref.get()); }
  void clear() { set((A) null); }
  
  // can override
  boolean validRef() { return true; }
  
  // TODO: sync all the indexing and unindexing!?
  void index() { 
    if (!validRef()) return;
    var br = lookupInterface(IHasBackRefs.class, get());
    { if (br != null) br._registerBackRef(this); }
  }

  void unindex() {
    if (!validRef()) return;
    var br = lookupInterface(IHasBackRefs.class, get());
    { if (br != null) br._unregisterBackRef(this); }
  }
  
  // not used yet
  void change() {}

  public String toString() {
    return
      
        str(value);
  }
}
/*
 * #!
 * Ontopia Engine
 * #-
 * Copyright (C) 2001 - 2013 The Ontopia Project
 * #-
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * !#
 */

// modified by Stefan Reich

// Implements the Set interface more compactly than
// java.util.HashSet by using a closed hashtable.

// Note: equals is always called on the _stored_ object, not the one
// passed as an argument to find(), contains() etc.
// (In case you want to put special magic in your equals() function)

static class UnsynchronizedCompactHashSet<A> extends java.util.AbstractSet<A> {
  protected final static int INITIAL_SIZE = 3;
  public final static double LOAD_FACTOR = 0.75;

  protected final static Object nullObject = new Object();
  protected final static Object deletedObject = new Object();
  protected int elements;
  protected int freecells;
  protected A[] objects;
  
  protected int modCount;
  
  
  UnsynchronizedCompactHashSet() {
    this(INITIAL_SIZE);
  }

  UnsynchronizedCompactHashSet(int size) {
    // NOTE: If array size is 0, we get a
    // "java.lang.ArithmeticException: / by zero" in add(Object).
    objects = (A[]) new Object[(size==0 ? 1 : size)];
    elements = 0;
    freecells = objects.length;
    
      modCount = 0;
    
  }

  UnsynchronizedCompactHashSet(Collection<A> c) {
    this(c.size());
    addAll(c);
  }

  @Override
  public Iterator<A> iterator() {
    return new CompactHashIterator<A>();
  }

  @Override
  public int size() {
    return elements;
  }

  @Override
  public boolean isEmpty() {
    return elements == 0;
  }

  @Override
  public boolean contains(Object o) {
    return find(o) != null;
  }
  
  A find(Object o) {
    if (o == null) o = nullObject;
    
    int hash = o.hashCode();
    int index = (hash & 0x7FFFFFFF) % objects.length;
    int offset = 1;

    // search for the object (continue while !null and !this object)
    while(objects[index] != null &&
          !(objects[index].hashCode() == hash &&
            objects[index].equals(o))) {
      index = ((index + offset) & 0x7FFFFFFF) % objects.length;
      offset = offset*2 + 1;

      if (offset == -1)
        offset = 2;
    }

    return objects[index];
  }
  
  boolean removeIfSame(Object o) {
    A value = find(o);
    if (value == o) {
      remove(value);
      return true;
    }
    return false;
  }

  @Override
  public boolean add(Object o) {
    if (o == null) o = nullObject;

    int hash = o.hashCode();
    int index = (hash & 0x7FFFFFFF) % objects.length;
    int offset = 1;
    int deletedix = -1;
    
    // search for the object (continue while !null and !this object)
    while(objects[index] != null &&
          !(objects[index].hashCode() == hash &&
            objects[index].equals(o))) {

      // if there's a deleted object here we can put this object here,
      // provided it's not in here somewhere else already
      if (objects[index] == deletedObject)
        deletedix = index;
      
      index = ((index + offset) & 0x7FFFFFFF) % objects.length;
      offset = offset*2 + 1;

      if (offset == -1)
        offset = 2;
    }
    
    if (objects[index] == null) { // wasn't present already
      if (deletedix != -1) // reusing a deleted cell
        index = deletedix;
      else
        freecells--;

      
        modCount++;
      
      elements++;

      // here we face a problem regarding generics:
      // add(A o) is not possible because of the null Object. We cant do 'new A()' or '(A) new Object()'
      // so adding an empty object is a problem here
      // If (! o instanceof A) : This will cause a class cast exception
      // If (o instanceof A) : This will work fine

      objects[index] = (A) o;
      
      // do we need to rehash?
      if (1 - (freecells / (double) objects.length) > LOAD_FACTOR)
        rehash();
      return true;
    } else // was there already 
      return false;
  }
  
  @Override
  public boolean remove(Object o) {
    if (o == null) o = nullObject;
    
    int hash = o.hashCode();
    int index = (hash & 0x7FFFFFFF) % objects.length;
    int offset = 1;
    
    // search for the object (continue while !null and !this object)
    while(objects[index] != null &&
          !(objects[index].hashCode() == hash &&
            objects[index].equals(o))) {
      index = ((index + offset) & 0x7FFFFFFF) % objects.length;
      offset = offset*2 + 1;

      if (offset == -1)
        offset = 2;
    }

    // we found the right position, now do the removal
    if (objects[index] != null) {
      // we found the object

      // same problem here as with add
      objects[index] = (A) deletedObject;
      
        modCount++;
      
      elements--;
      return true;
    } else
      // we did not find the object
      return false;
  }
  
  @Override
  public void clear() {
    elements = 0;
    for (int ix = 0; ix < objects.length; ix++)
      objects[ix] = null;
    freecells = objects.length;
    
      modCount++;
    
  }

  @Override
  public Object[] toArray() {
    Object[] result = new Object[elements];
    Object[] objects = this.objects;
    int pos = 0;
    for (int i = 0; i < objects.length; i++)
      if (objects[i] != null && objects[i] != deletedObject) {
        if (objects[i] == nullObject)
          result[pos++] = null;
        else
          result[pos++] = objects[i];
      }
    // unchecked because it should only contain A
    return result;
  }

  // not sure if this needs to have generics
  @Override
  public <T> T[] toArray(T[] a) {
    int size = elements;
    if (a.length < size)
      a = (T[])java.lang.reflect.Array.newInstance(
                                 a.getClass().getComponentType(), size);
    A[] objects = this.objects;
    int pos = 0;
    for (int i = 0; i < objects.length; i++)
      if (objects[i] != null && objects[i] != deletedObject) {
        if (objects[i] == nullObject)
          a[pos++] = null;
        else
          a[pos++] = (T) objects[i];
      }
    return a;
  }
  
  protected void rehash() {
    int garbagecells = objects.length - (elements + freecells);
    if (garbagecells / (double) objects.length > 0.05)
      // rehash with same size
      rehash(objects.length);
    else
      // rehash with increased capacity
      rehash(objects.length*2 + 1);
  }
  
  protected void rehash(int newCapacity) {
    int oldCapacity = objects.length;
    @SuppressWarnings("unchecked")
    A[] newObjects = (A[]) new Object[newCapacity];

    for (int ix = 0; ix < oldCapacity; ix++) {
      Object o = objects[ix];
      if (o == null || o == deletedObject)
        continue;
      
      int hash = o.hashCode();
      int index = (hash & 0x7FFFFFFF) % newCapacity;
      int offset = 1;

      // search for the object
      while(newObjects[index] != null) { // no need to test for duplicates
        index = ((index + offset) & 0x7FFFFFFF) % newCapacity;
        offset = offset*2 + 1;

        if (offset == -1)
          offset = 2;
      }

      newObjects[index] = (A) o;
    }

    objects = newObjects;
    freecells = objects.length - elements;
  }
  
  private class CompactHashIterator<T> implements Iterator<T> {
    private int index;
    private int lastReturned = -1;

    
      private int expectedModCount;
    

    @SuppressWarnings("empty-statement")
    public CompactHashIterator() {
        for (index = 0; index < objects.length &&
                        (objects[index] == null ||
                        objects[index] == deletedObject); index++)
          ;
        
          expectedModCount = modCount;
        
    }

    @Override
    public boolean hasNext() {
        return index < objects.length;
    }

    @SuppressWarnings("empty-statement")
    @Override
    public T next() {
        /*if (modCount != expectedModCount)
          throw new ConcurrentModificationException();*/
        int length = objects.length;
        if (index >= length) {
          lastReturned = -2;
          throw new NoSuchElementException();
        }
  
        lastReturned = index;
        for (index += 1; index < length &&
                         (objects[index] == null ||
                          objects[index] == deletedObject); index++)
          ;
        if (objects[lastReturned] == nullObject)
          return null;
        else
          return (T) objects[lastReturned];
    }

    @Override
    public void remove() {
        
          if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        
        if (lastReturned == -1 || lastReturned == -2)
          throw new IllegalStateException();
        // delete object
        if (objects[lastReturned] != null && objects[lastReturned] != deletedObject) {
          objects[lastReturned] = (A) deletedObject;
          elements--;
          
            modCount++;
            expectedModCount = modCount; // this is expected; we made the change
          
        }
    }
  }
  
  int capacity() { return objects.length; }
  
  // returns true if there was a shrink
  boolean shrinkToFactor(double factor) {
    if (factor > LOAD_FACTOR)
      throw fail("Shrink factor must be equal to or smaller than load factor: " + factor + " / " + LOAD_FACTOR);
    int newCapacity = max(INITIAL_SIZE, iround(size()/factor));
    if (newCapacity >= capacity()) return false;
    rehash(newCapacity);
    return true;
  }
}
static interface WidthAndHeight {
  int getWidth();
  int getHeight();
}


static interface IMeta {
  // see class "Meta" for the bla bla
  
  public void _setMeta(Object meta);
  public Object _getMeta();
  default public IAutoCloseableF0 _tempMetaMutex() {
    return new IAutoCloseableF0() {
      public Object get() { return IMeta.this; }
      public void close() {}
    };
  }
}
static interface IHasBackRefs {
  public void _registerBackRef(IRef ref);
  public void _unregisterBackRef(IRef ref);
}
static interface IRef<A> extends IF0<A> {
  // called by the referencee to atomically replace itself
  // Passing oldValue to avoid race conditions
  public default void replaceValue(A oldValue, A newValue) {}
}


static interface IAutoCloseableF0<A> extends IF0<A>, AutoCloseable {}


static boolean isAbstract(Class c) {
  return (c.getModifiers() & Modifier.ABSTRACT) != 0;
}

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


static boolean reflection_isForbiddenMethod(Method m) {
  return m.getDeclaringClass() == Object.class
    && eqOneOf(m.getName(), "finalize", "clone", "registerNatives");
}


static Set<Class> allInterfacesImplementedBy(Class c) {
  if (c == null) return null;
  HashSet<Class> set = new HashSet();
  allInterfacesImplementedBy_find(c, set);
  return set;
}

static void allInterfacesImplementedBy_find(Class c, Set<Class> set) {
  if (c.isInterface() && !set.add(c)) return;
  do {
    for (Class intf : c.getInterfaces())
      allInterfacesImplementedBy_find(intf, set);
  } while ((c = c.getSuperclass()) != null);
}


static Method findMethod(Object o, String method, Object... args) {
  return findMethod_cached(o, method, args);
}

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


static Method findStaticMethod(Class c, String method, Object... args) {
  Class _c = c;
  while (c != null) {
    for (Method m : c.getDeclaredMethods()) {
      if (!m.getName().equals(method))
        continue;

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

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

static boolean findStaticMethod_checkArgs(Method m, Object[] args) {
  Class<?>[] types = m.getParameterTypes();
  if (types.length != args.length)
    return false;
  for (int i = 0; i < types.length; i++)
    if (!(args[i] == null || isInstanceX(types[i], args[i])))
      return false;
  return true;
}



static 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 List<String> quoteAll(Collection<String> l) {
  List<String> x = new ArrayList();
  for (String s : l)
    x.add(quote(s));
  return x;
}


static <A> ArrayList<A> toList(A[] a) { return asList(a); }
static ArrayList<Integer> toList(int[] a) { return asList(a); }
static <A> ArrayList<A> toList(Set<A> s) { return asList(s); }
static <A> ArrayList<A> toList(Iterable<A> s) { return asList(s); }


static boolean arraysEqual(Object[] a, Object[] b) {
  if (a.length != b.length) return false;
  for (int i = 0; i < a.length; i++)
    if (neq(a[i], b[i])) return false;
  return true;
}


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


static UnsupportedOperationException unsupportedOperation() {
  throw new UnsupportedOperationException();
}


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

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

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

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

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

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

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

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

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


static int rgbInt(int r, int g, int b) {
  return (clamp(r, 0, 255) << 16) | (clamp(g, 0, 255) << 8) | clamp(b, 0, 255);
}


static int asInt(Object o) {
  return toInt(o);
}


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


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



static <A> List<A> ll(A... a) {
  ArrayList l = new ArrayList(a.length);
  if (a != null) for (A x : a) l.add(x);
  return l;
}


static <A, B> LinkedHashMap<A, B> cloneLinkedHashMap(Map<A, B> map) {
  return map == null ? new LinkedHashMap() : new LinkedHashMap(map);
}


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

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

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


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



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




static char second(String s) {
  return charAt(s, 1);
}




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


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


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



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

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

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

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

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

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

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


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


//ifclass Symbol



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


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


static 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 <A> void remove(List<A> l, int i) {
  if (l != null && i >= 0 && i < l(l))
    l.remove(i);
}

static <A> void remove(Collection<A> l, A a) {
  if (l != null) l.remove(a);
}

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


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

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




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





static <A> A reverseGet(List<A> l, int idx) {
  if (l == null || idx < 0) return null;
  int n = l(l);
  return idx < n ? l.get(n-1-idx) : null;
}


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

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


static <A, B> Collection<B> values(Map<A, B> map) {
  return map == null ? emptyList() : map.values();
}

// convenience shortcut for values_gen
static Collection values(Object map) {
  return values((Map) map);
}


static <A, B> Collection<B> values(MultiMap<A, B> mm) {
  return mm == null ? emptyList() : concatLists(values(mm.data));
}





static <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 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 void add(BitSet bs, int i) {
  bs.set(i);
}

static <A> boolean add(Collection<A> c, A a) {
  return c != null && c.add(a);
}


static void add(Container c, Component x) {
  addToContainer(c, x);
}



static <A> AutoCloseable tempSetTL(ThreadLocal<A> tl, A a) {
  return tempSetThreadLocal(tl, a);
}

static <A> AutoCloseable tempSetTL(x30_pkg.x30_util.BetterThreadLocal<A> tl, A a) {
  return tempSetThreadLocalIfNecessary(tl, a);
}


static 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 void stepAll(Steppable s) {
  if (s != null) while  (s.step()) { ping(); }
}



static void stepMax(int max, Steppable s) {
  if (s == null) return;
  while  (max-- > 0 && s.step()) { ping(); }
}

static void stepMax(Steppable s, int max) {
  stepMax(max, s);
}


static String nEntries(long n) { return n2(n, "entry", "entries"); }
static String nEntries(Collection l) { return nEntries(l(l)); }
static String nEntries(Map map) { return nEntries(l(map)); }


static int ifloor(double d) {
  return (int) Math.floor(d);
}



  static float clampZeroToOne(float x) {
    return x < 0 ? 0 : x > 1 ? 1 : x;
  }


  static double clampZeroToOne(double x) {
    return x < 0 ? 0 : x > 1 ? 1 : x;
  }




static void arrayCopy(Object[] a, Object[] b) {
  arraycopy(a, b);
}



static void arrayCopy(Object src, int srcPos, Object dest, int destPos, int n) {
  arraycopy(src, srcPos, dest, destPos, n);
}


static Rect rectMinSize(int minW, int minH, Rect r) {
  return r == null || r.w >= minW && r.h >= minH ? r
    : rect(r.x, r.y, max(r.w, minW), max(r.h, minH));
}


static Rect toRect_floor(DoubleRect r) {
  if (r == null) return null;
  int x = ifloor(r.x), y = ifloor(r.y);
  return new Rect(x, y, ifloor(r.x2())-x, ifloor(r.y2())-y);
}


static DoubleRect doubleRectFromRanges(DoubleRange x, DoubleRange y) {
  return new DoubleRect(x.start, y.start, x.length(), y.length());
}


static int rectArea(Rect r) {
  return r == null ? 0 : r.w*r.h;
}



  static double ii_averageBrightnessOfArea(IIntegralImage img, int x1, int y1, int x2, int y2) {
    return doubleRatio(img.rectSum(x1, y1, x2, y2), (x2-x1)*(y2-y1)*3);
  }
  
  static double ii_averageBrightnessOfArea(IIntegralImage img, int x1, int y1, int x2, int y2, int channel) {
    return doubleRatio(img.rectSum(x1, y1, x2, y2, channel), (x2-x1)*(y2-y1));
  }
  
  static double ii_averageBrightnessOfArea(IIntegralImage img, Rect r) {
    return ii_averageBrightnessOfArea(img, r.x, r.y, r.x2(), r.y2());
  }
  
  static double ii_averageBrightnessOfArea(IIntegralImage img, Rect r, int channel) {
    return ii_averageBrightnessOfArea(img, r.x, r.y, r.x2(), r.y2(), channel);
  }


  static double ii_averageBrightnessOfArea(IntegralImage img, int x1, int y1, int x2, int y2) {
    return doubleRatio(img.rectSum(x1, y1, x2, y2), (x2-x1)*(y2-y1)*3);
  }
  
  static double ii_averageBrightnessOfArea(IntegralImage img, int x1, int y1, int x2, int y2, int channel) {
    return doubleRatio(img.rectSum(x1, y1, x2, y2, channel), (x2-x1)*(y2-y1));
  }
  
  static double ii_averageBrightnessOfArea(IntegralImage img, Rect r) {
    return ii_averageBrightnessOfArea(img, r.x, r.y, r.x2(), r.y2());
  }
  
  static double ii_averageBrightnessOfArea(IntegralImage img, Rect r, int channel) {
    return ii_averageBrightnessOfArea(img, r.x, r.y, r.x2(), r.y2(), channel);
  }




static double transformBetweenDoubleRanges(double x, DoubleRange src, DoubleRange dest) {
  return dest.start+dest.length()*doubleRatio(x-src.start, src.length());
}

static DoubleRange transformBetweenDoubleRanges(DoubleRange r, DoubleRange src, DoubleRange dest) {
  return r == null ? null :
    new DoubleRange(transformBetweenDoubleRanges(r.start, src, dest),
      transformBetweenDoubleRanges(r.end, src, dest));
}


static DoubleRange zeroToOne_value = new DoubleRange(0, 1);

static DoubleRange zeroToOne() {
  return zeroToOne_value;
}


static RGB rgb(String s) {
  return new RGB(s);
}

static RGB rgb(double r, double g, double b) {
  return new RGB((float) r, (float) g, (float) b);
}


static <A> A third(List<A> l) {
  return _get(l, 2);
}

static <A> A third(Iterable<A> l) {
  if (l == null) return null;
  Iterator<A> it = iterator(l);
  for (int _repeat_0 = 0; _repeat_0 < 2; _repeat_0++)  {
    if (!it.hasNext()) return null;
    it.next();
  }
  return it.hasNext() ? it.next() : null;
}



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


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



static DoubleRange doubleRange(double start, double end) {
  return new DoubleRange(start, end);
}


static float abs(float f) { return Math.abs(f); }
static int abs(int i) { return Math.abs(i); }
static double abs(double d) { return Math.abs(d); }


static String shortClassName_dropNumberPrefix(Object o) {
  return dropNumberPrefix(shortClassName(o));
}


static String formatDouble_noLeadingZero(double d, int digits) {
  String s = formatDouble(d, digits);
  if (startsWith(s, "-"))
    return startsWith(s, "-0.") ? "-." + dropFirst(3, s) : s;
  else
    return startsWith(s, "0.") ? dropFirst(s) : s;
}



static int hashCode(Object a) {
  return a == null ? 0 : a.hashCode();
}


static int hashCodeFor(Object a) {
  return a == null ? 0 : a.hashCode();
}


static boolean stdEq2(Object a, Object b) {
  if (a == null) return b == null;
  if (b == null) return false;
  if (a.getClass() != b.getClass()) return false;
  for (String field : allFields(a))
    if (neq(getOpt(a, field), getOpt(b, field)))
      return false;
  return true;
}


static int stdHash2(Object a) {
  if (a == null) return 0;
  return stdHash(a, toStringArray(allFields(a)));
}


static long longMul(long a, long b) {
  return a*b;
}


static BufferedImage toBufferedImage(Object o) {
  return toBufferedImageOpt(o);
}


static int[] pixelsOfBufferedImage(BufferedImage image) { try {
  int width = image.getWidth();
  int height = image.getHeight();
  int[] pixels = new int[width*height];
  PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width);
  if (!pixelGrabber.grabPixels())
    throw fail("Could not grab pixels");
  return pixels;
} catch (Exception __e) { throw rethrow(__e); } }


static double averageBrightness(BufferedImage img) {
  return new BWImage(img).averageBrightness();
}


static BufferedImage integralImageToBufferedImage(IntegralImage img) {
  if (img == null) return null;
  int w = img.w, h = img.h;
  BufferedImage out = newBufferedImage(w, h);
  for (int y = 0; y < h; y++)
    for (int x = 0; x < w; x++)
      out.setRGB(x, y, ii_getPixel(img, x, y));
  return out;
}


static Object[] litobjectarray(Object... l) {
  return litObjectArray(l);
}


static <A> A navigableSet_find(NavigableSet<A> set, A a) {
  if (set == null || a == null) return null;
  A b = set.floor(a);
  return b != null && sortedSet_compare(set, a, b) == 0 ? b : null;
}


// TODO: clean up these type signatures?

static <A, B, C extends Iterator<B>> IterableIterator<B> nestedIterator(final Iterable<A> c, final F1<A, C> makeInnerIterator) {
  return nestedIterator(iterator(c), makeInnerIterator);
}

static <A, B, C extends Iterator<B>> IterableIterator<B> nestedIterator(Collection<A> c, final IF1<A, C> makeInnerIterator) {
  return nestedIterator(iterator(c), makeInnerIterator);
}

static <A, B, C extends Iterator<B>> IterableIterator<B> nestedIterator(Iterator<A> it1, IF1<A, C> makeInnerIterator) {
  return nestedIterator(it1, toF1(makeInnerIterator));
}

static <A, B, C extends Iterator<B>> IterableIterator<B> nestedIterator(final Iterator<A> it1, final F1<A, C> makeInnerIterator) {
  if (it1 == null || !it1.hasNext()) return emptyIterableIterator();
  return iff(new F0() {
    A a;
    Iterator<B> innerIterator;
    
    { nextOuter(); }
    
    void nextOuter() {
      a = it1.next();
      innerIterator = makeInnerIterator.get(a);
    }
    
    public Object get() {
      while (true) { ping();
        if (innerIterator != null && innerIterator.hasNext())
          return innerIterator.next();
        if (!it1.hasNext()) return endMarker();
        nextOuter();
      }
    }
  });
}

static <A, B, C extends Iterator<B>> IterableIterator<B> nestedIterator(IF1<A, C> makeInnerIterator, Iterator<A> it1) {
  return nestedIterator(it1, makeInnerIterator);
}

static <A, B, C extends Iterator<B>> IterableIterator<B> nestedIterator(IF1<A, C> makeInnerIterator, Collection<A> l) {
  return nestedIterator(l, makeInnerIterator);
}


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


static int getWidth(Component c) {
  return c == null ? 0 : (int) swingCall(c, "getWidth");
}


static int getHeight(Component c) {
  return c == null ? 0 : (int) swingCall(c, "getHeight");
}


static BufferedImage clipBufferedImage(BufferedImage src, Rectangle clip) {
  return clipBufferedImage(src, new Rect(clip));
}

static BufferedImage clipBufferedImage(BufferedImage src, Rect r) {
  if (src == null || r == null) return null;
  // fixClipRect
  r = intersectRects(r, new Rect(0, 0, src.getWidth(), src.getHeight()));
  if (rectEmpty(r)) return null; // can't make zero-sized BufferedImage
    
  return src.getSubimage(r.x, r.y, r.w, r.h);
}

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



static <A> A set(A o, String field, Object value) {
  if (o == null) return null;
  if (o instanceof Class) set((Class) o, field, value);
  else try {
    Field f = set_findField(o.getClass(), field);
    makeAccessible(f);
    smartSet(f, o, value);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
  return o;
}

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

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

static void set(BitSet bs, int idx) {
  { if (bs != null) bs.set(idx); }
}


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

static boolean inRange(int x, int a, int b) {
  return x >= a && x < b;
}


static int limitToUByte(int i) {
  return max(0, min(255, i));
}


static void setPixel(BufferedImage img, Pt p, Color color) {
  { if (img != null) img.setRGB(p.x, p.y, colorToIntOpaque(color)); }
}


static Class<?> getClass(String name) {
  return _getClass(name);
}

static Class getClass(Object o) {
  return _getClass(o);
}

static Class getClass(Object realm, String name) {
  return _getClass(realm, name);
}


static boolean has(String a, String b, String c) {
  
  return false;
}

static boolean has(T3<String, String, String> t) {
  
  return false;
}


// We even allow overriding existing interface implementations
static <A> A lookupInterface(Class<A> intrface, Object o) {
  return lookupDynamicInterface(intrface, o);
}




static <A> A lookupInterface(Object o, Class<A> intrface) {
  return lookupDynamicInterface(o, intrface);
}


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

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

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



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


static String find(String pattern, String text) {
  Matcher matcher = Pattern.compile(pattern).matcher(text);
  if (matcher.find())
    return matcher.group(1);
  return null;
}

static <A> A find(Collection<A> c, Object... data) {
  for (A x : c)
    if (checkFields(x, data))
      return x;
  return null;
}




static Method findMethod_cached(Object o, String method, Object... args) { try {
  if (o == null) return null;
  if (o instanceof Class) {
    _MethodCache cache = callOpt_getCache(((Class) o));
    List<Method> methods = cache.cache.get(method);
    if (methods != null) for (Method m : methods)
      if (isStaticMethod(m) && findMethod_checkArgs(m, args, false))
        return m;
    return null;
  } else {
    _MethodCache cache = callOpt_getCache(o.getClass());
    List<Method> methods = cache.cache.get(method);
    if (methods != null) for (Method m : methods)
      if (findMethod_checkArgs(m, args, false))
        return m;
    return null;
  }
} catch (Exception __e) { throw rethrow(__e); } }



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


static float clamp(float x, float a, float b) {
  return x < a ? a : x > b ? b : x;
}

static double clamp(double x, double a, double b) {
  return x < a ? a : x > b ? b : x;
}

static int clamp(int x, int a, int b) {
  return x < a ? a : x > b ? b : x;
}

static long clamp(long x, long a, long b) {
  return x < a ? a : x > b ? b : x;
}


static 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 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 char charAt(String s, int i) {
  return s != null && i >= 0 && i < s.length() ? s.charAt(i) : '\0';
}


static <A> List<A> immutableEmptyList() {
  return Collections.emptyList();
}


static <A, B> Map<A, B> immutableEmptyMap() {
  return Collections.emptyMap();
}


static void addToContainer(Container a, Component... b) {
  if (a == null) return;
  { swing(new Runnable() {  public void run() { try { 
    for (Component c : unnullForIteration(b))
      if (c != null) 
        a.add(c);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "for (Component c : unnullForIteration(b))\r\n      if (c != null) \r\n        a.a..."; }}); }
}


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

static <A> AutoCloseable tempSetThreadLocalIfNecessary(x30_pkg.x30_util.BetterThreadLocal<A> tl, A a) {
  if (tl == null) return null;
  A prev = tl.get();
  if (eq(prev, a)) return null;
  tl.set(a);
  return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); }};
}


static Rect rect(int x, int y, int w, int h) {
  return new Rect(x, y, w, h);
}

static Rect rect(Pt p, int w, int h) {
  return new Rect(p.x, p.y, w, h);
}

static Rect rect(int w, int h) {
  return new Rect(0, 0, w, h);
}




static <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 String dropNumberPrefix(String s) {
  return dropFirst(s, indexOfNonDigit(s));
}


static String shortClassName(Object o) {
  if (o == null) return null;
  Class c = o instanceof Class ? (Class) o : o.getClass();
  String name = c.getName();
  return shortenClassName(name);
}


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

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

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

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

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

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

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

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




static Map<Class, Set<String>> allFields_cache = weakHashMap();

static Set<String> allFields(Object o) {
  if (o == null) return emptySet();
  Class _c = _getClass(o);
  Set<String> fields = allFields_cache.get(_c);
  if (fields == null)
    allFields_cache.put(_c, fields = asTreeSet(keys(getOpt_getFieldMap(o))));
  return fields;
}


static int stdHash(Object a, String... fields) {
  if (a == null) return 0;
  int hash = getClassName(a).hashCode();
  for (String field : fields)
    hash = boostHashCombine(hash, hashCode(getOpt(a, field)));
  return hash;
}


static String[] 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 BufferedImage toBufferedImageOpt(Object o) {
  if (o instanceof BufferedImage) return (BufferedImage) o;
  if (o instanceof MakesBufferedImage)
    return ((MakesBufferedImage) o).getBufferedImage();
  if (o instanceof File)
    if (isImageFile(((File) o)))
      return loadBufferedImageFile(((File) o));
  String c = getClassName(o);
  
  // Keep this because it also works on imported objects
  if (eqOneOf(c, "main$BWImage", "main$RGBImage"))
    return (BufferedImage) call(o, "getBufferedImage");
    
  if (eq(c, "main$PNGFile"))
    return (BufferedImage) call(o, "getImage");
  return null;
}


// undefined color, seems to be all black in practice
static BufferedImage newBufferedImage(int w, int h) {
  return new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
}


static BufferedImage newBufferedImage(int w, int h, RGB rgb) {
  return newBufferedImage(w, h, rgb.getColor());
}


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


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



// assumes coordinates are in range
static int ii_getPixel(IntegralImage img, int x, int y) {
  if (img == null) return 0;
  int r = iround(img.rectSum(x, y, x+1, y+1, 0));
  int g = iround(img.rectSum(x, y, x+1, y+1, 1));
  int b = iround(img.rectSum(x, y, x+1, y+1, 2));
  return rgbInt(r, g, b);
}


static Object[] litObjectArray(Object... l) {
  return l;
}


static <A> int sortedSet_compare(SortedSet<A> set, A a, A b) {
  return compareWithComparator(set.comparator(), a, b);
}


static F1 toF1(final Object f) {
  return functionToF1(f);
}


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

static <A> IterableIterator<A> emptyIterableIterator() {
  return emptyIterableIterator_instance; 
}


// f: func -> A | endMarker
static <A> IterableIterator<A> iff(Object f) {
  return iteratorFromFunction_withEndMarker(f);
}

// can't use type parameter because end marker
static IterableIterator iff(F0 f) {
  return iteratorFromFunction_withEndMarker(f);
}

static <A> IterableIterator iff(IF0 f) {
  return iteratorFromFunction_withEndMarker(f);
}


static Object endMarker() {
  return iteratorFromFunction_endMarker;
}


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 Rect intersectRects(Rect a, Rect b) {
  int x = max(a.x, b.x), y = max(a.y, b.y);
  int x2 = min(a.x+a.w, b.x+b.w), y2 = min(a.y+a.h, b.y+b.h);
  return new Rect(x, y, x2-x, y2-y);
}


static boolean rectEmpty(Rect r) {
  return r == null || r.w <= 0 || r.h <= 0;
}


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


static int colorToIntOpaque(Color c) {
  return c.getRGB() | 0xFF000000;
}


// We even allow overriding existing interface implementations
static <A> A lookupDynamicInterface(Class<A> intrface, Object o) {
  if (o instanceof DynamicObject)
    { A a =  (A) (mapGet((Map) ((DynamicObject) o).fieldValues, intrface)); if (a != null) return a; }
  if (isInstance(intrface, o)) return (A) o;
  return null;
}


static <A> A lookupDynamicInterface(Object o, Class<A> intrface) {
  return lookupDynamicInterface(intrface, o);
}


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




// requires ugly casting when used (O -> A)
static Object iteratorFromFunction_endMarker = new Object();

// f: func -> A | endMarker
static <A> IterableIterator<A> iteratorFromFunction_withEndMarker(final Object f) {
  class IFF extends IterableIterator<A> {
    A a;
    boolean have, done;
    
    public boolean hasNext() {
      getNext();
      return !done;
    }
    
    public A next() {
      getNext();
      if (done) throw fail();
      A _a = a;
      a = null;
      have = false;
      return _a;
    }
    
    void getNext() {
      if (done || have) return;
      Object o = callF(f);
      if (o == iteratorFromFunction_endMarker)
        { done = true; return; }
      a = (A) o;
      have = true;
    }
  };
  return new IFF();
}

// optimized version for F0 argument; TODO: do same for IF0
static <A> IterableIterator<A> iteratorFromFunction_withEndMarker(final F0 f) {
  return iteratorFromFunction_withEndMarker_f0(f);
}


static 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 int parseInt(String s) {
  return emptyString(s) ? 0 : Integer.parseInt(s);
}

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


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


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


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 int indexOfNonDigit(String s) {
  int n = l(s);
  for (int i = 0; i < n; i++)
    if (!isDigit(s.charAt(i)))
      return i;
  return -1;
}


static String shortenClassName(String name) {
  if (name == null) return null;
  int i = lastIndexOf(name, "$");
  if (i < 0) i = lastIndexOf(name, ".");
  return i < 0 ? name : substring(name, i+1);
}


static String[] drop(int n, String[] a) {
  n = Math.min(n, a.length);
  String[] b = new String[a.length-n];
  System.arraycopy(a, n, b, 0, b.length);
  return b;
}

static Object[] drop(int n, Object[] a) {
  n = Math.min(n, a.length);
  Object[] b = new Object[a.length-n];
  System.arraycopy(a, n, b, 0, b.length);
  return b;
}


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


static Set emptySet() {
  return new HashSet();
}


static <A> TreeSet<A> asTreeSet(Collection<A> set) {
  return set == null ? null : set instanceof TreeSet ? (TreeSet) set : new TreeSet(set);
}


static boolean isImageFile(File f) {
  return isImageFileName(fileName(f));
}


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


static <A> int compareWithComparator(Comparator<A> comparator, A a, A b) {
  return comparator == null ? cmp(a, b) : comparator.compare(a, b);
}


static F1 functionToF1(final Object f) {
  if (isString(f)) return mainFunctionToF1((String) f);
  if (f instanceof F1) return (F1) f;
  return new F1<Object, Object>() { public Object get(Object a) { try {  return callF(f, a);  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret callF(f, a);"; }};
}


static boolean isTrueOrYes(Object o) {
  return isTrueOpt(o) || o instanceof String && (eqicOneOf(((String) o), "1", "t", "true") || isYes(((String) o)));
}


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


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




static <A> IterableIterator<A> iteratorFromFunction_withEndMarker_f0(final F0<A> f) {
  class IFF2 extends IterableIterator<A> {
    A a;
    boolean have, done;
    
    public boolean hasNext() {
      getNext();
      return !done;
    }
    
    public A next() {
      getNext();
      if (done) throw fail();
      A _a = a;
      a = null;
      have = false;
      return _a;
    }
    
    void getNext() {
      if (done || have) return;
      Object o = f.get();
      if (o == iteratorFromFunction_endMarker)
        { done = true; return; }
      a = (A) o;
      have = true;
    }
  };
  return new IFF2();
}


static <A> A[] arrayOfSameType(A[] a, int n) {
  return newObjectArrayOfSameType(a, n);
}


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

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

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

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




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


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 isDigit(char c) {
  return Character.isDigit(c);
}


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 boolean isImageFileName(String s) {
  return eqicOneOf(fileExtension(s), ".png", ".jpg", ".jpeg", ".gif");
}


static String fileName(File f) {
  return f == null ? null : f.getName();
}


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

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


static boolean isString(Object o) {
  return o instanceof String;
}


static F1 mainFunctionToF1(final String fname) {
  return new F1<Object, Object>() { public Object get(Object a) { try {  return callMC(fname, a);  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "callMC(fname, a)"; }};
}


static boolean isTrueOpt(Object o) {
  if (o instanceof Boolean)
    return ((Boolean) o).booleanValue();
  return false;
}


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


static List<String> isYes_yesses = litlist("y", "yes", "yeah", "y", "yup", "yo", "corect", "sure", "ok", "afirmative"); // << collapsed words, so "corect" means "correct"

static boolean isYes(String s) {
  return isYes_yesses.contains(collapseWord(toLowerCase(firstWord2(s))));
}




static <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 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 String fileExtension(File f) {
  if (f == null) return null;
  return fileExtension(f.getName());
}

static String fileExtension(String s) {
  return substring(s, smartLastIndexOf(s, '.'));
}


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


static String collapseWord(String s) {
  if (s == null) return "";
  StringBuilder buf = new StringBuilder();
  for (int i = 0; i < l(s); i++)
    if (i == 0 || !charactersEqualIC(s.charAt(i), s.charAt(i-1)))
      buf.append(s.charAt(i));
  return buf.toString();
}


static List<String> toLowerCase(List<String> strings) {
  List<String> x = new ArrayList();
  for (String s : strings)
    x.add(s.toLowerCase());
  return x;
}

static String[] toLowerCase(String[] strings) {
  String[] x = new String[l(strings)];
  for (int i = 0; i < l(strings); i++)
    x[i] = strings[i].toLowerCase();
  return x;
}

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


static String firstWord2(String s) {
  s = xltrim(s);
  if (empty(s)) return "";
  if (isLetterOrDigit(first(s)))
    return takeCharsWhile(s, "isLetterOrDigit");
  else return "" + first(s);
}



static boolean isLetterOrDigit(char c) {
  return Character.isLetterOrDigit(c);
}


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

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


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




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


static int smartLastIndexOf(String s, char c) {
  if (s == null) return 0;
  int i = s.lastIndexOf(c);
  return i >= 0 ? i : l(s);
}

static <A> int smartLastIndexOf(List<A> l, A sub) {
  int i = lastIndexOf(l, sub);
  return i < 0 ? l(l) : i;
}


static boolean charactersEqualIC(char c1, char c2) {
  if (c1 == c2) return true;
  char u1 = Character.toUpperCase(c1);
  char u2 = Character.toUpperCase(c2);
  if (u1 == u2) return true;
  return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}



static String xltrim(String s) {
  int i = 0;
  while (i < s.length() && contains(" \t\r\n", s.charAt(i)))
    ++i;
  return substr(s, i);
}


// pred: char -> bool
static String takeCharsWhile(String s, Object pred) {
  int i = 0;
  while (i < l(s) && isTrue(callF(pred, s.charAt(i)))) ++i;
  return substring(s, 0, i);
}

static String takeCharsWhile(IF1<Character, Boolean> f, String s) {
  return takeCharsWhile(s, f);
}




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

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


static Runnable toRunnable(final Object o) {
  if (o instanceof Runnable) return (Runnable) o;
  return new Runnable() {  public void run() { try {  callF(o) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "callF(o)"; }};
}


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

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


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

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




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


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



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



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


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

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





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


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

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

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




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

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

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



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




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


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

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




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




static class DoubleRect {
  double x, y, w, h;
  
  DoubleRect() {}
  DoubleRect(Rectangle r) {
    x = r.x;
    y = r.y;
    w = r.width;
    h = r.height;
  }
  DoubleRect(double x, double y, double w, double h) {
  this.h = h;
  this.w = w;
  this.y = y;
  this.x = x;}
  
  public boolean equals(Object o) { return stdEq2(this, o); }
public int hashCode() { return stdHash2(this); }
  
  public String toString() {
    return x + "," + y + " / " + w + "," + h;
  }
  
  double x2() { return x + w; }
  double y2() { return y + h; }
  
  boolean contains(Pt p) {
    return contains(p.x, p.y);
  }
  
  boolean contains(double _x, double _y) {
    return _x >= x && _y >= y && _x < x+w && _y < y+h;
  }
  
  boolean empty() { return w <= 0 || h <= 0; }
}
static final class BWImage implements MakesBufferedImage, IBWImage {
  int width, height;
  byte[] pixels;

  // color returned when getPixel is called with a position outside the actual image
  float borderColor = 0.0f;
  
  // for unstructure()
  BWImage() {}

  // BLACK!
  BWImage(int width, int height) {
  this.height = height;
  this.width = width;
    pixels = new byte[width*height];
  }

  BWImage(int width, int height, float brightness) {
  this.height = height;
  this.width = width;
    pixels = new byte[width*height];
    fillArrayUnlessZero(pixels, _toByte(brightness));
  }
  
  BWImage(int width, int height, float[] pixels) {
    this.pixels = new byte[pixels.length];
  this.height = height;
  this.width = width;
    for (int i = 0; i < pixels.length; i++)
      this.pixels[i] = _toByte(pixels[i]);
  }

  public BWImage(int width, int height, byte[] pixels) {
    this.height = height;
    this.width = width;
    this.pixels = pixels;
  }

  public BWImage(BWImage image) {
    width = image.getWidth();
    height = image.getHeight();
    byte[] pixels = this.pixels = new byte[width*height];
    for (int y = 0; y < height; y++)
      for (int x = 0; x < width; x++)
        pixels[y*width+x] = image.getByte(x, y);
  }

  // TODO: optimize!
  BWImage(RGBImage image) {
    width = image.getWidth();
    height = image.getHeight();
    byte[] pixels = this.pixels = new byte[height*width];
    for (int y = 0; y < height; y++)
      for (int x = 0; x < width; x++) {
        RGB rgb = image.getRGB(x, y);
        pixels[y*width+x] = BWImage._toByte(rgb.getBrightness());
      }
  }

  /*public BWImage(BufferedImage image) {
    this(new RGBImage(image));
  }*/

  BWImage(BufferedImage image) { try {
 width = image.getWidth();
    height = image.getHeight();
    int[] pixels = new int[width*height];
    byte[] bytePixels = this.pixels = new byte[width*height];
    PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width);
    if (!pixelGrabber.grabPixels())
      throw fail("Could not grab pixels");
    int n = width*height;
    
    for (int i = 0; i < n; i++) {
      //bytePixels[i] = pixelToByte(pixels[i]);
      int packed = pixels[i];
      /*float r = ((packed >> 16) & 0xFF)/255f;
      float g = ((packed >> 8) & 0xFF)/255f;
      float b = (packed & 0xFF)/255f;
      bytePixels[i] = (byte) iround((r+g+b)/3.0f*255f);*/
      int r = ((packed >> 16) & 0xFF);
      int g = ((packed >> 8) & 0xFF);
      int b = (packed & 0xFF);
      bytePixels[i] = (byte) ((r+g+b+1)/3);
    }
  } catch (Exception __e) { throw rethrow(__e); } }
  
  // TODO: does it exactly match the other method? (asRGB+getBrightness+_toByte)
  static byte pixelToByte(int packed) {
    /*int r = (packed >> 16) & 0xFF;
    int g = (packed >> 8) & 0xFF;
    int b = packed & 0xFF;
    ret (byte) ((r+g+b)/3.0f);*/
    float r = ((packed >> 16) & 0xFF)/255f;
    float g = ((packed >> 8) & 0xFF)/255f;
    float b = (packed & 0xFF)/255f;
    return (byte) ((r+g+b)/3.0f*255f);
  }

  public byte getByte(int x, int y) {
    return inRange(x, y) ? getByte_noRangeCheck(x, y) : _toByte(borderColor);
  }
  
  int getInt(int x, int y) {
    return ubyteToInt(getByte(x, y));
  }

  public double averageBrightness() {
    double sum = 0;
    for (int y = 0; y < height; y++)
      for (int x = 0; x < width; x++)
        sum += getPixel(x, y);
    return (sum/(double) (height*width));
  }

  public float minimumBrightness() {
    float min = 1;
    for (int y = 0; y < height; y++)
      for (int x = 0; x < width; x++)
        min = Math.min(min, getPixel(x, y));
    return min;
  }

  public float maximumBrightness() {
    float max = 0;
    for (int y = 0; y < height; y++)
      for (int x = 0; x < width; x++)
        max = Math.max(max, getPixel(x, y));
    return max;
  }

  float getPixel(int x, int y) {
    return inRange(x, y) ? _toFloat(getByte(x,y )) : borderColor;
  }
  
  public float getFloatPixel(int x, int y) { return getPixel(x, y); }
  
  float getPixel(Pt p) { return getPixel(p.x, p.y); }

  static byte _toByte(float pixel) {
    return (byte) (pixel*255f);
  }

  static float _toFloat(byte pixel) {
    return (((int) pixel) & 255)/255f;
  }

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

  public int getWidth() { return width; }
  int w() { return width; }

  public int getHeight() { return height; }
  int h() { return height; }

  public RGBImage toRGB() {
    int[] rgbs = new int[width*height];
    for (int y = 0; y < height; y++)
      for (int x = 0; x < width; x++) {
        int b = getByte(x, y) & 0xFF;
        rgbs[y*width+x] = 0xFF000000 | b*0x010101;
      }
    return new RGBImage(width, height, rgbs);
  }
  
  public RGBImage toRGB_slow() {
    RGB[] rgbs = new RGB[width*height];
    for (int y = 0; y < height; y++)
      for (int x = 0; x < width; x++) {
        float p = getPixel(x, y);
        rgbs[y*width+x] = new RGB(p, p, p);
      }
    return new RGBImage(width, height, rgbs);
  }


  public BWImage clip(int x, int y, int w, int h) {
    return clip(new Rectangle(x, y, w, h));
  }

  private Rectangle fixClipRect(Rectangle r) {
    return r.intersection(new Rectangle(0, 0, width, height));
  }

  BWImage clip(Rect r) {
    return clip(r.getRectangle());
  }
  
  /** this should be multithread-safe */
  public BWImage clip(Rectangle r) {
    r = fixClipRect(r);
    byte[] newPixels = new byte[r.height*r.width];
    for (int y = 0; y < r.height; y++)
      for (int x = 0; x < r.width; x++)
        newPixels[y*r.width+x] = getByte(r.x+x, r.y+y);
    return new BWImage(r.width, r.height, newPixels);
  }

  public void setPixel(int x, int y, float brightness) {
    setByte(x, y, _toByte(fixPixel(brightness)));
  }
  
  // i = 0 to 255
  public void setInt(int x, int y, int i) {
    setByte(x, y, (byte) limitToUByte(i));
  }
  
  public void setByte(int x, int y, byte b) {
    if (x >= 0 && x < width && y >= 0 && y < height)
      pixels[y*width+x] = b;
  }

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

  public void setByte(int x, int y, int brightness) {
    setByte(x, y, (byte) brightness);
  }

  private float fixPixel(float pixel) {
    return Math.max(0, Math.min(1, pixel));
  }

  public float getBorderColor() {
    return borderColor;
  }

  public void setBorderColor(float borderColor) {
    this.borderColor = borderColor;
  }

  public boolean anyPixelBrighterThan(double threshold) {
    for (int y = 0; y < height; y++)
      for (int x = 0; x < width; x++)
        if (getPixel(x, y) > threshold)
          return true;
    return false;
  }
  
  public BufferedImage getBufferedImage() {
    //ret toRGB().getBufferedImage();
    
    // TYPE_BYTE_GRAY is buggy - see #1015235
    BufferedImage bufferedImage = new BufferedImage(width, height, /*BufferedImage.TYPE_BYTE_GRAY*/BufferedImage.TYPE_INT_RGB);
    for (int y = 0; y < height; y++)
      for (int x = 0; x < width; x++) {
        int b = ((int) getByte(x, y) & 0xFF);
        bufferedImage.setRGB(x, y, b*0x010101);
      }
    return bufferedImage; 
  }
  
  byte[] getBytes() {
    return pixels;
  }
}
static class T3<A, B, C> {
  A a;
  B b;
  C c;
  
  T3() {}
  T3(A a, B b, C c) {
  this.c = c;
  this.b = b;
  this.a = a;}
  T3(T3<A, B, C> t) { a = t.a; b = t.b; c = t.c; }
  
  public int hashCode() {
    return _hashCode(a) + 2*_hashCode(b) - 4*_hashCode(c);
  }
  
  public boolean equals(Object o) {
    if (o == this) return true;
    if (!(o instanceof T3)) return false;
    T3 t = (T3) o;
    return eq(a, t.a) && eq(b, t.b) && eq(c, t.c);
  }
  
  public String toString() {
    return "(" + quoteBorderless(a) + ", " + quoteBorderless(b) + ", " + quoteBorderless(c) + ")";
  }
}


static interface IBWImage {
  int getWidth();
  int getHeight();
  float getFloatPixel(int x, int y);
}


static void fillArrayUnlessZero(byte[] a, byte value) {
  if (value != 0) Arrays.fill(a, value);
}

static void fillArrayUnlessZero(int[] a, int value) {
  if (value != 0) Arrays.fill(a, value);
}

static void fillArrayUnlessZero(float[] a, float value) {
  if (value != 0) Arrays.fill(a, value);
}


static int ubyteToInt(byte b) {
  return b & 0x0FF;
}


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

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



}