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 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.*;
public class main {
// A concept should be an object, not just a string.

static class Concepts {
}

static class OurConcepts extends Concepts {
  Map<Long, Concept> concepts = synchroTreeMap();
  HashMap<Class, Object> perClassData = new HashMap<Class, Object>();
  String programID;
  long idCounter;
  volatile long changes = 1, changesWritten;
  volatile java.util.Timer autoSaver;
  volatile boolean savingConcepts;
  
  OurConcepts() { }
  OurConcepts(String programID) {
  this.programID = programID;}
  
  long newID() {
    do {
      ++idCounter;
    } while (hasConcept(idCounter));
    return idCounter;
  }
  
  synchronized void loadConceptsFrom(String programID) {
    clearConcepts();
    DynamicObject._loading = true;
    try {
      readLocally2(this, programID, "concepts");
      assignConceptsToUs();
      readLocally2(this, programID, "idCounter");
    } finally {
      DynamicObject._loading = false;
    }
  }
  
  void assignConceptsToUs() {
    for (Concept c : values(concepts)) {
      c.concepts = this;
      callOpt(c, "_doneLoading2");
    }
  }
  
  synchronized void loadConcepts() {
    loadConceptsFrom(progID());
  }
  
  String progID() {
    return programID == null ? programID() : programID;
  }
  
  Concept getConcept(String id) {
    return empty(id) ? null : getConcept(parseLong(id));
  }
  
  Concept getConcept(long id) {
    return (Concept) concepts.get((long) id);
  }
  
  Concept getConcept(PassRef ref) {
    return ref == null ? null : getConcept(ref.longID());
  }
  
  boolean hasConcept(long id) {
    return concepts.containsKey((long) id);
  }
  
  void deleteConcept(long id) {
    Concept c = getConcept(id);
    if (c == null)
      print("Concept " + id + " not found");
    else
      c.delete();
  }
  
  // call in only one thread
  void saveConceptsIfDirty() {
    savingConcepts = true;
    try {
      String s;
      synchronized(main.class) {
        if (changes == changesWritten) return;
        changesWritten = changes;
        saveLocally2(this, "idCounter");
        s = structure(cloneMap(concepts));
      }
      print("Saving " + l(s) + " chars (" + changesWritten + ")");
      saveTextFile(getProgramFile("concepts.structure"), s);
      copyFile(getProgramFile("concepts.structure"), getProgramFile("concepts.structure.backup" + ymd() + "-" + formatInt(hours(), 2)));
    } finally {
      savingConcepts = false;
    }
  }
  
  void saveConcepts() {
    saveConceptsIfDirty();
  }
  
  void clearConcepts() {
    concepts.clear();
    change();
  }
  
  synchronized void change() {
    ++changes;
  }
  
  // auto-save every second if dirty
  synchronized void autoSaveConcepts() {
    if (autoSaver == null)
      autoSaver = doEvery(1000, new Runnable() { public void run() { try {  saveConcepts(); 
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } });
  }
  
  void cleanMeUp() {
    if (autoSaver != null) {
      autoSaver.cancel();
      autoSaver = null;
    }
    while (savingConcepts) sleep(10);
    saveConceptsIfDirty();
  }
  
  Map<Long, String> getIDsAndNames() {
    Map<Long, String> map = new HashMap<Long, String>();
    Map<Long, Concept> cloned = cloneMap(concepts);
    for (long id : keys(cloned)) 
      map.put(id, cloned.get(id).className);
    return map;
  }
  
  void deleteConcepts(List<Long> ids) {
    concepts.keySet().removeAll(ids);
  }
  
  <A extends Concept> A findBackRef(Concept c, Class<A> type) {
    return findBackRefOfType(c, type);
  }
  
  <A extends Concept> A findBackRefOfType(Concept c, Class<A> type) {
    for (Concept.Ref r : c.backRefs)
      if (instanceOf(r.concept(), type))
        return (A) r.concept(); return null;
  }
  
  <A extends Concept> List<A> findBackRefs(Concept c, Class<A> type) {
    List<A> l = new ArrayList<A>();
    for (Concept.Ref r : c.backRefs)
      if (instanceOf(r.concept(), type))
        l.add((A) r.concept());
    return l;
  }
  
  <A extends Concept> A conceptOfType(Class<A> type) {
    return firstOfType(allConcepts(), type);
  }
  
  <A extends Concept> List<A> conceptsOfType(Class<A> type) {
    return filterByType(allConcepts(), type);
  }
  
  <A extends Concept> List<A> listConcepts(Class<A> type) {
    return conceptsOfType(type);
  }
  
  <A extends Concept> List<A> list(Class<A> type) {
    return conceptsOfType(type);
  }
  
  List<Concept> conceptsOfType(String type) {
    return filterByDynamicType(allConcepts(), "main$" + type);
  }
  
  boolean hasConceptOfType(Class<? extends Concept> type) {
    return hasType(allConcepts(), type);
  }
  
  void persistConcepts() {
    loadConcepts();
    autoSaveConcepts();
  }
  
  // We love synonyms
  void conceptPersistence() {
    persistConcepts();
  }
    
  // Runs r if there is no concept of that type
  <A extends Concept> A ensureHas(Class<A> c, Runnable r) {
    A a = conceptOfType(c);
    if (a == null) {
      r.run();
      a = conceptOfType(c);
      if (a == null)
        throw fail("Concept not made by " + r + ": " + shortClassName(c));
    }
    return a;
  }
  
  // Ensures that every concept of type c1 is ref'd by a concept of
  // type c2.
  // Type of func: voidfunc(concept)
  void ensureHas(Class<? extends Concept> c1, Class<? extends Concept> c2, Object func) {
    for (Concept a : conceptsOfType(c1)) {
      Concept b = findBackRef(a, c2);
      if (b == null) {
        callF(func, a);
        b = findBackRef(a, c2);
        if (b == null)
          throw fail("Concept not made by " + func + ": " + shortClassName(c2));
      }
    }
  }
  
  // Type of func: voidfunc(concept)
  void forEvery(Class<? extends Concept> type, Object func) {
    for (Concept c : conceptsOfType(type))
      callF(func, c);
  }
  
  int deleteAll(Class<? extends Concept> type) {
    List<Concept> l = (List) conceptsOfType(type);
    for (Concept c : l) c.delete();
    return l(l);
  }
  
  Collection<Concept> allConcepts() {
    synchronized(concepts) {
      return new ArrayList(values(concepts));
    }
  }
  
  Concept cnew(String name, Object... values) {
    Class<? extends Concept> cc = findClass(name);
    Concept c = cc != null ? nuObject(cc) : new Concept(name);
    csetAll(c, values);
    return c;
  }
  
  void csetAll(Concept c, Object... values) {
    for (int i = 0; i+1 < l(values); i += 2)
      cset(c, (String) values[i], values[i+1]);
  }
  
  void cset(Concept c, String field, Object value) { try {
 
    Field f = setOpt_findField(c.getClass(), field);
    print("cset: " + c.id + " " + field + " " + struct(value) + " " + f);
    if (value instanceof PassRef) value = getConcept((PassRef) value);
    if (f == null)
      c.fieldValues.put(field, value instanceof Concept ? c.new Ref((Concept) value) : value);
    else if (isSubtypeOf(f.getType(), Concept.Ref.class))
      ((Concept.Ref) f.get(c)).set((Concept) value);
    else
      f.set(c, value);
    change();
  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
  
  Object cget(Concept c, String field) {
    Object o = getOpt(c, field);
    if (o instanceof Concept.Ref) return ((Concept.Ref) o).get();
    return o;
  }
  
  PassRef toPassRef(Concept c) {
    return new PassRef(c);
  }
  
  // inter-process methods
  
  PassRef xnew(String name, Object... values) {
    return new PassRef(cnew(name, values));
  }
  
  void xset(long id, String field, Object value) {
    xset(new PassRef(id), field, value);
  }
  
  void xset(PassRef c, String field, Object value) {
    if (value instanceof PassRef)
      value = getConcept((PassRef) value);
    cset(getConcept(c), field, value);
  }
  
  Object xget(long id, String field) {
    return xget(new PassRef(id), field);
  }
  
  Object xget(PassRef c, String field) {
    return cget(getConcept(c), field);
  }
  
  void xdelete(long id) {
    xdelete(new PassRef(id));
  }
  
  void xdelete(PassRef c) {
    getConcept(c).delete();
  }
  
  List<PassRef> xlist() {
    return map("toPassRef", allConcepts());
  }
  
  List<PassRef> xlist(String className) {
    return map("toPassRef", conceptsOfType(className));
  }
}

static volatile OurConcepts outConcepts = new OurConcepts(); // Where we create new concepts

static class Concept extends DynamicObject {
  transient OurConcepts concepts; // Where we belong
  long id;
  Object madeBy;
  //double energy;
  //bool defunct;
  long created;
  
  // used only internally (cnew)
  Concept(String className) {
    super(className);
    _created();
  }
  
  Concept() {
    if (!_loading) {
      className = shortClassName(this);
      print("New concept of type " + className);
      _created();
    }
  }
  
  List<Ref> refs = new ArrayList<Ref>();
  List<Ref> backRefs = new ArrayList<Ref>();

  void _created() {
    concepts = outConcepts;
    id = concepts.newID();
    created = now();
    concepts.concepts.put((long) id, this);
    concepts.change();
  }
  
  void put(String field, Object value) {
    fieldValues.put(field, value);
    concepts.change();
  }
  
  Object get(String field) {
    return fieldValues.get(field);
  }
  
  class Ref<A extends Concept> {
    A value;
    
    Ref() {
      if (!_loading) refs.add(this);
    }
    
    Ref(A value) {
  this.value = value;
      refs.add(this);
      index();
    }
    
    // get owning concept (source)
    Concept concept() {
      return Concept.this;
    }
    
    // get target
    A get() {
      return value;
    }
    
    void set(A a) {
      if (a == value) return;
      unindex();
      value = a;
      index();
    }
    
    void set(Ref<A> ref) {
      set(ref.get());
    }
    
    void index() { 
      if (value != null)
        value.backRefs.add(this);
      concepts.change();
    }
    
    void unindex() {
      if (value != null)
        value.backRefs.remove(this);
    }
  }
  
  class RefL<A extends Concept> extends AbstractList<Concept> {
    List<Ref<A>> l = new ArrayList<Ref<A>>();
    
    public A set(int i, A o) {
      A prev = l.get(i).get();
      l.get(i).set(o);
      return prev;
    }
    
    public void add(int i, A o) {
      l.add(i, new Ref(o));
    }
    
    public A get(int i) {
      return l.get(i).get();
    }
    
    public A remove(int i) {
      return l.remove(i).get();
    }
    
    public int size() {
      return l.size();
    }
  }
  
  void delete() {
    concepts.concepts.remove((long) id);
    id = 0;
    //name = "[defunct " + name + "]";
    //defunct = true;
    //energy = 0;
    for (Ref r : refs)
      r.unindex();
    refs.clear();
    concepts.change();
  }
  
  BaseXRef export() {
    return new BaseXRef(concepts.programID, id);
  }
  
  // notice system of a change in this object
  void change() {
    concepts.change();
  }
} // class Concept

// for inter-process communication
// prepared for string ids if we do them later
static class PassRef {
  String id;
  
  PassRef() {} // make serialisation happy
  PassRef(long id) { this.id = str(id); }
  PassRef(Concept c) { this(c.id); }
  long longID() { return parseLong(id); }
  
  public String toString() {
    return id;
  }
}

static class Event extends Concept {}

// Reference to a concept in another program
static class BaseXRef {
  String programID;
  long id;
    
  BaseXRef() {}
  BaseXRef(String programID, long id) {
  this.id = id;
  this.programID = programID;}
  
  public boolean equals(Object o) {
    if (!(o instanceof BaseXRef)) return false;
    BaseXRef r = (BaseXRef) ( o);
    return eq(programID, r.programID) && eq(id, r.id);
  }
  
  public int hashCode() {
    return programID.hashCode() + (int) id;
  }
}

// BaseXRef as a concept
static class XRef extends Concept {
  BaseXRef ref;
  
  XRef() {}
  XRef(BaseXRef ref) {
  this.ref = ref; _doneLoading2(); }
  
  // after we have been added to concepts
  void _doneLoading2() {
    getIndex().put(ref, this);
  }
    
  HashMap<BaseXRef, XRef> getIndex() {
    return getXRefIndex(concepts);
  }
}

static synchronized HashMap<BaseXRef, XRef> getXRefIndex(OurConcepts concepts) {
  HashMap cache = (HashMap) concepts.perClassData.get(XRef.class);
  if (cache == null)
    concepts.perClassData.put(XRef.class, cache = new HashMap());
  return cache;
}

// uses outConcepts
static XRef lookupOrCreateXRef(BaseXRef ref) {
  XRef xref = getXRefIndex(outConcepts).get(ref);
  if (xref == null)
    xref = new XRef(ref);
  return xref;
} // Dynamic Concepts

static class CKnownString extends Concept {
  String s;
  
  CKnownString() {}
  CKnownString(String s) {
  this.s = s;}
}

static class CUnknownString extends Concept {}

static class CUnknownCharacter extends Concept {}

static class CKnownCharacter extends Concept {
  char c;
  
  CKnownCharacter() {}
  CKnownCharacter(char c) {
  this.c = c;}
}

static class CharInString extends Concept {
  Ref string = new Ref();
  int index;
  
  CharInString() {}
  CharInString(Concept string, int index) {
  this.index = index; this.string.set(string); }
}

static class CUnknownInt extends Concept {}

static class CKnownInt extends Concept {
  BigInteger value;
  
  CKnownInt() {}
  CKnownInt(int value) { this.value = bigint(value); }
}

static class CKnownEquals extends Concept {
  RefL what = new RefL();
}

static class Question extends Concept {}

static class WhichCharacterIsIt extends Question {
  Ref character = new Ref();
  Ref answer = new Ref();
  
  WhichCharacterIsIt() {}
  WhichCharacterIsIt(Concept character) { this.character.set(character); }
}

public static void main(String[] args) throws Exception {
  CKnownString s = new CKnownString("hello world");
  CharInString c = new CharInString(s, 3);
  WhichCharacterIsIt question = new WhichCharacterIsIt(c);
  tryToAnswer(question);
}

static void tryToAnswer(WhichCharacterIsIt question) {
  // We need a rewriting engine here
}

public static void copyFile(File src, File dest) { try {
 
  mkdirsForFile(dest);
  FileInputStream inputStream = new FileInputStream(src.getPath());
  FileOutputStream outputStream = new FileOutputStream(dest.getPath());
  try {
    copyStream(inputStream, outputStream);
    inputStream.close();
  } finally {
    outputStream.close();
  }

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String struct(Object o) {
  return structure(o);
}
static String formatInt(int i, int digits) {
  return padLeft(str(i), '0', digits);
}

static Object callOpt(Object o) {
  if (o == null) return null;
  return callF(o);
}

static Object callOpt(Object o, String method, Object... args) {
  try {
    if (o == null) return null;
    if (o instanceof Class) {
      Method m = callOpt_findStaticMethod((Class) o, method, args, false);
      if (m == null) return null;
      m.setAccessible(true);
      return m.invoke(null, args);
    } else {
      Method m = callOpt_findMethod(o, method, args, false);
      if (m == null) return null;
      m.setAccessible(true);
      return m.invoke(o, args);
    }
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

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

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

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

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

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


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

static Set keys(Object map) {
  return keys((Map) map);
}
static <A, B> Collection<B> values(Map<A, B> map) {
  return map.values();
}

static <A> A firstOfType(Collection c, Class<A> type) {
  for (Object x : c)
    if (isInstanceX(type, x))
      return (A) x;
  return null;
}
static Object callF(Object f, Object... args) {
  return callFunction(f, args);
}
// firstDelay = delay
static java.util.Timer doEvery(int delay, Runnable r) {
  java.util.Timer timer = new java.util.Timer();
  timer.scheduleAtFixedRate(timerTask(r), delay, delay);
  return timer;
}

static Map synchroTreeMap() {
  return Collections.synchronizedMap(new TreeMap());
}

static boolean empty(Collection c) {
  return isEmpty(c);
}

static boolean empty(String s) {
  return isEmpty(s);
}

static boolean empty(Map map) {
  return map == null || map.isEmpty();
}

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

static boolean empty(Object o) {
  if (o instanceof Collection) return empty((Collection) o);
  if (o instanceof String) return empty((String) o);
  if (o instanceof Map) return empty((Map) o);
  if (o instanceof Object[]) return empty((Object[]) o);
  throw fail("unknown type for 'empty': " + getType(o));
}
static boolean instanceOf(Object o, String className) {
  if (o == null) return false;
  String c = o.getClass().getName();
  return eq(c, className) || eq(c, "main$" + className);
}

static boolean instanceOf(Object o, Class c) {
  if (c == null) return false;
  return c.isInstance(o);
}
static void sleep(long ms) {
  try {
    Thread.sleep(ms);
  } catch (Exception e) { throw new RuntimeException(e); }
}

static void sleep() { try {
 
  print("Sleeping.");
  synchronized(main.class) { main.class.wait(); }

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String ymd() {
  return year() + formatInt(month(), 2) + formatInt(dayOfMonth(), 2);
}
static long now_virtualTime;
static long now() {
  return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}

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

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

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

static Class get_dynamicObject = findClass("DynamicObject");

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

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

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

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

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

static Field get_findField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field))
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static String shortClassName(Object o) {
  if (o == null) return null;
  Class c = o instanceof Class ? (Class) o : o.getClass();
  String name = c.getName();
  return substring(name, xIndexOf(name, '$')+1);
}
static List map(Iterable l, Object f) {
  return map(f, l);
}

static List map(Object f, Iterable l) {
  List x = new ArrayList();
  Object mc = mc();
  for (Object o : unnull(l))
    x.add(callFunction(f, o));
  return x;
}

static List map(Object f, Object[] l) {
  return map(f, asList(l));
}
static BigInteger bigint(String s) {
  return new BigInteger(s);
}

static BigInteger bigint(long l) {
  return BigInteger.valueOf(l);
}
static String programID() {
  return getProgramID();
}
static File getProgramFile(String progID, String fileName) {
  if (new File(fileName).isAbsolute())
    return new File(fileName);
  return new File(getProgramDir(progID), fileName);
}

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

static void saveLocally(String variableName) {
  saveLocally(programID(), variableName);
}

static void saveLocally(String progID, String variableName) {
  saveLocally2(mc(), progID, variableName);
}

static void saveLocally2(Object obj, String variableName) {
  saveLocally2(obj, programID(), variableName);
}

static synchronized void saveLocally2(Object obj, String progID, String variableName) {
  File textFile = new File(programDir(progID), variableName + ".text");
  File structureFile = new File(programDir(progID), variableName + ".structure");
  Object x = get(obj, variableName);
  
  if (x == null) {
    textFile.delete();
    structureFile.delete();
  } else if (x instanceof String) {
    saveTextFile(textFile, (String) x);
    structureFile.delete();
  } else {
    saveTextFile(structureFile, structure(x));
    textFile.delete();
  }
}
static int hours() {
  return Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
}
static <A, B> Map<A, B> cloneMap(Map<A, B> map) {
  if (map == null) return litmap();
  // assume mutex is equal to collection, which will be true unless you explicitly pass a mutex to synchronizedList() which no one ever does.
  synchronized(map) {
    return new HashMap(map);
  }
}
static void set(Object o, String field, Object value) {
  if (o instanceof Class) set((Class) o, field, value);
  else try {
    Field f = set_findField(o.getClass(), field);
    smartSet(f, o, value);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

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

static Field set_findField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field))
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static <A> List<A> filterByDynamicType(Collection<A> c, String type) {
  List<A> l = new ArrayList<A>();
  for (A x : c)
    if (eq(dynamicClassName(x), type))
      l.add(x);
  return l;
}
static <A> List<A> filterByType(Collection c, Class<A> type) {
  List<A> l = new ArrayList<A>();
  for (Object x : c)
    if (isInstanceX(type, x))
      l.add((A) x);
  return l;
}
// currently finds only inner classes of class "main"
// returns null on not found
// this is the simple version that is not case-tolerant
static Class findClass(String name) {
  if (!isJavaIdentifier(name)) return null;
  try {
    return Class.forName("main$" + name);
  } catch (ClassNotFoundException e) {
    return null;
  }
}
static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] a) { return a == null ? 0 : a.length; }
static int l(char[] a) { return a == null ? 0 : a.length; }
static int l(Collection c) { return c == null ? 0 : c.size(); }
static int l(Map m) { return m == null ? 0 : m.size(); }
static int l(CharSequence s) { return s == null ? 0 : s.length(); } 

static int l(Object o) {
  return l((List) o); // incomplete
}

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

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

static <A> ArrayList<A> list(Set<A> s) {
  return asList(s);
}
static boolean eq(Object a, Object b) {
  if (a == null) return b == null;
  if (a.equals(b)) return true;
  if (a instanceof BigInteger) {
    if (b instanceof Integer) return a.equals(BigInteger.valueOf((Integer) b));
    if (b instanceof Long) return a.equals(BigInteger.valueOf((Long) b));
  }
  return false;
}
static String structure(Object o) {
  HashSet refd = new HashSet();
  return structure_2(structure_1(o, new structure_Data(refd)), refd);
}

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

static int structure_shareStringsLongerThan = 20;

static class structure_Data {
  int stringSizeLimit;
  IdentityHashMap<Object, Integer> seen = new IdentityHashMap<Object, Integer>();
  HashSet<Integer> refd;
  HashMap<String, Integer> strings = new HashMap<String, Integer>();
  HashSet<String> concepts = new HashSet<String>();
  Class conceptClass = findClass("Concept");
  
  structure_Data(HashSet<Integer> refd) {
  this.refd = refd;}
}

static String structure_1(Object o, structure_Data d) {
  if (o == null) return "null";
  
  // these are never back-referenced (for readability)
  
  if (o instanceof BigInteger)
    return "bigint(" + o + ")";
  
  if (o instanceof Double)
    return "d(" + quote(str(o)) + ")";
    
  if (o instanceof Float)
    return "fl " + quote(str(o));
    
  if (o instanceof Long)
    return o + "L";
  
  if (o instanceof Integer)
    return str(o);
    
  if (o instanceof Boolean)
    return ((Boolean) o).booleanValue() ? "t" : "f";
    
  if (o instanceof Character)
    return quoteCharacter((Character) o);
    
  if (o instanceof File)
    return "File " + quote(((File) o).getPath());
    
  // referencable objects follow
  
  Integer ref = d.seen.get(o);
  if (ref != null) {
    d.refd.add(ref);
    return "r" + ref;
  }
      
  if (o instanceof String && (ref = d.strings.get((String) o)) != null) {
    d.refd.add(ref);
    return "r" + ref;
  }
  
  ref = d.seen.size()+1;
  d.seen.put(o, ref);
  String r = "m" + ref + " "; // marker

  if (o instanceof String) {
    String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o;
    if (l(s) >= structure_shareStringsLongerThan)
      d.strings.put(s, ref);
    return r + quote(s);
  }
    
  String name = o.getClass().getName();

  StringBuilder buf = new StringBuilder();
  
  if (o instanceof HashSet)
    return r + "hashset " + structure_1(new ArrayList((Set) o), d);

  if (o instanceof TreeSet)
    return r + "treeset " + structure_1(new ArrayList((Set) o), d);
  
  if (o instanceof Collection) {
    for (Object x : (Collection) o) {
      if (buf.length() != 0) buf.append(", ");
      buf.append(structure_1(x, d));
    }
    return r + "[" + buf + "]";
  }
  
  if (o instanceof Map) {
    for (Object e : ((Map) o).entrySet()) {
      if (buf.length() != 0) buf.append(", ");
      buf.append(structure_1(((Map.Entry) e).getKey(), d));
      buf.append("=");
      buf.append(structure_1(((Map.Entry) e).getValue(), d));
    }
    return r + (o instanceof HashMap ? "hashmap" : "") + "{" + buf + "}";
  }
  
  if (o.getClass().isArray()) {
    if (o instanceof byte[])
      return "ba " + quote(bytesToHex((byte[]) o));

    int n = Array.getLength(o);
    for (int i = 0; i < n; i++) {
      if (buf.length() != 0) buf.append(", ");
      buf.append(structure_1(Array.get(o, i), d));
    }
    return r + "array{" + buf + "}";
  }

  if (o instanceof Class)
    return r + "class(" + quote(((Class) o).getName()) + ")";
    
  if (o instanceof Throwable)
    return r + "exception(" + quote(((Throwable) o).getMessage()) + ")";
    
  if (o instanceof BitSet) {
    BitSet bs = (BitSet) o;
    for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
      if (buf.length() != 0) buf.append(", ");
       buf.append(i);
    }
    return "bitset{" + buf + "}";
  }
    
  // Need more cases? This should cover all library classes...
  if (name.startsWith("java.") || name.startsWith("javax."))
    return r + String.valueOf(o);
    
  String shortName = o.getClass().getName().replaceAll("^main\\$", "");
  
  if (shortName.equals("Lisp")) {
    buf.append("l(" + structure_1(getOpt(o, "head"), d));
    List args = (List) ( getOpt(o, "args"));
    if (nempty(args))
      for (int i = 0; i < l(args); i++) {
        buf.append(", ");
        Object arg = args.get(i);
        
        // sweet shortening
        if (arg != null && eq(arg.getClass().getName(), "main$Lisp") && isTrue(call(arg, "isEmpty")))
          arg = get(arg, "head");
          
        buf.append(structure_1(arg, d));
      }
    buf.append(")");
    return r + str(buf);
  }
    
  int numFields = 0;
  String fieldName = "";
  if (shortName.equals("DynamicObject")) {
    shortName = (String) get_raw(o, "className");
    Map<String, Object> fieldValues = (Map) get_raw(o, "fieldValues");
    
    for (String _fieldName : fieldValues.keySet()) {
      fieldName = _fieldName;
      Object value = fieldValues.get(fieldName);
      if (value != null) {
        if (buf.length() != 0) buf.append(", ");
        buf.append(fieldName + "=" + structure_1(value, d));
      }
      ++numFields;
   }
  } else {
    // regular class
    
    Class c = o.getClass();
    
    if (d.conceptClass != null && d.conceptClass.isInstance(o) && !d.concepts.contains(c.getName())) {
      d.concepts.add(c.getName());
      r += "c ";
    }
    
    while (c != Object.class) {
      List<Field> fields = asList(c.getDeclaredFields());
      for (int i = 1; i < l(fields); i++)
        if (eq(fields.get(i).getName(), "this$1")) {
          swapElements(fields, 0, i);
          break;
        }
      for (Field field : fields) {
        if ((field.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) != 0)
          continue;
        fieldName = field.getName();
        
        // skip outer object reference
        //if (fieldName.indexOf("$") >= 0) continue;
  
        Object value;
        try {
          field.setAccessible(true);
          value = field.get(o);
        } catch (Exception e) {
          value = "?";
        }
        
        // put special cases here...
    
        if (value != null) {
          if (buf.length() != 0) buf.append(", ");
          buf.append(fieldName + "=" + structure_1(value, d));
        }
        ++numFields;
      }
      c = c.getSuperclass();
    }
  }
  
  String b = buf.toString();
  
  if (numFields == 1 && structure_allowShortening)
    b = b.replaceAll("^" + fieldName + "=", ""); // drop field name if only one
  String s = shortName;
  if (buf.length() != 0)
    s += "(" + b + ")";
  return r + s;
}

// drop unused markers
static String structure_2(String s, HashSet<Integer> refd) {
  List<String> tok = javaTok(s);
  StringBuilder out = new StringBuilder();
  for (int i = 1; i < l(tok); i += 2) {
    String t = tok.get(i);
    if (t.startsWith("m") && isInteger(t.substring(1))
      && !refd.contains(parseInt(t.substring(1))))
      continue;
    out.append(t).append(tok.get(i+1));
  }
  return str(out);
}

static boolean isSubtypeOf(Class a, Class b) {
  return b.isAssignableFrom(a); // << always hated that method, let's replace it!
}
static String str(Object o) {
  return String.valueOf(o);
}
  static RuntimeException fail() {
    throw new RuntimeException("fail");
  }
  
  static RuntimeException fail(Object msg) {
    throw new RuntimeException(String.valueOf(msg));
  }
  
  static RuntimeException fail(String msg) {
    throw new RuntimeException(unnull(msg));
  }
   
  // disabled for now to shorten some programs 
  /*static RuntimeException fail(S msg, O... args) {
    throw new RuntimeException(format(msg, args));
  }*/
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile StringBuffer print_log = local_log; // might be redirected, e.g. to main bot

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

static boolean print_silent; // total mute if set

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

// slightly overblown signature to return original object...
static <A> A print(A o) {
  if (print_silent) return o;
  String s = String.valueOf(o) + "\n";
  // TODO if (print_maxLineLength != 0)
  StringBuffer loc = local_log;
  StringBuffer buf = print_log;
  int loc_max = print_log_max;
  if (buf != loc && buf != null) {
    print_append(buf, s, print_log_max);
    loc_max = local_log_max;
  }
  if (loc != null) 
    print_append(loc, s, loc_max);
  System.out.print(s);
  return o;
}

static void print(long l) {
  print(String.valueOf(l));
}

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

static void print_append(StringBuffer buf, String s, int max) {
  synchronized(buf) {
    buf.append(s);
    max /= 2;
    if (buf.length() > max) try {
      int newLength = max/2;
      int ofs = buf.length()-newLength;
      String newString = buf.substring(ofs);
      buf.setLength(0);
      buf.append("[...] ").append(newString);
    } catch (Exception e) {
      buf.setLength(0);
    }
  }
}
static Object getOpt(Object o, String field) {
  if (o instanceof String) o = getBot ((String) o);
  if (o == null) return null;
  if (o instanceof Class) return getOpt((Class) o, field);
  
  if (o.getClass().getName().equals("main$DynamicObject"))
    return ((Map) getOpt_raw(o, "fieldValues")).get(field);
  
  if (o instanceof Map) return ((Map) o).get(field);
  
  return getOpt_raw(o, field);
}

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

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

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

static 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 long parseLong(String s) {
  if (s == null) return 0;
  return Long.parseLong(dropSuffix("L", s));
}

static long parseLong(Object s) {
  return Long.parseLong((String) s);
}
  /** writes safely (to temp file, then rename) */
  public static void saveTextFile(String fileName, String contents) throws IOException {
    File file = new File(fileName);
    File parentFile = file.getParentFile();
    if (parentFile != null)
      parentFile.mkdirs();
    String tempFileName = fileName + "_temp";
    File tempFile = new File(tempFileName);
    if (contents != null) {
      if (tempFile.exists()) try {
        String saveName = tempFileName + ".saved." + now();
        copyFile(tempFile, new File(saveName));
      } catch (Throwable e) { printStackTrace(e); }
      FileOutputStream fileOutputStream = new FileOutputStream(tempFile.getPath());
      OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
      PrintWriter printWriter = new PrintWriter(outputStreamWriter);
      printWriter.print(contents);
      printWriter.close();
    }
    
    if (file.exists() && !file.delete())
      throw new IOException("Can't delete " + fileName);

    if (contents != null)
      if (!tempFile.renameTo(file))
        throw new IOException("Can't rename " + tempFile + " to " + file);
  }
  
  public static void saveTextFile(File fileName, String contents) {
    try {
      saveTextFile(fileName.getPath(), contents);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

static boolean equals(Object a, Object b) {
  return a == null ? b == null : a.equals(b);
}
static Object nuObject(String className, Object... args) { try {
 
  return nuObject(Class.forName(className), args);

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}

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

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

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}

static Constructor nuObject_findConstructor(Class c, Object... args) {
  for (Constructor m : c.getDeclaredConstructors()) {
    if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
      continue;
    return m;
  }
  throw new RuntimeException("Constructor with " + args.length + " matching parameter(s) not found in " + c.getName());
}

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

static void readLocally(String varNames) {
  readLocally2(mc(), programID(), varNames);
}

static void readLocally2(Object obj, String varNames) {
  readLocally2(obj, programID(), varNames);
}

// read a string variable from standard storage
// does not overwrite variable contents if there is no file
static synchronized void readLocally2(Object obj, String progID, String varNames) {
  for (String variableName : codeTokensOnly(javaTok(varNames))) {
    File textFile = new File(programDir(progID), variableName + ".text");
    File structureFile = new File(programDir(progID), variableName + ".structure");
    
    String value = loadTextFile(textFile);
    if (value != null)
      set(main.class, variableName, value);
    else {
      value = loadTextFile(structureFile);
      if (value != null)
      readLocally_set(obj, variableName, unstructure(value));
    }
  }
}

static void readLocally_set(Object c, String varName, Object value) {
  Object oldValue = get(c, varName);
  if (oldValue instanceof List && !(oldValue instanceof ArrayList) && value != null) {
    // Assume it's a synchroList.
    value = synchroList((List) value);
  }
  set(c, varName, value);
}

static boolean hasType(Collection c, Class type) {
  for (Object x : c)
    if (isInstanceX(type, x))
      return true;
  return false;
}


static int year() {
  return Calendar.getInstance().get(Calendar.YEAR);
}
static Object callFunction(Object f, Object... args) {
  if (f == null) return null;
  if (f instanceof Runnable) {
    ((Runnable) f).run();
    return null;
  } else if (f instanceof String)
    return call(mc(), (String) f, args);
  else
    return call(f, "get", args);
  //else throw fail("Can't call a " + getClassName(f));
}
static <A> ArrayList<A> asList(A[] a) {
  return new ArrayList<A>(Arrays.asList(a));
}

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

static <A> ArrayList<A> asList(Iterable<A> s) {
  if (s instanceof ArrayList) return (ArrayList) s;
  ArrayList l = new ArrayList();
  if (s != null)
    for (A a : s)
      l.add(a);
  return l;
}
  public static String bytesToHex(byte[] bytes) {
    return bytesToHex(bytes, 0, bytes.length);
  }

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

static void swapElements(List l, int i, int j) {
  if (i == j) return;
  Object o = l.get(i);
  l.set(i, l.get(j));
  l.set(j, o);
}
static boolean isInteger(String s) {
  return s != null && Pattern.matches("\\-?\\d+", s);
}
static RuntimeException asRuntimeException(Throwable t) {
  return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
  static String quote(String s) {
    if (s == null) return "null";
    return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r", "\\r").replace("\n", "\\n") + "\"";
  }
  
  static String quote(long l) {
    return quote("" + l);
  }
  
  static String quote(char c) {
    return quote("" + c);
  }

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

static File programDir(String snippetID) {
  return new File(javaxDataDir(), formatSnippetID(snippetID));
}

static Object getBot(String botID) {
  return callOpt(getMainBot(), "getBot", botID);
}

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

// extended over Class.isInstance() to handle primitive types
static boolean isInstanceX(Class type, Object arg) {
  if (type == boolean.class) return arg instanceof Boolean;
  if (type == int.class) return arg instanceof Integer;
  if (type == long.class) return arg instanceof Long;
  if (type == float.class) return arg instanceof Float;
  if (type == short.class) return arg instanceof Short;
  if (type == char.class) return arg instanceof Character;
  if (type == byte.class) return arg instanceof Byte;
  if (type == double.class) return arg instanceof Double;
  return type.isInstance(arg);
}
static void printStackTrace(Throwable e) {
  // we go to system.out now - system.err is nonsense
  print(getStackTrace(e));
}

static void printStackTrace() {
  printStackTrace(new Throwable());
}
// returns l(s) if not found
static int xIndexOf(String s, String sub, int i) {
  if (s == null) return 0;
  i = s.indexOf(sub, min(i, l(s)));
  return i >= 0 ? i : l(s);
}

static int xIndexOf(String s, String sub) {
  return xIndexOf(s, sub, 0);
}

static int xIndexOf(String s, char c) {
  if (s == null) return 0;
  int i = s.indexOf(c);
  return i >= 0 ? i : l(s);
}
  static List<String> codeTokensOnly(List<String> tok) {
    List<String> l = new ArrayList<String>();
    for (int i = 1; i < tok.size(); i += 2)
      l.add(tok.get(i));
    return l;
  }
static Map litmap(Object... x) {
  TreeMap map = new TreeMap();
  litmap_impl(map, x);
  return map;
}

static void litmap_impl(Map map, Object... x) {
  for (int i = 0; i < x.length-1; i += 2)
    if (x[i+1] != null)
      map.put(x[i], x[i+1]);
}
static int month() {
  return Calendar.getInstance().get(Calendar.MONTH)+1;
}
static String getType(Object o) {
  return getClassName(o);
}
static int dayOfMonth() {
  return days();
}
static boolean isJavaIdentifier(String s) {
  if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0)))
    return false;
  for (int i = 1; i < s.length(); i++)
    if (!Character.isJavaIdentifierPart(s.charAt(i)))
      return false;
  return true;
}
public static File mkdirsForFile(File file) {
  File dir = file.getParentFile();
  if (dir != null) // is null if file is in current dir
    dir.mkdirs();
  return file;
}

static TimerTask timerTask(final Runnable r) {
  return new TimerTask() {
    public void run() {
      r.run();
    }
  };
}
static String programID;

static String getProgramID() {
  return nempty(programID) ? formatSnippetID(programID) : "?";
}

// TODO: ask JavaX instead
static String getProgramID(Class c) {
  String id = (String) getOpt(c, "programID");
  if (nempty(id))
    return formatSnippetID(id);
  return "?";
}

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

  static String unnull(String s) {
    return s == null ? "" : s;
  }
  
  static <A> List<A> unnull(List<A> l) {
    return l == null ? emptyList() : l;
  }
  
  static <A> Iterable<A> unnull(Iterable<A> i) {
    return i == null ? emptyList() : i;
  }
  
  static Object[] unnull(Object[] a) {
    return a == null ? new Object[0] : a;
  }
// replacement for class JavaTok
// maybe incomplete, might want to add floating point numbers
// todo also: extended multi-line strings

static int javaTok_n, javaTok_elements;
static boolean javaTok_opt;

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

static List<String> javaTok(String s, List<String> existing) {
  ++javaTok_n;
  int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
  List<String> tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
  int l = s.length();
  
  int i = 0, n = 0;
  while (i < l) {
    int j = i;
    char c; String cc;
    
    // scan for whitespace
    while (j < l) {
      c = s.charAt(j);
      cc = s.substring(j, Math.min(j+2, l));
      if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
        ++j;
      else if (cc.equals("/*")) {
        do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
        j = Math.min(j+2, l);
      } else if (cc.equals("//")) {
        do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
      } else
        break;
    }
    
    if (n < nExisting && javaTok_isCopyable(existing.get(n), s, i, j))
      tok.add(existing.get(n));
    else
      tok.add(quickSubstring(s, i, j));
    ++n;
    i = j;
    if (i >= l) break;
    c = s.charAt(i); // cc is not needed in rest of loop body
    cc = s.substring(i, Math.min(i+2, l));

    // scan for non-whitespace
    if (c == '\'' || c == '"') {
      char opener = c;
      ++j;
      while (j < l) {
        if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors
          ++j;
          break;
        } else if (s.charAt(j) == '\\' && j+1 < l)
          j += 2;
        else
          ++j;
      }
    } else if (Character.isJavaIdentifierStart(c))
      do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
    else if (Character.isDigit(c)) {
      do ++j; while (j < l && Character.isDigit(s.charAt(j)));
      if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
    } else if (cc.equals("[[")) {
      do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
      j = Math.min(j+2, l);
    } else if (cc.equals("[=") && i+2 < l && s.charAt(i+2) == '[') {
      do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
      j = Math.min(j+3, l);
    } else
      ++j;

    if (n < nExisting && javaTok_isCopyable(existing.get(n), s, i, j))
      tok.add(existing.get(n));
    else
      tok.add(quickSubstring(s, i, j));
    ++n;
    i = j;
  }
  
  if ((tok.size() % 2) == 0) tok.add("");
  javaTok_elements += tok.size();
  return tok;
}

static List<String> javaTok(List<String> tok) {
  return javaTok(join(tok), tok);
}

static boolean javaTok_isCopyable(String t, String s, int i, int j) {
  return t.length() == j-i
    && s.regionMatches(i, t, 0, j-i); // << could be left out, but that's brave
}
static Object unstructure(String text) {
  return unstructure(text, false);
}

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

static int structure_internStringsLongerThan = 50;

// TODO: backrefs for hashmap{} etc
// classFinder: name -> class
static Object unstructure(String text, final boolean allDynamic,
  final Object classFinder) {
  if (text == null) return null;
  final List<String> tok = javaTok(text);
  final boolean debug = unstructure_debug;
  
  class X {
    int i = 1;
    HashMap<Integer, Object> refs = new HashMap<Integer, Object>();
    HashSet<String> concepts = new HashSet<String>();

    Object parse() {
      String t = tok.get(i);
      
      int refID = 0;
      if (t.startsWith("m") && isInteger(t.substring(1))) {
        refID = parseInt(t.substring(1));
        i += 2;
        t = tok.get(i);
      }
      
      if (debug)
        print("parse: " + quote(t));
        
      if (t.startsWith("'")) {
        char c = unquoteCharacter(tok.get(i));
        i += 2;
        return c;
      }
      if (t.equals("bigint"))
        return parseBigInt();
      if (t.equals("d"))
        return parseDouble();
      if (t.equals("fl"))
        return parseFloat();
      if (t.equals("false") || t.equals("f")) {
        i += 2; return false;
      }
      if (t.equals("true") || t.equals("t")) {
        i += 2; return true;
      }
      if (t.equals("-")) {
        t = tok.get(i+2);
        i += 4;
        return isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t));
      }
      if (isInteger(t) || isLongConstant(t)) {
        i += 2;
        if (debug)
          print("isLongConstant " + quote(t) + " => " + isLongConstant(t));
        if (isLongConstant(t)) return parseLong(t);
        long l = parseLong(t);
        boolean isInt = l == (int) l;
        if (debug)
          print("l=" + l + ", isInt: " + isInt);
        return isInt ? (Object) new Integer((int) l) : (Object) new Long(l);
      }
      
      if (t.equals("File")) {
        File f = new File(unquote(tok.get(i+2)));
        i += 4;
        return f;
      }
      
      if (t.startsWith("r") && isInteger(t.substring(1))) {
        i += 2;
        int ref = Integer.parseInt(t.substring(1));
        Object o = refs.get(ref);
        if (o == null)
          print("Warning: unsatisfied back reference " + ref);
        return o;
      }
      
      Object o = parse_inner(refID);
      if (refID != 0)
        refs.put(refID, o);
      return o;
    }
    
    // everything that can be backreferenced
    Object parse_inner(int refID) {
      String t = tok.get(i);
      
      if (debug)
        print("parse_inner: " + quote(t));
        
      if (t.startsWith("\"")) {
        String s = internIfLongerThan(unquote(tok.get(i)), structure_internStringsLongerThan);
        i += 2;
        return s;
      }
      if (t.equals("hashset"))
        return parseHashSet();
      if (t.equals("treeset"))
        return parseTreeSet();
      if (t.equals("hashmap"))
        return parseHashMap();
      if (t.equals("{"))
        return parseMap();
      if (t.equals("["))
        return parseList();
      if (t.equals("array"))
        return parseArray();
      if (t.equals("ba")) {
        String hex = unquote(tok.get(i+2));
        i += 4;
        return hexToBytes(hex);
      }
      if (t.equals("class"))
        return parseClass();
      if (t.equals("l"))
        return parseLisp();
      if (t.equals("null")) {
        i += 2; return null;
      }
      
      /* in dev.
      if (!allDynamic && t.equals("run")) {
        S snippetID = unquote(t.get(i+2));
        i += 4;
        run(
      }
      */
      
      boolean concept = eq(t, "c");
      if (concept) {
        consume("c");
        t = tok.get(i);
        assertTrue(isJavaIdentifier(t));
        concepts.add(t);
      }

      // any other class name
      if (isJavaIdentifier(t)) {
        // First, find class
        Class c;
        if (allDynamic) c = null;
        else if (classFinder != null)
          c = (Class) callF(classFinder, t);
        else
          c = findClass(t);
          
        // Second, check if it has an outer reference
        i += 2;
        boolean hasOuter = eq(get(tok, i), "(") && eq(get(tok, i+2), "this$1");
        
        DynamicObject dO = null;
        Object o = null;
        if (c != null)
          o = hasOuter ? nuStubInnerObject(c) : nuObject(c);
        else {
          if (concepts.contains(t) && (c = findClass("Concept")) != null)
            dO = (DynamicObject) nuObject(c);
          else
            dO = new DynamicObject();
          dO.className = t;
        }
        
        // Now, save in references list.
        
        if (refID != 0)
          refs.put(refID, o != null ? o : dO);
        
        // NOW parse the fields!
        
        Map<String, Object> fields = new TreeMap<String, Object>();
        if (i < tok.size() && tok.get(i).equals("(")) {
          consume("(");
          while (!tok.get(i).equals(")")) {
            String key = unquote(tok.get(i));
            i += 2;
            consume("=");
            Object value = parse();
            fields.put(key, value);
            if (tok.get(i).equals(",")) i += 2;
          }
          consume(")");
        }

        if (o != null)
          setOptAll(o, fields);
        else
          dO.fieldValues.putAll(fields);

        if (o != null)
          pcallOpt(o, "_doneLoading");
        return o != null ? o : dO;
      }
      throw new RuntimeException("Unknown token " + (i+1) + ": " + t);
    }
    
    Object parseSet(Set set) {
      set.addAll((List) parseList());
      return set;
    }
    
    Object parseLisp() {
      consume("l");
      consume("(");
      List list = new ArrayList();
      while (!tok.get(i).equals(")")) {
        list.add(parse());
        if (tok.get(i).equals(",")) i += 2;
      }
      consume(")");
      return newObject("main$Lisp", (String) list.get(0), subList(list, 1));
    }
    
    Object parseList() {
      consume("[");
      List list = new ArrayList();
      while (!tok.get(i).equals("]")) {
        Object o = parse();
        if (debug)
          print("List element type: " + getClassName(o));
        list.add(o);
        if (tok.get(i).equals(",")) i += 2;
      }
      consume("]");
      return list;
    }
    
    Object parseArray() {
      consume("array");
      consume("{");
      List list = new ArrayList();
      while (!tok.get(i).equals("}")) {
        list.add(parse());
        if (tok.get(i).equals(",")) i += 2;
      }
      consume("}");
      return list.toArray();
    }
    
    Object parseClass() {
      consume("class");
      consume("(");
      String name = tok.get(i);
      i += 2;
      consume(")");
      Class c = allDynamic ? null : findClass(name);
      if (c != null) return c;
      DynamicObject dO = new DynamicObject();
      dO.className = "java.lang.Class";
      dO.fieldValues.put("name", name);
      return dO;
    }
    
    Object parseBigInt() {
      consume("bigint");
      consume("(");
      String val = tok.get(i);
      i += 2;
      if (eq(val, "-")) {
        val = "-" + tok.get(i);
        i += 2;
      }
      consume(")");
      return new BigInteger(val);
    }
    
    Object parseDouble() {
      consume("d");
      consume("(");
      String val = unquote(tok.get(i));
      i += 2;
      consume(")");
      return Double.parseDouble(val);
    }
    
    Object parseFloat() {
      consume("fl");
      String val;
      if (eq(tok.get(i), "(")) {
        consume("(");
        val = unquote(tok.get(i));
        i += 2;
        consume(")");
      } else {
        val = unquote(tok.get(i));
        i += 2;
      }
      return Float.parseFloat(val);
    }
    
    Object parseHashMap() {
      consume("hashmap");
      return parseMap(new HashMap());
    }
    
    Object parseHashSet() {
      consume("hashset");
      return parseSet(new HashSet());
    }
    
    Object parseTreeSet() {
      consume("treeset");
      return parseSet(new TreeSet());
    }
    
    Object parseMap() {
      return parseMap(new TreeMap());
    }
    
    Object parseMap(Map map) {
      consume("{");
      while (!tok.get(i).equals("}")) {
        Object key = parse();
        consume("=");
        Object value = parse();
        map.put(key, value);
        if (tok.get(i).equals(",")) i += 2;
      }
      consume("}");
      return map;
    }
    
    void consume(String s) {
      if (!tok.get(i).equals(s)) {
        String prevToken = i-2 >= 0 ? tok.get(i-2) : "";
        String nextTokens = join(tok.subList(i, Math.min(i+4, tok.size())));
        throw fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")");
      }
      i += 2;
    }
  }
  
  return new X().parse();
}

static boolean unstructure_debug;
static String substring(String s, int x) {
  return safeSubstring(s, x);
}

static String substring(String s, int x, int y) {
  return safeSubstring(s, x, y);
}
static <A> List<A> synchroList() {
  return Collections.synchronizedList(new ArrayList<A>());
}

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

static String padLeft(String s, char c, int n) {
  return rep(c, n-l(s)) + s;
}
  public static String loadTextFile(String fileName) {
    try {
      return loadTextFile(fileName, null);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  
  public static String loadTextFile(String fileName, String defaultContents) throws IOException {
    if (!new File(fileName).exists())
      return defaultContents;

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

  public static String loadTextFile(File fileName, String defaultContents) throws IOException {
    try {
      return loadTextFile(fileName.getPath(), defaultContents);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  
  public static String loadTextFile(Reader reader) throws IOException {
    StringBuilder builder = new StringBuilder();
    try {
      char[] buffer = new char[1024];
      int n;
      while (-1 != (n = reader.read(buffer)))
        builder.append(buffer, 0, n);
        
    } finally {
      reader.close();
    }
    return builder.toString();
  }
static boolean isEmpty(Collection c) {
  return c == null || c.isEmpty();
}

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

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

static boolean isEmpty(Map map) {
  return map == null || map.isEmpty();
}
static boolean nempty(Collection c) {
  return !isEmpty(c);
}

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

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

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

static boolean nempty(Iterator i) {
  return i != null && i.hasNext();
}
static String dropSuffix(String suffix, String s) {
  return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static void smartSet(Field f, Object o, Object value) throws Exception {
  f.setAccessible(true);
  
  // take care of common case (long to int)
  if (f.getType() == int.class && value instanceof Long)
    value = ((Long) value).intValue();
    
  f.set(o, value);
}
static File getProgramDir() {
  return programDir();
}

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

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

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

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

  static Method call_findMethod(Object o, String method, Object[] args, boolean debug) {
    Class c = o.getClass();
    while (c != null) {
      for (Method m : c.getDeclaredMethods()) {
        if (debug)
          System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
        if (m.getName().equals(method) && call_checkArgs(m, args, debug))
          return m;
      }
      c = c.getSuperclass();
    }
    throw new RuntimeException("Method '" + method + "' (non-static) with " + args.length + " parameter(s) not found in " + o.getClass().getName());
  }

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


static String dynamicClassName(Object o) {
  if (o instanceof DynamicObject) return "main$" + ((DynamicObject) o).className;
  return className(o);
}
static int parseInt(String s) {
  return empty(s) ? 0 : Integer.parseInt(s);
}
// hmm, this shouldn't call functions really. That was just
// for coroutines.
static boolean isTrue(Object o) {
  if (o instanceof Boolean)
    return ((Boolean) o).booleanValue();
  if (o == null) return false;
  return ((Boolean) callF(o)).booleanValue();
}

static boolean isTrue(Object pred, Object arg) {
  return booleanValue(callF(pred, arg));
}
static void copyStream(InputStream in, OutputStream out) { try {
 
  byte[] buf = new byte[65536];
  while (true) {
    int n = in.read(buf);
    if (n <= 0) return;
    out.write(buf, 0, n);
  }

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}


// hopefully covers all cases :)
static String safeSubstring(String s, int x, int y) {
  if (s == null) return null;
  if (x < 0) x = 0;
  if (x > s.length()) return "";
  if (y < x) y = x;
  if (y > s.length()) y = s.length();
  return s.substring(x, y);
}

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

  public static String join(String glue, Iterable<String> strings) {
    StringBuilder buf = new StringBuilder();
    Iterator<String> i = strings.iterator();
    if (i.hasNext()) {
      buf.append(i.next());
      while (i.hasNext())
        buf.append(glue).append(i.next());
    }
    return buf.toString();
  }
  
  public static String join(String glue, String[] strings) {
    return join(glue, Arrays.asList(strings));
  }
  
  public static String join(Iterable<String> strings) {
    return join("", strings);
  }
  
  public static String join(String[] strings) {
    return join("", strings);
  }

static byte[] hexToBytes(String s) {
  int n = l(s) / 2;
  byte[] bytes = new byte[n];
  for (int i = 0; i < n; i++)
    bytes[i] = (byte) parseHexByte(substring(s, i*2, i*2+2));
  return bytes;
}
static void pcallOpt(Object o, String method, Object... args) {
  try { /* pcall 1*/  callOpt(o, method, args); /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); }
}
static String quickSubstring(String s, int i, int j) {
  if (i == j) return "";
  return s.substring(i, j);
}
static String className(Object o) {
  return getClassName(o);
}
static Object mainBot;

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

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 byte min(byte[] c) {
  byte x = 127;
  for (byte d : c) if (d < x) x = d;
  return x;
}
static void assertTrue(Object o) {
  assertEquals(true, o);
}
  
static boolean assertTrue(String msg, boolean b) {
  if (!b)
    throw fail(msg);
  return b;
}

static boolean assertTrue(boolean b) {
  if (!b)
    throw fail("oops");
  return b;
}
static Object newObject(Class c, Object... args) {
  return nuObject(c, args);
}

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

static boolean isLongConstant(String s) {
  if (!s.endsWith("L")) return false;
  s = s.substring(0, l(s)-1);
  return isInteger(s);
}
static String internIfLongerThan(String s, int l) {
  return s == null ? null : l(s) >= l ? s.intern() : s;
}
static Class getMainClass() { try {
 
  return Class.forName("main");

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}

static Class getMainClass(Object o) { try {
 
  return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static <A> List<A> subList(List<A> l, int startIndex) {
  return subList(l, startIndex, l(l));
}

static <A> List<A> subList(List<A> l, int startIndex, int endIndex) {
  startIndex = max(0, min(l(l), startIndex));
  endIndex = max(0, min(l(l), endIndex));
  if (startIndex > endIndex) return litlist();
  return l.subList(startIndex, endIndex);
}
static int days() {
  return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
}
static String getStackTrace(Throwable throwable) {
  StringWriter writer = new StringWriter();
  throwable.printStackTrace(new PrintWriter(writer));
  return writer.toString();
}
static String formatSnippetID(String id) {
  return "#" + parseSnippetID(id);
}

static String formatSnippetID(long id) {
  return "#" + id;
}
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 boolean booleanValue(Object o) {
  return eq(true, o);
}
static String getClassName(Object o) {
  return o == null ? "null" : o.getClass().getName();
}
static File javaxDataDir_dir; // can be set to work on different base dir

static File javaxDataDir() {
  return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
}
static double parseDouble(String s) {
  return Double.parseDouble(s);
}
static List emptyList() {
  return new ArrayList();
  //ret Collections.emptyList();
}
  public static String unquote(String s) {
    if (s == null) return null;
    if (s.startsWith("[")) {
      int i = 1;
      while (i < s.length() && s.charAt(i) == '=') ++i;
      if (i < s.length() && s.charAt(i) == '[') {
        String m = s.substring(1, i);
        if (s.endsWith("]" + m + "]"))
          return s.substring(i+1, s.length()-i-1);
      }
    }
    
    if (s.startsWith("\"") /*&& s.endsWith("\"")*/ && s.length() > 1) {
      String st = s.substring(1, s.endsWith("\"") ? s.length()-1 : s.length());
      StringBuilder sb = new StringBuilder(st.length());
  
      for (int i = 0; i < st.length(); i++) {
        char ch = st.charAt(i);
        if (ch == '\\') {
          char nextChar = (i == st.length() - 1) ? '\\' : st
                  .charAt(i + 1);
          // Octal escape?
          if (nextChar >= '0' && nextChar <= '7') {
              String code = "" + nextChar;
              i++;
              if ((i < st.length() - 1) && st.charAt(i + 1) >= '0'
                      && st.charAt(i + 1) <= '7') {
                  code += st.charAt(i + 1);
                  i++;
                  if ((i < st.length() - 1) && st.charAt(i + 1) >= '0'
                          && st.charAt(i + 1) <= '7') {
                      code += st.charAt(i + 1);
                      i++;
                  }
              }
              sb.append((char) Integer.parseInt(code, 8));
              continue;
          }
          switch (nextChar) {
          case '\\':
              ch = '\\';
              break;
          case 'b':
              ch = '\b';
              break;
          case 'f':
              ch = '\f';
              break;
          case 'n':
              ch = '\n';
              break;
          case 'r':
              ch = '\r';
              break;
          case 't':
              ch = '\t';
              break;
          case '\"':
              ch = '\"';
              break;
          case '\'':
              ch = '\'';
              break;
          // Hex Unicode: u????
          case 'u':
              if (i >= st.length() - 5) {
                  ch = 'u';
                  break;
              }
              int code = Integer.parseInt(
                      "" + st.charAt(i + 2) + st.charAt(i + 3)
                              + st.charAt(i + 4) + st.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();      
    } else
      return s; // return original
  }
static void setOptAll(Object o, Map<String, Object> fields) {
  if (fields == null) return;
  for (String field : keys(fields))
    setOpt(o, field, fields.get(field));
}
static char unquoteCharacter(String s) {
  assertTrue(s.startsWith("'") && s.length() > 1);
  return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length()-1 : s.length()) + "\"").charAt(0);
}
static <A> A nuStubInnerObject(Class<A> c) { try {
 
  Class outerType = getOuterClass(c);
  Constructor m = c.getDeclaredConstructor(outerType);
  m.setAccessible(true);
  return (A) m.newInstance(new Object[] {null});

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}


static Class getOuterClass(Class c) { try {
 
  String s = c.getName();
  int i = s.lastIndexOf('$');
  return Class.forName(substring(s, 0, i));

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String _userHome;
static String userHome() {
  if (_userHome == null) {
    if (isAndroid())
      _userHome = "/storage/sdcard0/";
    else
      _userHome = System.getProperty("user.home");
    //System.out.println("userHome: " + _userHome);
  }
  return _userHome;
}

static File userHome(String path) {
  return new File(userDir(), path);
}
static <A> ArrayList<A> litlist(A... a) {
  return new ArrayList<A>(Arrays.asList(a));
}
static int max(int a, int b) {
  return Math.max(a, b);
}

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 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 byte max(byte[] c) {
  byte x = -128;
  for (byte d : c) if (d > x) x = d;
  return x;
}
static <A> A assertEquals(Object x, A y) {
  return assertEquals(null, x, y);
}

static <A> A assertEquals(String msg, Object x, A y) {
  if (!(x == null ? y == null : x.equals(y)))
    throw fail((msg != null ? msg + ": " : "") + structure(x) + " != " + structure(y));
  return y;
}
public static long parseSnippetID(String snippetID) {
  long id = Long.parseLong(shortenSnippetID(snippetID));
  if (id == 0) throw fail("0 is not a snippet ID");
  return id;
}
  static String repeat(char c, int n) {
    n = max(n, 0);
    char[] chars = new char[n];
    for (int i = 0; i < n; i++)
      chars[i] = c;
    return new String(chars);
  }

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

static int parseHexByte(String s) {
  return Integer.parseInt(s, 16);
}
static void setOpt(Object o, String field, Object value) {
  if (o instanceof Class) setOpt((Class) o, field, value);
  else try {
    Field f = setOpt_findField(o.getClass(), field);
    if (f != null)
      smartSet(f, o, value);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

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

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


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

static File userDir(String path) {
  return new File(userHome(), path);
}
static boolean isAndroid() { return System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0; }


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