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 x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.l;
import static x30_pkg.x30_util.fail;
import static x30_pkg.x30_util.indexOf;
import static x30_pkg.x30_util.getOpt;
import static x30_pkg.x30_util.setOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.get_raw;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils._threadInfo_addMakerAndRetriever;
import static loadableUtils.utils.dm_currentModule;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.getOpt_raw;
import static loadableUtils.utils.setOpt_raw;
import static loadableUtils.utils.getField;
import static loadableUtils.utils.fieldType;
import static loadableUtils.utils.format3;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.struct;
import static loadableUtils.utils.structure;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPage_utf8;
import static loadableUtils.utils.loadPageSilentlyWithTimeout;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.loadSnippetQuietly;
import static loadableUtils.utils.sendToLocalBot;
import static loadableUtils.utils.sendToLocalBotOpt;
import static loadableUtils.utils.sendToLocalBotQuietly;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.componentPopupMenu_top;
import static loadableUtils.utils.componentPopupMenu_initForComponent;
import static loadableUtils.utils.componentPopupMenu_getEvent;
import static loadableUtils.utils.listPopupMenu;
import static loadableUtils.utils.tablePopupMenu;
import static loadableUtils.utils.tablePopupMenuFirst;
import static loadableUtils.utils.rowSorter_setComparators;
import static loadableUtils.utils.sexyTableWithoutDrag;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.dm_current_mandatory_generic;
import static loadableUtils.utils.cset;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.concepts_unlisted;
import static loadableUtils.utils.makePopupMenuConditional;
import static loadableUtils.utils.makeConceptsTable_idWidth;
import static loadableUtils.utils.showConceptsTable_afterUpdate;
import static loadableUtils.utils.dynamicObjectIsLoading;
import static loadableUtils.utils.rethrow;
import static loadableUtils.utils.hasBot;
import static loadableUtils.utils.concepts_internStringsLongerThan;
import static loadableUtils.utils.concepts_setUnlistedByDefault;
import static loadableUtils.utils.realMC_tl;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF0;
import loadableUtils.utils.IF1;
import loadableUtils.utils.IVF1;
import loadableUtils.utils.IVF2;
import loadableUtils.utils.Matches;
import loadableUtils.utils.BetterLabel;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.Snippet;
import loadableUtils.utils.Q;
import loadableUtils.utils.ImageSurface;
import loadableUtils.utils.structure_Data;
import loadableUtils.utils.structure_ClassInfo;
import loadableUtils.utils.RGBImage;
import loadableUtils.utils.RGB;
import loadableUtils.utils.BWImage;
import loadableUtils.utils.MakesBufferedImage;
import loadableUtils.utils.MultiSet;
import loadableUtils.utils.Concept;
import loadableUtils.utils.Concepts;
import loadableUtils.utils.RC;
import loadableUtils.utils.IConceptIndex;
import loadableUtils.utils.IFieldIndex;
import loadableUtils.utils.Derefable;
import loadableUtils.utils.ImageSurfaceSelector;
import loadableUtils.utils.SimpleCRUD;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.DynPrintLog;
import loadableUtils.utils.DynObjectTable;
import loadableUtils.utils.DynImageSurface;
import loadableUtils.utils.DynCalculatedList;
import loadableUtils.utils.GlobalID;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import loadableUtils.utils.SynchronizedArrayList;
import loadableUtils.utils.SecretValue;
import loadableUtils.utils.HCRUD;
import loadableUtils.utils.HCRUD_Data;
import loadableUtils.utils.HCRUD_Concepts;
import loadableUtils.utils.ValueConverterForField;
import loadableUtils.utils.DefaultValueConverterForField;
import loadableUtils.utils.OrError;
import loadableUtils.utils.HTML;
import javax.swing.border.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.nio.charset.Charset;

class main {

  static public class BoxFinder extends DynImageSurface {

    public int nBoxes = 1;

    public boolean keepGoing = false;

    public Best<BackgroundPlus<BoxWithColor>> best = new Best();

    transient public RGBImage original;

    transient public Thread recognizerThread;

    transient public ImageSurface isBoxes;

    transient public BackgroundPlus<BoxWithColor> rendered;

    public String switchableFields() {
      return "nBoxes keepGoing";
    }

    public JComponent visualize() {
      JSpinner spinner = liveValueSpinner(dm_fieldLiveValue("nBoxes"), 1, 50);
      main.onChange(spinner, new Runnable() {

        public void run() {
          try {
            startRecognition();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "startRecognition();";
        }
      });
      return jvsplit(vgrid(super.visualize(), jscroll_centered(isBoxes = imageSurface())), northAndCenter(withSideMargin(rightAlignedLine(dm_fieldCheckBox("keepGoing"), jbutton("Start", new Runnable() {

        public void run() {
          try {
            startRecognition();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "startRecognition();";
        }
      }), jbutton("Stop", new Runnable() {

        public void run() {
          try {
            cancelThread(recognizerThread);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "cancelThread(recognizerThread)";
        }
      }), withLabel("Boxes:", spinner))), dm_printLogComponent()));
    }

    public void start() {
      try {
        super.start();
        if (!hasImage())
          setImage(whiteImage(50, 50));
        onNewImage = new Runnable() {

          public void run() {
            try {
              startRecognition();
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "startRecognition();";
          }
        };
        doEvery(1.0, new Runnable() {

          public void run() {
            try {
              renderBoxes();
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "renderBoxes();";
          }
        });
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public double scoreImage(RGBImage image) {
      return 100 * (1.0 - rgbDistance(image, original));
    }

    public void startRecognition() {
      AutoCloseable __10 = enter();
      try {
        cancelThread(recognizerThread);
        recognizerThread = startThread(new Runnable() {

          public void run() {
            try {
              BufferedImage image = getImage();
              final int w = image.getWidth(), h = image.getHeight();
              print("Starting recognition on " + w + "*" + h + " image");
              best = new Best();
              best.stringifier = "sfu";
              original = new RGBImage(image);
              AIStrategy_Racer_RandomWithVary<BackgroundPlus<BoxWithColor>> strategy = new AIStrategy_Racer_RandomWithVary();
              strategy.verbose = true;
              strategy.best = best;
              strategy.submit = new F1<BackgroundPlus<BoxWithColor>, Double>() {

                public Double get(BackgroundPlus<BoxWithColor> s) {
                  try {
                    return scoreImage(rgbRenderRenderable(w, h, s));
                  } catch (Exception __e) {
                    throw rethrow(__e);
                  }
                }

                public String toString() {
                  return "scoreImage(rgbRenderRenderable(w, h, s))";
                }
              };
              strategy.random = new F0<BackgroundPlus<BoxWithColor>>() {

                public BackgroundPlus<BoxWithColor> get() {
                  try {
                    return randomBackgroundPlusBoxes(w, h, nBoxes);
                  } catch (Exception __e) {
                    throw rethrow(__e);
                  }
                }

                public String toString() {
                  return "ret randomBackgroundPlusBoxes(w, h, nBoxes);";
                }
              };
              strategy.vary = new F1<BackgroundPlus<BoxWithColor>, BackgroundPlus<BoxWithColor>>() {

                public BackgroundPlus<BoxWithColor> get(BackgroundPlus<BoxWithColor> s) {
                  try {
                    return varyBackgroundPlusBoxes(s, w, h);
                  } catch (Exception __e) {
                    throw rethrow(__e);
                  }
                }

                public String toString() {
                  return "varyBackgroundPlusBoxes(s, w, h)";
                }
              };
              if (keepGoing)
                runStrategyForever(best, strategy);
              else
                runStrategyWhileImprovement(best, strategy);
              print("Done");
              persistMe();
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "BufferedImage image = getImage();\r\n      final int w = image.getWidth(), h = ...";
          }
        });
      } finally {
        _close(__10);
      }
    }

    public void renderBoxes() {
      AutoCloseable __11 = enter();
      try {
        if (original != null && best.get() != rendered) {
          rendered = best.get();
          isBoxes.setImage(renderRenderable(original.w(), original.h(), rendered));
        }
      } finally {
        _close(__11);
      }
    }
  }

  static public boolean _moduleClass_BoxFinder = true;

  static public String programID;

  static public void _onLoad_initUtils() {
    utils.__javax = javax();
  }

  static public void _onLoad_defaultClassFinder() {
    setDefaultClassFinder(new F1<String, Class>() {

      public Class get(String name) {
        Class c = findClass_fullName(name);
        if (c != null)
          return c;
        if (name.startsWith("main$"))
          return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + name.substring(4));
        return null;
      }
    });
  }

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

  static public String sfu(Object o) {
    return structureForUser(o);
  }

  static public JSpinner liveValueSpinner(final SimpleLiveValue<Integer> lv, int min, int max) {
    final JSpinner spinner = jSpinner(lv.get(), min, max);
    onChange(spinner, new Runnable() {

      public void run() {
        try {
          lv.set(intFromSpinner(spinner));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "lv.set(intFromSpinner(spinner))";
      }
    });
    lv.onChange(new Runnable() {

      public void run() {
        try {
          setSpinnerValue(spinner, lv.get());
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "setSpinnerValue(spinner, lv.get())";
      }
    });
    return spinner;
  }

  static public SimpleLiveValue dm_fieldLiveValue(String fieldName) {
    return dm_fieldLiveValue(dm_current_mandatory(), fieldName);
  }

  static public SimpleLiveValue dm_fieldLiveValue(final DynModule module, final String fieldName) {
    Lock __0 = module.lock;
    lock(__0);
    try {
      AutoCloseable __2 = module.enter();
      try {
        Class type = getFieldType(module, fieldName);
        final SimpleLiveValue value = new SimpleLiveValue(type, get(module, fieldName));
        dm_watchField(fieldName, new Runnable() {

          public void run() {
            try {
              Object o = get(module, fieldName);
              value.set(o);
              ;
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "ifdef dm_fieldLiveValue_debug\r\n      print(\"dm_fieldLiveValue: setting \" + fi...";
          }
        });
        value.onChange(new Runnable() {

          public void run() {
            try {
              module.setField(fieldName, value.get());
              ;
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "ifdef dm_fieldLiveValue_debug\r\n      print(\"dm_fieldLiveValue: setting 2 \" + ...";
          }
        });
        return value;
      } finally {
        _close(__2);
      }
    } finally {
      unlock(__0);
    }
  }

  static public <A extends JSpinner> A onChange(A spinner, Object r) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            spinner.addChangeListener(changeListener(r));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "spinner.addChangeListener(changeListener(r));";
        }
      });
    }
    return spinner;
  }

  static public <A extends AbstractButton> A onChange(A b, Object r) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            b.addItemListener(itemListener(r));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "b.addItemListener(itemListener(r));";
        }
      });
    }
    return b;
  }

  static public void onChange(JTextComponent tc, Object r) {
    onUpdate(tc, r);
  }

  static public <A extends JSlider> A onChange(A slider, final Object r) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            slider.addChangeListener(changeListener(r));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "slider.addChangeListener(changeListener(r));";
        }
      });
    }
    return slider;
  }

  static public JComboBox onChange(Object r, JComboBox cb) {
    return onChange(cb, r);
  }

  static public JComboBox onChange(JComboBox cb, final Object r) {
    if (isEditableComboBox(cb))
      onChange(textFieldFromComboBox(cb), r);
    else
      onSelectedItem(cb, new VF1<String>() {

        public void get(String s) {
          try {
            callF(r);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "callF(r)";
        }
      });
    return cb;
  }

  static public JSplitPane jvsplit(Component n, Component s) {
    return jvsplit(n, s, 0.5);
  }

  static public JSplitPane jvsplit(Component n, Component s, double splitPoint, int delay) {
    return jvsplit(n, s, splitPoint);
  }

  static public JSplitPane jvsplit(Component n, Component s, double splitPoint) {
    return setSplitPaneOnFirstShowing(swingNu(JSplitPane.class, JSplitPane.VERTICAL_SPLIT, wrap(n), wrap(s)), splitPoint);
  }

  static public JSplitPane jvsplit(double splitPoint, Component n, Component s) {
    return jvsplit(n, s, splitPoint);
  }

  static public JPanel vgrid(List parts) {
    return vgrid(asArray(parts));
  }

  static public JPanel vgrid(Object... parts) {
    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(parts.length, 1));
    smartAdd(panel, parts);
    return panel;
  }

  static public JScrollPane jscroll_centered(Component c) {
    return jscroll(jFullCenter(c));
  }

  static public ImageSurface imageSurface(BufferedImage img) {
    return swingNu(ImageSurface.class, img);
  }

  static public ImageSurface imageSurface(MakesBufferedImage img) {
    return swingNu(ImageSurface.class, img);
  }

  static public ImageSurface imageSurface() {
    return swingNu(ImageSurface.class);
  }

  static public JPanel northAndCenter(Component n, Component c) {
    return centerAndNorth(c, n);
  }

  static public JPanel withSideMargin(Component c) {
    return withLeftAndRightMargin(c);
  }

  static public JPanel withSideMargin(int w, Component c) {
    return withLeftAndRightMargin(w, c);
  }

  static public JPanel withSideMargin(int w1, int w2, Component c) {
    return withLeftAndRightMargin(w1, w2, c);
  }

  static public JPanel rightAlignedLine(Component... components) {
    return jrightAlignedLine(components);
  }

  static public JPanel rightAlignedLine(List<? extends Component> components) {
    return jrightAlignedLine(components);
  }

  static public JCheckBox dm_fieldCheckBox(String field) {
    return dm_fieldCheckBox(humanizeFormLabel(field), field);
  }

  static public JCheckBox dm_fieldCheckBox(String text, String field) {
    if (isIdentifier(text) && !isIdentifier(field)) {
      String temp = field;
      field = text;
      text = temp;
    }
    return jLiveValueCheckBox(text, dm_fieldLiveValue(field));
  }

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

  static public JButton jbutton(String text) {
    return newButton(text, null);
  }

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

  static public void cancelThread(Thread t) {
    if (t == null)
      return;
    ping();
    synchronized (ping_actions) {
      ping_actions.put(t, "cancelled");
      ping_anyActions = true;
    }
  }

  public static JComponent withLabel(String label, JComponent component) {
    return westAndCenter(jlabel(label + " "), component);
  }

  static public JComponent dm_printLogComponent() {
    DynModule mod = dm_current_mandatory();
    final JTextArea ta = moveCaretToEnd(typeWriterTextArea_noUndo(str(mod._actualPrintLog())));
    JComponent section = jSection("Log", awtEvery(ta, 500, new Runnable() {

      public void run() {
        try {
          setText(ta, str(mod._actualPrintLog()));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "setText(ta, str(mod._actualPrintLog()))";
      }
    }));
    componentPopupMenuItem(section, "Clear", new Runnable() {

      public void run() {
        try {
          clearPrintLog();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "clearPrintLog();";
      }
    });
    return section;
  }

  static public JLabel setImage(final BufferedImage img, final JLabel lbl) {
    if (lbl != null) {
      swing(new Runnable() {

        public void run() {
          try {
            lbl.setIcon(imageIcon(img));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "lbl.setIcon(imageIcon(img));";
        }
      });
    }
    return lbl;
  }

  static public JLabel setImage(JLabel lbl, BufferedImage img) {
    return setImage(img, lbl);
  }

  static public JLabel setImage(final String imageID, final JLabel lbl) {
    if (lbl != null) {
      swing(new Runnable() {

        public void run() {
          try {
            lbl.setIcon(imageIcon(imageID));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "lbl.setIcon(imageIcon(imageID));";
        }
      });
    }
    return lbl;
  }

  static public JLabel setImage(JLabel lbl, String imageID) {
    return setImage(imageID, lbl);
  }

  static public BufferedImage whiteImage(int w, int h) {
    return newBufferedImage(w, h, Color.white);
  }

  static public BufferedImage whiteImage(int size) {
    return whiteImage(size, size);
  }

  static public FixedRateTimer doEvery(long delay, final Object r) {
    return doEvery(delay, delay, r);
  }

  static public FixedRateTimer doEvery(long delay, long firstDelay, final Object r) {
    FixedRateTimer timer = new FixedRateTimer(shorten(programID() + ": " + r, 80));
    timer.scheduleAtFixedRate(smartTimerTask(r, timer, toInt(delay)), toInt(firstDelay), toInt(delay));
    return vmBus_timerStarted(timer);
  }

  static public FixedRateTimer doEvery(double initialSeconds, double delaySeconds, final Object r) {
    return doEvery(toMS(delaySeconds), toMS(initialSeconds), r);
  }

  static public FixedRateTimer doEvery(double delaySeconds, final Object r) {
    return doEvery(toMS(delaySeconds), r);
  }

  static public float rgbDistance(RGBImage a, RGBImage b, float maxDistance) {
    return 1f - rgbImageSimilarityResized(a, b, 1f - maxDistance);
  }

  static public float rgbDistance(RGBImage a, RGBImage b) {
    return rgbDistance(a, b, 1);
  }

  static public float rgbDistance(RGB a, RGB b) {
    return rgbDiff(a, b);
  }

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

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

  static public Thread startThread(Thread t) {
    _registerThread(t);
    t.start();
    return t;
  }

  static volatile public StringBuffer local_log = new StringBuffer();

  static volatile public Appendable print_log = local_log;

  static volatile public int print_log_max = 1024 * 1024;

  static volatile public int local_log_max = 100 * 1024;

  static public boolean print_silent = false;

  static public Object print_byThread_lock = new Object();

  static volatile public ThreadLocal<Object> print_byThread;

  static volatile public Object print_allThreads;

  static volatile public Object print_preprocess;

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

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

  static public <A> A print(A o) {
    ping_okInCleanUp();
    if (print_silent)
      return o;
    String s = o + "\n";
    print_noNewLine(s);
    return o;
  }

  static public void print_noNewLine(String s) {
    Object f = getThreadLocal(print_byThread_dontCreate());
    if (f == null)
      f = print_allThreads;
    if (f != null)
      if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s)))
        return;
    print_raw(s);
  }

  static public 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 public void print_autoRotate() {
  }

  static public RGBImage rgbRenderRenderable(int w, int h, Renderable r) {
    return new RGBImage(renderRenderable(w, h, r));
  }

  static public BackgroundPlus<BoxWithColor> randomBackgroundPlusBoxes(final int w, final int h, int n) {
    return new BackgroundPlus<BoxWithColor>(randomColor(), produceN(new F0<Object>() {

      public Object get() {
        try {
          return randomBoxWithColor(w, h);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret randomBoxWithColor(w, h);";
      }
    }, n));
  }

  static public <A extends BackgroundPlus<BoxWithColor>> A varyBackgroundPlusBoxes(A s, int w, int h) {
    s = cloneThroughStructure(s);
    if (oneIn(10))
      s.background = varyColor(s.background);
    else if (tossCoin())
      replaceRandomElement(s.things, randomBoxWithColor(w, h));
    else
      varyBoxWithColor(random(s.things), w, h);
    return s;
  }

  static public <A> void runStrategyForever(AIStrategy strategy, Object... __) {
    runStrategyForever(strategy.best, strategy, __);
  }

  static public <A> void runStrategyForever(Best<A> best, Steppable strategy, Object... __) {
    Double optimumValue = (Double) (optPar("optimumValue", __));
    double score = best.score();
    long sameScoreSince = 0;
    while (licensed()) {
      if (strategy.step())
        return;
      ++sameScoreSince;
      if (best.score() != score) {
        print("Improvement after " + n2(sameScoreSince, "round") + ": " + best);
        sameScoreSince = 0;
        score = best.score();
        if (optimumValue != null && eq(score, optimumValue))
          return;
      }
    }
  }

  static public <A> void runStrategyWhileImprovement(Best<A> best, Steppable strategy, Object... __) {
    double score = best.score();
    int plateauLength = optPar("plateauLength", __, 1000);
    long sameScoreSince = 0;
    Double minRuntimeUnless100 = (Double) (optPar("minRuntimeUnless100", __));
    long start = sysNow();
    while (licensed()) {
      if (strategy.step())
        return;
      ++sameScoreSince;
      if (best.score() != score) {
        print("Improvement after " + n2(sameScoreSince, "round") + ": " + callStringifier(optParam(__, "printer"), best));
        sameScoreSince = 0;
        score = best.score();
      } else if (sameScoreSince >= plateauLength && (minRuntimeUnless100 == null || elapsedSeconds(start) >= minRuntimeUnless100))
        return;
    }
  }

  static public <A> Best<A> runStrategyWhileImprovement(AIStrategy strategy, Object... __) {
    runStrategyWhileImprovement(strategy.best, strategy, __);
    return strategy.best;
  }

  static public void _close(AutoCloseable c) {
    if (c != null)
      try {
        c.close();
      } catch (Throwable e) {
        if (c instanceof javax.imageio.stream.ImageOutputStream)
          return;
        else
          throw rethrow(e);
      }
  }

  static public BufferedImage renderRenderable(int w, int h, Renderable r) {
    BufferedImage img = newBufferedImage(w, h);
    r.renderOn(imageGraphics(img), w, h);
    return img;
  }

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

  static public void setDefaultClassFinder(Object cf) {
    _defaultClassFinder_value = cf;
  }

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

  static public Class findClass_fullName(String name) {
    synchronized (findClass_fullName_cache) {
      if (findClass_fullName_cache.containsKey(name))
        return findClass_fullName_cache.get(name);
      Class c;
      try {
        c = Class.forName(name);
      } catch (ClassNotFoundException e) {
        c = null;
      }
      findClass_fullName_cache.put(name, c);
      return c;
    }
  }

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

  static public Object _defaultClassFinder_value = defaultDefaultClassFinder();

  static public Object _defaultClassFinder() {
    return _defaultClassFinder_value;
  }

  static public String structureForUser(Object o) {
    return beautifyStructure(struct_noStringSharing(o));
  }

  static public JSpinner jSpinner(final int value) {
    return swing(new F0<JSpinner>() {

      public JSpinner get() {
        try {
          JSpinner s = new JSpinner();
          s.setValue(value);
          return s;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "new JSpinner s;\r\n    s.setValue(value);\r\n    ret s;";
      }
    });
  }

  static public JSpinner jSpinner(final int value, final int min, final int max) {
    return swing(new F0<JSpinner>() {

      public JSpinner get() {
        try {
          return new JSpinner(new SpinnerNumberModel(value, min, max, 1));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret new JSpinner(new SpinnerNumberModel(value, min, max, 1));";
      }
    });
  }

  static public int intFromSpinner(JSpinner s) {
    return toInt(s.getValue());
  }

  static public void setSpinnerValue(final JSpinner s, final int value) {
    if (s != null) {
      swing(new Runnable() {

        public void run() {
          try {
            s.setValue(value);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "s.setValue(value);";
        }
      });
    }
  }

  static public void lock(Lock lock) {
    try {
      ping();
      if (lock == null)
        return;
      try {
        lock.lockInterruptibly();
      } catch (InterruptedException e) {
        Object reason = vm_threadInterruptionReasonsMap().get(currentThread());
        print("Locking interrupted! Reason: " + strOr(reason, "Unknown"));
        printStackTrace(e);
        rethrow(e);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

  static public Class getFieldType(Object o, String field) {
    return fieldType(o, field);
  }

  static public void dm_watchField(String field, Runnable onChange) {
    new Dyn_FieldWatcher(dm_current_mandatory(), field, onChange);
  }

  static public void unlock(Lock lock, String msg) {
    if (lock == null)
      return;
    lock.unlock();
    print("Unlocked: " + msg);
  }

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

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

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

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

  static public ChangeListener changeListener(final Object r) {
    return new ChangeListener() {

      public void stateChanged(ChangeEvent e) {
        pcallF(r);
      }
    };
  }

  static public ItemListener itemListener(final Object r) {
    return new ItemListener() {

      public void itemStateChanged(ItemEvent e) {
        pcallF(r);
      }
    };
  }

  static public void onUpdate(JComponent c, final Object r) {
    if (c instanceof JTextComponent)
      ((JTextComponent) c).getDocument().addDocumentListener(new DocumentListener() {

        public void insertUpdate(DocumentEvent e) {
          call(r);
        }

        public void removeUpdate(DocumentEvent e) {
          call(r);
        }

        public void changedUpdate(DocumentEvent e) {
          call(r);
        }
      });
    else if (c instanceof ItemSelectable)
      ((ItemSelectable) c).addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {
          call(r);
        }
      });
    else
      print("Warning: onUpdate doesn't know " + getClassName(c));
  }

  static public void onUpdate(List<? extends JComponent> l, Object r) {
    for (JComponent c : l) onUpdate(c, r);
  }

  static public boolean isEditableComboBox(final JComboBox cb) {
    return cb != null && swing(new F0<Boolean>() {

      public Boolean get() {
        try {
          return cb.isEditable();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret cb.isEditable();";
      }
    });
  }

  static public JTextField textFieldFromComboBox(JComboBox cb) {
    return (JTextField) cb.getEditor().getEditorComponent();
  }

  static public JComboBox onSelectedItem(final JComboBox cb, final VF1<String> f) {
    addActionListener(cb, new Runnable() {

      public void run() {
        try {
          pcallF(f, selectedItem(cb));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "pcallF(f, selectedItem(cb))";
      }
    });
    return cb;
  }

  static public Object callF(Object f, Object... args) {
    try {
      if (f instanceof String)
        return callMC((String) f, args);
      return x30_util.callF(f, args);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

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

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

  static public Object callMC(String method, Object... args) {
    return call(mc(), method, args);
  }

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

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

  static public JSplitPane setSplitPaneOnFirstShowing(final Component c, final double value) {
    final JSplitPane sp = first(childrenOfType(c, JSplitPane.class));
    if (sp != null)
      onFirstResize(sp, new Runnable() {

        public void run() {
          try {
            sp.setDividerLocation(value);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "sp.setDividerLocation(value);";
        }
      });
    return sp;
  }

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

  static public JComponent wrap(Object swingable) {
    return _recordNewSwingComponent(wrap_2(swingable));
  }

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

  static public Object[] asArray(List l) {
    return toObjectArray(l);
  }

  static public <A> A[] asArray(Class<A> type, List l) {
    return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size()));
  }

  static public JPanel smartAdd(JPanel panel, List parts) {
    for (Object o : parts) addToContainer(panel, wrapForSmartAdd(o));
    return panel;
  }

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

  static public JScrollPane jscroll(final Component c) {
    return swing(new F0<JScrollPane>() {

      public JScrollPane get() {
        try {
          return new JScrollPane(c);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret new JScrollPane(c);";
      }
    });
  }

  static public JPanel jFullCenter(final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel panel = new JPanel(new GridBagLayout());
          panel.add(c);
          return panel;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel panel = new JPanel(new GridBagLayout);\r\n    panel.add(c);\r\n    ret panel;";
      }
    });
  }

  static public JPanel centerAndNorth(final Component c, final Component n) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel panel = new JPanel(new BorderLayout());
          panel.add(BorderLayout.CENTER, wrap(c));
          panel.add(BorderLayout.NORTH, wrap(n));
          return panel;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel panel = new JPanel(new BorderLayout);\r\n    panel.add(BorderLayout.CENT...";
      }
    });
  }

  static public int withLeftAndRightMargin_defaultWidth = 6;

  static public JPanel withLeftAndRightMargin(Component c) {
    return withLeftAndRightMargin(withLeftAndRightMargin_defaultWidth, c);
  }

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

  static public JPanel withLeftAndRightMargin(final int w1, final int w2, final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel p = new JPanel(new BorderLayout());
          p.setBorder(BorderFactory.createEmptyBorder(0, w1, 0, w2));
          p.add(c);
          return p;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel p = new JPanel(new BorderLayout);\r\n    p.setBorder(BorderFactory.creat...";
      }
    });
  }

  static public JPanel jrightAlignedLine(final Component... components) {
    return swing(new F0<RightAlignedLine>() {

      public RightAlignedLine get() {
        try {
          return new RightAlignedLine(components);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret RightAlignedLine(components);";
      }
    });
  }

  static public JPanel jrightAlignedLine(List<? extends Component> components) {
    return jrightAlignedLine(asArray(Component.class, components));
  }

  static public Map<String, String> humanizeFormLabel_replacements = litmap("id", "ID", "md5", "MD5");

  static public String humanizeFormLabel(String s) {
    if (containsSpace(s))
      return s;
    return firstToUpper(joinWithSpace(replaceElementsUsingMap(splitCamelCase(s), humanizeFormLabel_replacements)).replace("I D", "ID"));
  }

  static public boolean isIdentifier(String s) {
    return isJavaIdentifier(s);
  }

  static public JCheckBox jLiveValueCheckBox(String text, final SimpleLiveValue<Boolean> lv) {
    final JCheckBox cb = jCheckBox(text);
    bindCheckBoxToLiveValue(cb, lv);
    return cb;
  }

  static public boolean newButton_autoToolTip = true;

  static public JButton newButton(final String text, final Object action) {
    return swing(new F0<JButton>() {

      public JButton get() {
        try {
          String text2 = dropPrefix("[disabled] ", text);
          final JButton btn = new JButton(text2);
          if (l(text2) < l(text))
            btn.setEnabled(false);
          if (newButton_autoToolTip) {
            btn.setToolTipText(btn.getText());
          }
          if (action != null)
            btn.addActionListener(actionListener(action, btn));
          return btn;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "S text2 = dropPrefix(\"[disabled] \", text);\r\n    final JButton btn = new JButt...";
      }
    });
  }

  static volatile public boolean ping_pauseAll = false;

  static public int ping_sleep = 100;

  static volatile public boolean ping_anyActions = false;

  static public Map<Thread, Object> ping_actions = newWeakHashMap();

  static public ThreadLocal<Boolean> ping_isCleanUpThread = new ThreadLocal();

  static public boolean ping() {
    if (ping_pauseAll || ping_anyActions)
      ping_impl(true);
    return true;
  }

  static public boolean ping_impl(boolean okInCleanUp) {
    try {
      if (ping_pauseAll && !isAWTThread()) {
        do Thread.sleep(ping_sleep); while (ping_pauseAll);
        return true;
      }
      if (ping_anyActions) {
        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 public JPanel westAndCenter(final Component w, final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel panel = new JPanel(new BorderLayout());
          panel.add(BorderLayout.WEST, wrap(w));
          panel.add(BorderLayout.CENTER, wrap(c));
          return panel;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel panel = new JPanel(new BorderLayout);\r\n    panel.add(BorderLayout.WEST...";
      }
    });
  }

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

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

  static public <A extends JTextComponent> A moveCaretToEnd(A ta) {
    setCaretPosition(ta, textAreaTextLength(ta));
    return ta;
  }

  static public JTextArea typeWriterTextArea_noUndo() {
    return typeWriterTextArea_noUndo("");
  }

  static public JTextArea typeWriterTextArea_noUndo(String text) {
    return setFont(jTextArea_noUndo(text), typeWriterFont());
  }

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

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

  static public JPanel jSection(Component c) {
    return jSection("", c);
  }

  static public JPanel jSection(final String title, final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);
          border = BorderFactory.createTitledBorder(border, title);
          JSection panel = new JSection(c);
          panel.setBorder(border);
          return panel;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);\r\n    bo...";
      }
    });
  }

  static public JPanel jSection(String title) {
    return jSection(title, jpanel());
  }

  static public <A extends JComponent> A awtEvery(A component, long delay, Object r) {
    swingEvery(component, delay, r);
    return component;
  }

  static public <A extends JComponent> A awtEvery(A component, long delay, long firstDelay, Object r) {
    swingEvery(component, delay, firstDelay, r);
    return component;
  }

  static public void awtEvery(RootPaneContainer frame, long delay, Object r) {
    swingEvery(frame, delay, r);
  }

  static public <A extends JComponent> A awtEvery(A component, double delaySeconds, Object r) {
    return awtEvery(component, toMS(delaySeconds), r);
  }

  static public boolean setText_opt = true;

  static public <A extends JTextComponent> A setText(A c, Object text) {
    setText((JComponent) c, text);
    return c;
  }

  static public <A extends JComboBox> A setText(final A c, Object text) {
    final String s = strUnnull(text);
    {
      swing(new Runnable() {

        public void run() {
          try {
            c.getEditor().setItem(s);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c.getEditor().setItem(s);";
        }
      });
    }
    return c;
  }

  static public void setText(JLabel c, Object text) {
    setText((JComponent) c, text);
  }

  static public JButton setText(JButton c, Object text) {
    setText((JComponent) c, jlabel_textAsHTML_center_ifNeeded(strUnnull(text)));
    return c;
  }

  static public <A extends JComponent> A setText(final A c, Object text) {
    if (c == null)
      return null;
    final String s = strUnnull(text);
    {
      swing(new Runnable() {

        public void run() {
          try {
            if (!setText_opt || neq(callOpt(c, "getText"), s))
              call(c, "setText", s);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (!setText_opt || neq(callOpt(c, \"getText\"), s))\r\n      call(c, \"setText\", s);";
        }
      });
    }
    return c;
  }

  static public <A extends JComponent> A componentPopupMenuItem(A c, final String name, final Object action) {
    componentPopupMenu(c, new VF1<JPopupMenu>() {

      public void get(JPopupMenu menu) {
        try {
          addMenuItem(menu, name, action);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "addMenuItem(menu, name, action);";
      }
    });
    return c;
  }

  static public void componentPopupMenuItem(JComponent c, final JMenuItem menuItem) {
    componentPopupMenu(c, new VF1<JPopupMenu>() {

      public void get(JPopupMenu menu) {
        try {
          addMenuItem(menu, menuItem);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "addMenuItem(menu, menuItem);";
      }
    });
  }

  static public void clearPrintLog() {
    clearStringBuffer_gen(local_log);
  }

  static public int imageIcon_cacheSize = 10;

  static public boolean imageIcon_verbose = false;

  static public Map<String, ImageIcon> imageIcon_cache;

  static public Lock imageIcon_lock = lock();

  static public ThreadLocal<Boolean> imageIcon_fixGIF = new ThreadLocal();

  static public ImageIcon imageIcon(String imageID) {
    try {
      if (imageID == null)
        return null;
      Lock __0 = imageIcon_lock;
      lock(__0);
      try {
        if (imageIcon_cache == null)
          imageIcon_cache = new MRUCache(imageIcon_cacheSize);
        imageID = fsI(imageID);
        ImageIcon ii = imageIcon_cache.get(imageID);
        if (ii == null) {
          if (imageIcon_verbose)
            print("Loading image icon: " + imageID);
          File f = loadBinarySnippet(imageID);
          Boolean b = imageIcon_fixGIF.get();
          if (!isFalse(b))
            ii = new ImageIcon(loadBufferedImageFixingGIFs(f));
          else
            ii = new ImageIcon(f.toURI().toURL());
        } else
          imageIcon_cache.remove(imageID);
        imageIcon_cache.put(imageID, ii);
        return ii;
      } finally {
        unlock(__0);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public ImageIcon imageIcon(File f) {
    try {
      return new ImageIcon(f.toURI().toURL());
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

  static public BufferedImage newBufferedImage(int w, int h) {
    return new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  }

  static public BufferedImage newBufferedImage(int w, int h, RGB rgb) {
    return newBufferedImage(w, h, toColor(rgb));
  }

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

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

  static public int shorten_default = 100;

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

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

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

  static public String shorten(int max, CharSequence s) {
    return shorten(s, max);
  }

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

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

  static public TimerTask smartTimerTask(Object r, java.util.Timer timer, long delay) {
    return new SmartTimerTask(r, timer, delay, _threadInfo());
  }

  static public class SmartTimerTask extends TimerTask implements IFieldsToList {

    public Object r;

    public java.util.Timer timer;

    public long delay;

    public Object threadInfo;

    public SmartTimerTask() {
    }

    public SmartTimerTask(Object r, java.util.Timer timer, long delay, Object threadInfo) {
      this.threadInfo = threadInfo;
      this.delay = delay;
      this.timer = timer;
      this.r = r;
    }

    public String toString() {
      return shortClassName(this) + "(" + r + ", " + timer + ", " + delay + ", " + threadInfo + ")";
    }

    public Object[] _fieldsToList() {
      return new Object[] { r, timer, delay, threadInfo };
    }

    public long lastRun;

    public void run() {
      if (!licensed())
        timer.cancel();
      else {
        _threadInheritInfo(threadInfo);
        AutoCloseable __1 = tempActivity(r);
        try {
          lastRun = fixTimestamp(lastRun);
          long now = now();
          if (now >= lastRun + delay * 0.9) {
            lastRun = now;
            if (eq(false, pcallF(r)))
              timer.cancel();
          }
        } finally {
          _close(__1);
        }
      }
    }
  }

  static public 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 public int toInt(long l) {
    if (l != (int) l)
      throw fail("Too large for int: " + l);
    return (int) l;
  }

  static public <A> A vmBus_timerStarted(A timer) {
    vmBus_send("timerStarted", timer, costCenter());
    return timer;
  }

  static public long toMS(double seconds) {
    return (long) (seconds * 1000);
  }

  static public float rgbImageSimilarityResized(RGBImage a, RGBImage b, float similarity) {
    int aw = a.w(), ah = a.h();
    int bw = b.w(), bh = b.h();
    if (aw == bw && ah == bh)
      return rgbImageSimilarity_sameSize(a, b, similarity);
    int wp = max(aw, bw), hp = max(ah, bh);
    float ratio1 = ((float) aw) / ah, ratio2 = ((float) bw) / bh;
    float mismatch = ratio1 / ratio2;
    if (mismatch < 1f)
      mismatch = 1f / mismatch;
    float factor = wp * hp / mismatch;
    float maxError = (1f - similarity) * factor;
    float diff = 0;
    for (int y = 0; y < hp; y++) for (int x = 0; x < wp; x++) {
      diff += rgbDiff(a.getInt(x * aw / wp, y * ah / hp), b.getInt(x * bw / wp, y * bh / hp));
      if (diff > maxError)
        return similarity - 0.001f;
    }
    return 1f - diff / factor;
  }

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

  static public 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 public String defaultThreadName_name;

  static public String defaultThreadName() {
    if (defaultThreadName_name == null)
      defaultThreadName_name = "A thread by " + programID();
    return defaultThreadName_name;
  }

  static public Runnable wrapAsActivity(Object r) {
    return toRunnable(r);
  }

  static public Thread newThread(Object runnable) {
    return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
  }

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

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

  static public 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 public Map<Thread, Boolean> _registerThread_threads;

  static public Object _onRegisterThread;

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

  static public void _registerThread() {
    _registerThread(Thread.currentThread());
  }

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

  static public void ping_okInCleanUp() {
    if (ping_pauseAll || ping_anyActions)
      ping_impl(true);
  }

  static public Object getThreadLocal(Object o, String name) {
    ThreadLocal t = (ThreadLocal) (getOpt(o, name));
    return t != null ? t.get() : null;
  }

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

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

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

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

  static public 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 public 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 public void vmBus_send(String msg, Object... args) {
    Object arg = vmBus_wrapArgs(args);
    pcallFAll(vm_busListeners_live(), msg, arg);
    pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg);
  }

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

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

  static public RGB randomColor() {
    return new RGB(random(), random(), random());
  }

  static public List produceN(Object f, int n) {
    List l = new ArrayList();
    for (int i = 0; i < n; i++) l.add(callF(f));
    return l;
  }

  static public BoxWithColor randomBoxWithColor(int w, int h) {
    return new BoxWithColor(randomPoint(w, h), randomPoint(w, h), randomColor());
  }

  static public <A> A cloneThroughStructure(A a) {
    return restructure(a);
  }

  static public boolean oneIn(int n) {
    return random(n) == 0;
  }

  static public boolean oneIn(int n, Random random) {
    return random(random, n) == 0;
  }

  static public RGB varyColor(RGB rgb) {
    int s = random(3);
    if (s == 0)
      return new RGB(vary0to1(rgb.r), rgb.g, rgb.b);
    else if (s == 1)
      return new RGB(rgb.r, vary0to1(rgb.g), rgb.b);
    else
      return new RGB(rgb.r, rgb.g, vary0to1(rgb.b));
  }

  static public boolean tossCoin() {
    return oneIn(2);
  }

  static public boolean tossCoin(Random random) {
    return oneIn(2, random);
  }

  static public <A> void replaceRandomElement(List<A> l, A newElement) {
    if (empty(l))
      return;
    l.set(random(l(l)), newElement);
  }

  static public void varyBoxWithColor(BoxWithColor l, int w, int h) {
    int i = random(3);
    if (i == 0)
      l.a = varyPoint(l.a, w, h);
    else if (i == 1)
      l.b = varyPoint(l.b, w, h);
    else
      l.color = varyColor(l.color);
  }

  static public Random random_random = new Random();

  static public int random(int n) {
    return random(random_random, n);
  }

  static public int random(int n, Random r) {
    return random(r, n);
  }

  static public int random(Random r, int n) {
    return n <= 0 ? 0 : r.nextInt(n);
  }

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

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

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

  static public int random(int min, int max) {
    return min + random(max - min);
  }

  static public int random(int min, int max, Random r) {
    return random(r, min, max);
  }

  static public int random(Random r, int min, int max) {
    return min + random(r, max - min);
  }

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

  static public <A> A random(Collection<A> c) {
    if (c instanceof List)
      return random((List<A>) c);
    int i = random(l(c));
    return collectionGet(c, i);
  }

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

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

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

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

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

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

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

  static volatile public boolean licensed_yes = true;

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

  static public void licensed_off() {
    licensed_yes = false;
  }

  static public String n2(long l) {
    return formatWithThousands(l);
  }

  static public String n2(Collection l) {
    return n2(l(l));
  }

  static public String n2(Map map) {
    return n2(l(map));
  }

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

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

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

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

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

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

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

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

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

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

  static public String n2(MultiSet ms, String singular, String plural) {
    return n_fancy2(ms, singular, plural);
  }

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

  static public long sysNow() {
    ping();
    return System.nanoTime() / 1000000;
  }

  static public String callStringifier(Object stringifier, Object o) {
    return stringifier != null ? str(callF(stringifier, o)) : str(o);
  }

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

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

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

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

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

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

  static public double elapsedSeconds(long time) {
    return toSeconds(sysNow() - time);
  }

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

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

  static public Class __javax;

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

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

  static public AutoCloseable tempInterceptPrint(F1<String, Boolean> f) {
    return tempSetThreadLocal(print_byThread(), f);
  }

  static public Object defaultDefaultClassFinder() {
    return new F1<String, Class>() {

      public Class get(String name) {
        Class c = findClass_fullName(name);
        if (c != null)
          return c;
        if (name.startsWith("loadableUtils.utils$"))
          return findClass_fullName("main" + name.substring(19));
        return null;
      }
    };
  }

  static public String beautifyStructure(String s) {
    List<String> tok = javaTokForStructure(s);
    structure_addTokenMarkers(tok);
    jreplace(tok, "lhm", "");
    return join(tok);
  }

  static public String struct_noStringSharing(Object o) {
    structure_Data d = new structure_Data();
    d.noStringSharing = true;
    return structure(o, d);
  }

  static public Map<Thread, Object> vm_threadInterruptionReasonsMap() {
    return vm_generalWeakSubMap("Thread interruption reasons");
  }

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

  static public String strOr(Object o, String ifNull) {
    return o == null ? ifNull : str(o);
  }

  static public <A extends Throwable> A printStackTrace(A e) {
    print(getStackTrace(e));
    return e;
  }

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

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

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

  static public void lockOrFail(Lock lock, long timeout) {
    try {
      ping();
      if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
        String s = "Couldn't acquire lock after " + timeout + " ms.";
        if (lock instanceof ReentrantLock) {
          ReentrantLock l = (ReentrantLock) lock;
          s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
        }
        throw fail(s);
      }
      ping();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public ReentrantLock fairLock() {
    return new ReentrantLock(true);
  }

  static public void swingAndWait(Runnable r) {
    try {
      if (isAWTThread())
        r.run();
      else
        EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public 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 public Object pcallF(Object f, Object... args) {
    return pcallFunction(f, args);
  }

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

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

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

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

  static public void addActionListener(JTextField tf, final Runnable action) {
    onEnter(tf, action);
  }

  static public void addActionListener(final JComboBox cb, final Runnable action) {
    if (cb != null) {
      swing(new Runnable() {

        public void run() {
          try {
            cb.addActionListener(actionListener(action));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "cb.addActionListener(actionListener(action));";
        }
      });
    }
  }

  static public void addActionListener(final AbstractButton b, final Runnable action) {
    if (b != null) {
      swing(new Runnable() {

        public void run() {
          try {
            b.addActionListener(actionListener(action));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "b.addActionListener(actionListener(action));";
        }
      });
    }
  }

  static public String selectedItem(JList l) {
    return getSelectedItem(l);
  }

  static public String selectedItem(JComboBox cb) {
    return getSelectedItem(cb);
  }

  static public 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);
        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);
        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 public Object first(Object list) {
    return first((Iterable) list);
  }

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

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

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

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

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

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

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

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

  static public <A> List<A> childrenOfType(Component c, Class<A> theClass) {
    List<A> l = new ArrayList();
    scanForComponents(c, theClass, l);
    return l;
  }

  static public <A> List<A> childrenOfType(Class<A> theClass, Component c) {
    return childrenOfType(c, theClass);
  }

  static public void onFirstResize(final Component c, final Object r) {
    if (c != null && r != null) {
      swing(new Runnable() {

        public void run() {
          try {
            c.addComponentListener(new ComponentAdapter() {

              public void componentResized(ComponentEvent e) {
                c.removeComponentListener(this);
                pcallF(r);
              }
            });
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c.addComponentListener(new ComponentAdapter {\r\n      public void componentRes...";
        }
      });
    }
  }

  static public <A> A swingConstruct(final Class<A> c, final Object... args) {
    return swing(new F0<A>() {

      public A get() {
        try {
          return nuObject(c, args);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret nuObject(c, args);";
      }
    });
  }

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

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

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

  static public void addToContainer(Container a, Component... b) {
    if (a == null)
      return;
    {
      swing(new Runnable() {

        public void run() {
          try {
            for (Component c : unnull(b)) if (c != null)
              a.add(c);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "for (Component c : unnull(b))\r\n      if (c != null) \r\n        a.add(c);";
        }
      });
    }
  }

  static public Component wrapForSmartAdd(Object o) {
    if (o == null)
      return jpanel();
    if (o instanceof String)
      return jlabel((String) o);
    return wrap(o);
  }

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

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

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

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

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

  static public boolean containsSpace(String s) {
    return containsSpaces(s);
  }

  static public String firstToUpper(String s) {
    if (empty(s))
      return s;
    return Character.toUpperCase(s.charAt(0)) + s.substring(1);
  }

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

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

  static public <A> List<A> replaceElementsUsingMap(Iterable<A> l, final Map<A, A> map) {
    return map(l, new F1<A, A>() {

      public A get(A a) {
        try {
          return getOrKeep(map, a);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "getOrKeep(map, a)";
      }
    });
  }

  static public List<String> splitCamelCase(String s) {
    return ai_splitCamelCase(s);
  }

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

  static public JCheckBox jCheckBox() {
    return swingNu(JCheckBox.class);
  }

  static public JCheckBox jCheckBox(boolean checked) {
    return swingNu(JCheckBox.class, "", checked);
  }

  static public JCheckBox jCheckBox(String text, boolean checked) {
    return swingNu(JCheckBox.class, text, checked);
  }

  static public JCheckBox jCheckBox(String text) {
    return swingNu(JCheckBox.class, text);
  }

  static public JCheckBox jCheckBox(String text, boolean checked, final Object onChange) {
    JCheckBox cb = jCheckBox(checked, onChange);
    cb.setText(text);
    return cb;
  }

  static public JCheckBox jCheckBox(boolean checked, final Object onChange) {
    final JCheckBox cb = jCheckBox(checked);
    cb.addChangeListener(new ChangeListener() {

      public void stateChanged(ChangeEvent e) {
        pcallF(onChange, cb.isSelected());
      }
    });
    return cb;
  }

  static public <A extends JCheckBox> A bindCheckBoxToLiveValue(final A cb, final SimpleLiveValue<Boolean> lv) {
    bindLiveValueListenerToComponent(cb, lv, new Runnable() {

      public void run() {
        try {
          setChecked(cb, isTrue(lv.get()));
          ;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ifdef bindCheckBoxToLiveValue_debug\r\n      print(\"bindCheckBoxToLiveValue: se...";
      }
    });
    onChange(cb, new Runnable() {

      public void run() {
        try {
          lv.set(isChecked(cb));
          ;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ifdef bindCheckBoxToLiveValue_debug\r\n      print(\"bindCheckBoxToLiveValue: se...";
      }
    });
    return cb;
  }

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

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

  static public ActionListener actionListener(final Object runnable, final Object instanceToHold) {
    if (runnable instanceof ActionListener)
      return (ActionListener) runnable;
    final Object info = _threadInfo();
    return new java.awt.event.ActionListener() {

      public void actionPerformed(java.awt.event.ActionEvent _evt) {
        try {
          _threadInheritInfo(info);
          AutoCloseable __1 = holdInstance(instanceToHold);
          try {
            callF(runnable);
          } finally {
            _close(__1);
          }
        } catch (Throwable __e) {
          messageBox(__e);
        }
      }
    };
  }

  static public boolean isAWTThread() {
    if (isAndroid())
      return false;
    if (isHeadless())
      return false;
    return isAWTThread_awt();
  }

  static public boolean isAWTThread_awt() {
    return SwingUtilities.isEventDispatchThread();
  }

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

  static public void setCaretPosition(final JTextComponent c, final int pos) {
    if (c != null) {
      swing(new Runnable() {

        public void run() {
          try {
            try {
              int _pos = max(0, min(l(c.getText()), pos));
              c.setCaretPosition(_pos);
            } catch (Throwable __e) {
              _handleException(__e);
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "pcall {\r\n      int _pos = max(0, min(l(c.getText()), pos));\r\n      c.setCaret...";
        }
      });
    }
  }

  static public int textAreaTextLength(JTextComponent ta) {
    return l(getText(ta));
  }

  static public <A extends JComponent> A setFont(final Font font, final A a) {
    if (a != null) {
      swing(new Runnable() {

        public void run() {
          try {
            a.setFont(font);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "a.setFont(font);";
        }
      });
    }
    return a;
  }

  static public <A extends JComponent> A setFont(A a, Font font) {
    return setFont(font, a);
  }

  static public <A extends JComponent> A setFont(final String fontID, float fontSize, final A a) {
    return setFont(loadFont_cached(fontID, fontSize), a);
  }

  static public JTextArea jTextArea_noUndo() {
    return jTextArea_noUndo("");
  }

  static public JTextArea jTextArea_noUndo(final String text) {
    return swingNu(JTextArea.class, text);
  }

  static public Font typeWriterFont() {
    return typeWriterFont(iround(14 * getSwingFontScale()));
  }

  static public Font typeWriterFont(int size) {
    return new Font("Courier", Font.PLAIN, size);
  }

  static public JPanel jpanel(LayoutManager layout) {
    return swingNu(JPanel.class, layout);
  }

  static public JPanel jpanel() {
    return swingNu(JPanel.class);
  }

  static public void swingEvery(JComponent component, long delay, Object r) {
    installTimer(component, delay, r);
  }

  static public void swingEvery(JComponent component, long delay, long firstDelay, Object r) {
    installTimer(component, r, delay, firstDelay);
  }

  static public void swingEvery(RootPaneContainer frame, long delay, Object r) {
    installTimer(frame, delay, r);
  }

  static public void swingEvery(RootPaneContainer frame, long delay, long firstDelay, Object r) {
    installTimer(frame, delay, firstDelay, r);
  }

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

  static public String jlabel_textAsHTML_center_ifNeeded(String text) {
    if (swic(text, "<html>") && ewic(text, "</html>"))
      return text;
    if (!containsNewLines(text))
      return text;
    return jlabel_textAsHTML_center(text);
  }

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

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

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

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

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

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

  static public void clearStringBuffer_gen(Object buf) {
    if (buf != null) {
      call(buf, "setLength", 0);
      call(buf, "trimToSize");
    }
  }

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

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

  static public File loadBinarySnippet(String snippetID) {
    IResourceLoader rl = vm_getResourceLoader();
    if (rl != null)
      return rl.loadLibrary(snippetID);
    return loadBinarySnippet_noResourceLoader(snippetID);
  }

  static public File loadBinarySnippet_noResourceLoader(String snippetID) {
    try {
      long id = parseSnippetID(snippetID);
      if (isImageServerSnippet(id))
        return loadImageAsFile(snippetID);
      File f = DiskSnippetCache_getLibrary(id);
      if (fileSize(f) == 0)
        f = loadDataSnippetToFile_noResourceLoader(snippetID);
      return f;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean loadBufferedImageFixingGIFs_debug = false;

  static public ThreadLocal<Var<byte[]>> loadBufferedImageFixingGIFs_output = new ThreadLocal();

  static public Image loadBufferedImageFixingGIFs(File file) {
    try {
      if (!file.exists())
        return null;
      if (!isGIF(file))
        return ImageIO.read(file);
      if (loadBufferedImageFixingGIFs_debug)
        print("loadBufferedImageFixingGIFs" + ": checking gif");
      ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next();
      reader.setInput(ImageIO.createImageInputStream(file));
      int numImages = reader.getNumImages(true);
      IIOMetadata imageMetaData = reader.getImageMetadata(0);
      String metaFormatName = imageMetaData.getNativeMetadataFormatName();
      boolean foundBug = false;
      for (int i = 0; i < numImages && !foundBug; i++) {
        IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName);
        int nNodes = root.getLength();
        for (int j = 0; j < nNodes; j++) {
          org.w3c.dom.Node node = root.item(j);
          if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
            String delay = ((IIOMetadataNode) node).getAttribute("delayTime");
            if (Integer.parseInt(delay) == 0) {
              foundBug = true;
            }
            break;
          }
        }
      }
      if (loadBufferedImageFixingGIFs_debug)
        print("loadBufferedImageFixingGIFs" + ": " + f2s(file) + " foundBug=" + foundBug);
      Image image;
      if (!foundBug) {
        image = Toolkit.getDefaultToolkit().createImage(f2s(file));
      } else {
        ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
        {
          ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream);
          try {
            ImageWriter writer = ImageIO.getImageWriter(reader);
            writer.setOutput(ios);
            writer.prepareWriteSequence(null);
            for (int i = 0; i < numImages; i++) {
              BufferedImage frameIn = reader.read(i);
              IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName);
              int nNodes = root.getLength();
              for (int j = 0; j < nNodes; j++) {
                org.w3c.dom.Node node = root.item(j);
                if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
                  String delay = ((IIOMetadataNode) node).getAttribute("delayTime");
                  if (Integer.parseInt(delay) == 0) {
                    ((IIOMetadataNode) node).setAttribute("delayTime", "10");
                  }
                  break;
                }
              }
              IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frameIn), null);
              metadata.setFromTree(metadata.getNativeMetadataFormatName(), root);
              IIOImage frameOut = new IIOImage(frameIn, null, metadata);
              writer.writeToSequence(frameOut, writer.getDefaultWriteParam());
            }
            writer.endWriteSequence();
          } finally {
            _close(ios);
          }
        }
        byte[] data = baoStream.toByteArray();
        setVar(loadBufferedImageFixingGIFs_output.get(), data);
        if (loadBufferedImageFixingGIFs_debug)
          print("Data size: " + l(data));
        image = Toolkit.getDefaultToolkit().createImage(data);
      }
      return image;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Color toColor(RGB rgb) {
    return rgb == null ? null : rgb.getColor();
  }

  static public Color toColor(int rgb) {
    return new Color(rgb);
  }

  static public Color toColor(String hex) {
    return awtColor(hex);
  }

  static public CharSequence subCharSequence(CharSequence s, int x) {
    return subCharSequence(s, x, s == null ? 0 : s.length());
  }

  static public CharSequence subCharSequence(CharSequence s, int x, int y) {
    if (s == null)
      return null;
    if (x < 0)
      x = 0;
    if (x >= s.length())
      return "";
    if (y < x)
      y = x;
    if (y > s.length())
      y = s.length();
    return s.subSequence(x, y);
  }

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

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

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

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

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

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

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

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

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

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

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

  static public String getProgramID(Class c) {
    String id = (String) getOpt(c, "programID");
    if (nempty(id))
      return formatSnippetID(id);
    return "?";
  }

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

  static public 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 public AutoCloseable tempActivity(Object r) {
    return null;
  }

  static public long fixTimestamp(long timestamp) {
    return timestamp > now() ? 0 : timestamp;
  }

  static public long now_virtualTime;

  static public long now() {
    return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
  }

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

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

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

  static public Object costCenter() {
    return mc();
  }

  static public float rgbImageSimilarity_sameSize(RGBImage a, RGBImage b, float similarity) {
    int w = a.w(), h = a.h();
    if (w != b.w() || h != b.h())
      throw fail("not same size");
    float factor = w * h;
    float maxError = (1f - similarity) * factor;
    float diff = 0;
    for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) {
      diff += rgbDiff(a.getInt(x, y), b.getInt(x, y));
      if (diff > maxError)
        return similarity - 0.001f;
    }
    return 1f - diff / factor;
  }

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

  static public int max(int a, int b, int c) {
    return max(max(a, b), c);
  }

  static public long max(int a, long b) {
    return Math.max((long) a, b);
  }

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

  static public double max(int a, double b) {
    return Math.max((double) a, b);
  }

  static public float max(float a, float b) {
    return Math.max(a, b);
  }

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

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

  static public 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 public 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 public byte max(byte[] c) {
    byte x = -128;
    for (byte d : c) if (d > x)
      x = d;
    return x;
  }

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

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

  static public Runnable _topLevelErrorHandling(final Runnable runnable) {
    final Object info = _threadInfo();
    return new Runnable() {

      public void run() {
        try {
          try {
            _threadInheritInfo(info);
            runnable.run();
          } catch (Throwable __e) {
            _handleException(__e);
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "pcall {\r\n      _threadInheritInfo(info);\r\n      runnable.run();\r\n    }";
      }
    };
  }

  static public <A> WeakReference<A> weakRef(A a) {
    return newWeakReference(a);
  }

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

  static public 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 public 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 public Object vmBus_wrapArgs(Object... args) {
    return empty(args) ? null : l(args) == 1 ? args[0] : args;
  }

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

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

  static public Set vm_busListeners_live_cache;

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

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

  static public Map<String, Set> vm_busListenersByMessage_live_cache;

  static public 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 public Map<String, Set> vm_busListenersByMessage_live_load() {
    return vm_generalHashMap("busListenersByMessage");
  }

  static public Pt randomPoint(int w, int h) {
    return new Pt(random(w), random(h));
  }

  static public Pt randomPoint(RGBImage img) {
    return randomPoint(img.w(), img.h());
  }

  static public <A> A restructure(A a) {
    return (A) unstructure(structure(a));
  }

  static public float vary0to1(float x) {
    return Math.max(0f, Math.min(1f, (float) (x + random(-0.1, 0.1))));
  }

  static public boolean empty(Collection c) {
    return c == null || c.isEmpty();
  }

  static public boolean empty(Iterable c) {
    return c == null || !c.iterator().hasNext();
  }

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

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

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

  static public 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 public boolean empty(Iterator i) {
    return i == null || !i.hasNext();
  }

  static public boolean empty(double[] a) {
    return a == null || a.length == 0;
  }

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

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

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

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

  static public boolean empty(short[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(MultiSet ms) {
    return ms == null || ms.isEmpty();
  }

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

  static public Pt varyPoint(Pt p, int w, int h) {
    return tossACoin() ? randomPoint(w, h) : varyPoint(p, 10);
  }

  static public Pt varyPoint(Pt p, int range) {
    range = max(range, 1);
    return new Pt(random(p.x - range, p.x + range + 1), random(p.y - range, p.y + range + 1));
  }

  static public <A> A oneOf(List<A> l) {
    return empty(l) ? null : l.get(new Random().nextInt(l.size()));
  }

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

  static public String oneOf(String... l) {
    return oneOf(asList(l));
  }

  static public <A> A collectionGet(Collection<A> c, int idx) {
    if (c == null || idx < 0 || idx >= l(c))
      return null;
    if (c instanceof List)
      return listGet((List<A>) c, idx);
    Iterator<A> it = c.iterator();
    for (int i = 0; i < idx; i++) if (it.hasNext())
      it.next();
    else
      return null;
    return it.hasNext() ? it.next() : null;
  }

  static public String formatWithThousands(long l) {
    return formatWithThousandsSeparator(l);
  }

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

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

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

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

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

  static public String n_fancy2(MultiSet ms, String singular, String plural) {
    return n_fancy2(l(ms), singular, plural);
  }

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

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

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

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

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

  static public double toSeconds(long ms) {
    return ms / 1000.0;
  }

  static public String toSeconds(long ms, int digits) {
    return formatDouble(toSeconds(ms), digits);
  }

  static public double toSeconds(double ms) {
    return ms / 1000.0;
  }

  static public String toSeconds(double ms, int digits) {
    return formatDouble(toSeconds(ms), digits);
  }

  static public Graphics2D antiAliasGraphics(BufferedImage img) {
    return antiAliasOn(createGraphics(img));
  }

  static public Map<BufferedImage, Object> createGraphics_modulators = synchroIdentityHashMap();

  static public Graphics2D createGraphics(BufferedImage img) {
    Graphics2D g = img.createGraphics();
    Object mod = createGraphics_modulators.get(img);
    if (mod != null)
      callF(mod, g);
    return g;
  }

  static public void createGraphics_modulate(BufferedImage img, Object mod) {
    mapPut2(createGraphics_modulators, img, mod);
  }

  static public <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 public List<String> javaTokForStructure(String s) {
    return javaTok_noMLS(s);
  }

  static public String structure_addTokenMarkers(String s) {
    return join(structure_addTokenMarkers(javaTokForStructure(s)));
  }

  static public List<String> structure_addTokenMarkers(List<String> tok) {
    TreeSet<Integer> refs = new TreeSet();
    for (int i = 1; i < l(tok); i += 2) {
      String t = tok.get(i);
      if (t.startsWith("t") && isInteger(t.substring(1)))
        refs.add(parseInt(t.substring(1)));
    }
    if (empty(refs))
      return tok;
    for (int i : refs) {
      int idx = i * 2 + 1;
      if (idx >= l(tok))
        continue;
      String t = "";
      if (endsWithLetterOrDigit(tok.get(idx - 1)))
        t = " ";
      tok.set(idx, t + "m" + i + " " + tok.get(idx));
    }
    return tok;
  }

  static public String jreplace(String s, String in, String out) {
    return jreplace(s, in, out, null);
  }

  static public String jreplace(String s, String in, String out, Object condition) {
    List<String> tok = javaTok(s);
    return jreplace(tok, in, out, condition) ? join(tok) : s;
  }

  static public boolean jreplace(List<String> tok, String in, String out) {
    return jreplace(tok, in, out, false, true, null);
  }

  static public boolean jreplace(List<String> tok, String in, String out, Object condition) {
    return jreplace(tok, in, out, false, true, condition);
  }

  static public boolean jreplace(List<String> tok, String in, String out, IF2<List<String>, Integer, Boolean> condition) {
    return jreplace(tok, in, out, (Object) condition);
  }

  static public boolean jreplace(List<String> tok, String in, String out, boolean ignoreCase, boolean reTok, Object condition) {
    String[] toks = javaTokForJFind_array(in);
    int lTokin = toks.length * 2 + 1;
    boolean anyChange = false;
    int i = -1;
    for (int n = 0; n < 10000; n++) {
      i = findCodeTokens(tok, i + 1, ignoreCase, toks, condition);
      if (i < 0)
        return anyChange;
      List<String> subList = tok.subList(i - 1, i + lTokin - 1);
      String expansion = jreplaceExpandRefs(out, subList);
      int end = i + lTokin - 2;
      clearAllTokens(tok, i, end);
      tok.set(i, expansion);
      if (reTok)
        reTok(tok, i, end);
      i = end;
      anyChange = true;
    }
    throw fail("woot? 10000! " + quote(in) + " => " + quote(out));
  }

  static public boolean jreplace_debug = false;

  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 public <A> String join(Iterable<A> strings) {
    return join("", strings);
  }

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

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

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

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

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

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

  static public 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 public Object pcallFunction(Object f, Object... args) {
    try {
      return callFunction(f, args);
    } catch (Throwable __e) {
      _handleException(__e);
    }
    return null;
  }

  static volatile public PersistableThrowable _handleException_lastException;

  static public List _handleException_onException = synchroList(ll("printStackTrace2"));

  static public 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)
      return;
    for (Object f : cloneList(_handleException_onException)) try {
      callF(f, e);
    } catch (Throwable e3) {
      try {
        printStackTrace2(e3);
      } catch (Throwable e4) {
        System.out.println(getStackTrace(e3));
        System.out.println(getStackTrace(e4));
      }
    }
  }

  static public JTextField onEnter(final JTextField tf, final Object action) {
    if (action == null || tf == null)
      return tf;
    tf.addActionListener(new java.awt.event.ActionListener() {

      public void actionPerformed(java.awt.event.ActionEvent _evt) {
        try {
          tf.selectAll();
          callF(action);
        } catch (Throwable __e) {
          messageBox(__e);
        }
      }
    });
    return tf;
  }

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

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

  static public JComboBox onEnter(final JComboBox cb, final Object action) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            if (cb.isEditable()) {
              JTextField text = (JTextField) cb.getEditor().getEditorComponent();
              onEnter(text, action);
            } else {
              cb.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enter");
              cb.getActionMap().put("enter", abstractAction("", new Runnable() {

                public void run() {
                  try {
                    cb.hidePopup();
                    callF(action);
                  } catch (Exception __e) {
                    throw rethrow(__e);
                  }
                }

                public String toString() {
                  return "cb.hidePopup(); callF(action);";
                }
              }));
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (cb.isEditable()) {\r\n      JTextField text = (JTextField) cb.getEditor().g...";
        }
      });
    }
    return cb;
  }

  static public JTable onEnter(final JTable table, final Object action) {
    table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
    table.getActionMap().put("Enter", new AbstractAction() {

      public void actionPerformed(ActionEvent e) {
        callF(action, table.getSelectedRow());
      }
    });
    return table;
  }

  static public JTextField onEnter(Object action, JTextField tf) {
    return onEnter(tf, action);
  }

  static public String getSelectedItem(JList l) {
    return (String) l.getSelectedValue();
  }

  static public String getSelectedItem(JComboBox cb) {
    return strOrNull(cb.getSelectedItem());
  }

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

  static public 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);
        Method me = cache.findMethod(methodName, args);
        if (me == null || (me.getModifiers() & Modifier.STATIC) == 0)
          return null;
        return invokeMethod(me, null, args);
      } else {
        Class c = o.getClass();
        _MethodCache cache = callOpt_getCache(c);
        Method me = cache.findMethod(methodName, args);
        if (me == null)
          return null;
        return invokeMethod(me, o, args);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

  static public 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 public boolean isStaticMethod(Method m) {
    return methodIsStatic(m);
  }

  static public 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 public <A> String joinWithComma(Collection<A> c) {
    return join(", ", c);
  }

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

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

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

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

  static public <A> void scanForComponents(final Component c, final Class<A> theClass, final List<A> l) {
    if (theClass.isInstance(c))
      l.add((A) c);
    if (c instanceof Container) {
      swing(new Runnable() {

        public void run() {
          try {
            for (Component comp : ((Container) c).getComponents()) scanForComponents(comp, theClass, l);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "for (Component comp : ((Container) c).getComponents())\r\n      scanForComponen...";
        }
      });
    }
  }

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

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

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

  static public 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 public Object vm_generalMap_get(Object key) {
    return vm_generalMap().get(key);
  }

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

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

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

  static public int[] unnull(int[] l) {
    return l == null ? emptyIntArray() : l;
  }

  static public char[] unnull(char[] l) {
    return l == null ? emptyCharArray() : l;
  }

  static public double[] unnull(double[] l) {
    return l == null ? emptyDoubleArray() : l;
  }

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

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

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

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

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

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

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

  static public ArrayList emptyList() {
    return new ArrayList();
  }

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

  static public ArrayList emptyList(Iterable l) {
    return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
  }

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

  static public <A> ArrayList<A> emptyList(Class<A> c) {
    return new ArrayList();
  }

  static public boolean containsSpaces(String s) {
    return indexOf(s, ' ') >= 0;
  }

  static public List map(Iterable l, Object f) {
    return map(f, l);
  }

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

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

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

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

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

  static public <A, B> List<B> map(IF1<A, B> f, A[] l) {
    return map(l, f);
  }

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

  static public List map(Object f, Object[] l) {
    return map(f, asList(l));
  }

  static public List map(Object[] l, Object f) {
    return map(f, l);
  }

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

  static public List map(Map map, Object f) {
    List x = new ArrayList();
    if (map != null)
      for (Object _e : map.entrySet()) {
        Map.Entry e = (Map.Entry) _e;
        x.add(callF(f, e.getKey(), e.getValue()));
      }
    return x;
  }

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

  static public <A> A getOrKeep(Map<A, ? extends A> map, A a) {
    if (map == null)
      return a;
    A v = map.get(a);
    return v != null ? v : a;
  }

  static public List<String> ai_splitCamelCase(String s) {
    int j = 0;
    List<String> l = new ArrayList();
    if (isAllUpperCase(s)) {
      l.add(s);
      return l;
    }
    for (int i = 0; i < l(s); i++) if (i > j && isUpperCaseLetter(s.charAt(i))) {
      l.add(substring(s, j, i));
      j = i;
    }
    if (j < l(s))
      l.add(substring(s, j));
    return l;
  }

  static public <A extends JComponent> A bindLiveValueListenerToComponent(A component, final LiveValue lv, final Runnable listener) {
    if (lv != null)
      bindToComponent(component, new Runnable() {

        public void run() {
          try {
            lv.onChangeAndNow(listener);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "ifdef bindLiveValueListenerToComponent_debug\r\n          print(\"bindLiveValueL...";
        }
      }, new Runnable() {

        public void run() {
          try {
            lv.removeOnChangeListener(listener);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "lv.removeOnChangeListener(listener)";
        }
      });
    return component;
  }

  static public void setChecked(JCheckBox checkBox, boolean b) {
    if (checkBox != null) {
      swing(new Runnable() {

        public void run() {
          try {
            if (isChecked(checkBox) != b)
              checkBox.setSelected(b);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (isChecked(checkBox) != b)\r\n      checkBox.setSelected(b);";
        }
      });
    }
  }

  static public void setChecked(JCheckBoxMenuItem mi, boolean b) {
    if (mi != null) {
      swing(new Runnable() {

        public void run() {
          try {
            mi.setSelected(b);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "mi.setSelected(b);";
        }
      });
    }
  }

  static public boolean isChecked(final JCheckBox checkBox) {
    return checkBox != null && (boolean) swing(new F0<Boolean>() {

      public Boolean get() {
        try {
          return checkBox.isSelected();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret checkBox.isSelected();";
      }
    });
  }

  static public boolean isChecked(final JCheckBoxMenuItem mi) {
    return mi != null && (boolean) swing(new F0<Boolean>() {

      public Boolean get() {
        try {
          return mi.isSelected();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret mi.isSelected();";
      }
    });
  }

  static public ThreadLocal<List<Object>> holdInstance_l = new ThreadLocal();

  static public AutoCloseable holdInstance(Object o) {
    if (o == null)
      return null;
    listThreadLocalAdd(holdInstance_l, o);
    return new AutoCloseable() {

      public void close() {
        listThreadLocalPopLast(holdInstance_l);
      }
    };
  }

  static public void messageBox(final String msg) {
    if (headless())
      print(msg);
    else {
      swing(new Runnable() {

        public void run() {
          try {
            JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MES...";
        }
      });
    }
  }

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

  static public String getText(final AbstractButton c) {
    return c == null ? "" : (String) swingAndWait(new F0<Object>() {

      public Object get() {
        try {
          return c.getText();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret c.getText();";
      }
    });
  }

  static public String getText(final JTextComponent c) {
    return c == null ? "" : (String) swingAndWait(new F0<Object>() {

      public Object get() {
        try {
          return c.getText();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret c.getText();";
      }
    });
  }

  static public String getText(final JLabel l) {
    return l == null ? "" : (String) swingAndWait(new F0<Object>() {

      public Object get() {
        try {
          return l.getText();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret l.getText();";
      }
    });
  }

  static public String getText(final JComboBox cb) {
    if (cb == null)
      return null;
    if (isEditableComboBox(cb))
      return unnull((String) cb.getEditor().getItem());
    else
      return str(cb.getSelectedItem());
  }

  static public Map<String, Font> loadFont_cached_cache = new HashMap();

  static synchronized public Font loadFont_cached(String snippetID) {
    try {
      snippetID = formatSnippetID(snippetID);
      Font f = loadFont_cached_cache.get(snippetID);
      if (f == null)
        loadFont_cached_cache.put(snippetID, f = loadFont(snippetID, 12f));
      return f;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static synchronized public Font loadFont_cached(String snippetID, float size) {
    try {
      return loadFont_cached(snippetID).deriveFont(size);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

  static public float getSwingFontScale() {
    return or((Float) vm_generalMap_get("swingFontScale_value"), 1f);
  }

  static public Timer installTimer(JComponent component, Object r, long delay) {
    return installTimer(component, r, delay, delay);
  }

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

  static public Timer installTimer(JComponent component, long delay, Object r) {
    return installTimer(component, r, delay, delay);
  }

  static public Timer installTimer(JComponent component, long delay, long firstDelay, Object r) {
    return installTimer(component, r, delay, firstDelay);
  }

  static public Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay) {
    return installTimer(component, r, delay, firstDelay, true);
  }

  static public Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay, final boolean repeats) {
    if (component == null)
      return null;
    return (Timer) swingAndWait(new F0<Object>() {

      public Object get() {
        try {
          final Var<Timer> timer = new Var();
          timer.set(new Timer(toInt(delay), new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent _evt) {
              try {
                AutoCloseable __1 = tempActivity(r);
                try {
                  try {
                    if (!allPaused())
                      if (isFalse(callF(r)))
                        cancelTimer(timer.get());
                  } catch (Throwable __e) {
                    _handleException(__e);
                  }
                } finally {
                  _close(__1);
                }
              } catch (Throwable __e) {
                messageBox(__e);
              }
            }
          }));
          timer.get().setInitialDelay(toInt(firstDelay));
          timer.get().setRepeats(repeats);
          bindTimerToComponent(timer.get(), component);
          return timer.get();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "final new Var<Timer> timer;\r\n    timer.set(new Timer(toInt(delay), actionList...";
      }
    });
  }

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

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

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

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

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

  static public boolean containsNewLines(String s) {
    return containsNewLine(s);
  }

  static public String jlabel_textAsHTML_center(String text) {
    return "<html><div style=\"text-align: center;\">" + replace(htmlencode(text), "\n", "<br>") + "</div></html>";
  }

  static public boolean jmenuItem_newThreads = false;

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

  static public JMenuItem jmenuItem(final String text, final Object r) {
    return swing(new F0<JMenuItem>() {

      public JMenuItem get() {
        try {
          Pair<String, Integer> p = jmenu_autoMnemonic(dropPrefix("[disabled] ", text));
          JMenuItem mi = new JMenuItem(p.a);
          if (startsWith(text, "[disabled] "))
            disableMenuItem(mi);
          if (p.b != 0)
            mi.setMnemonic(p.b);
          mi.addActionListener(jmenuItem_newThreads ? actionListenerInNewThread(r) : actionListener(r));
          return mi;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "Pair<S, Int> p = jmenu_autoMnemonic(dropPrefix(\"[disabled] \", text));\r\n    JM...";
      }
    });
  }

  static public MenuItem menuItem(String text, final Object r) {
    MenuItem mi = new MenuItem(text);
    mi.addActionListener(actionListener(r));
    return mi;
  }

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

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

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

  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 public boolean isImageServerSnippet(long id) {
    return id >= 1100000 && id < 1200000;
  }

  static public File loadImageAsFile(String snippetIDOrURL) {
    try {
      if (isURL(snippetIDOrURL))
        throw fail("not implemented");
      if (!isSnippetID(snippetIDOrURL))
        throw fail("Not a URL or snippet ID: " + snippetIDOrURL);
      String snippetID = "" + parseSnippetID(snippetIDOrURL);
      File file = imageSnippetCacheFile(snippetID);
      if (fileSize(file) > 0)
        return file;
      String imageURL = snippetImageURL_noHttps(snippetID);
      System.err.println("Loading image: " + imageURL);
      byte[] data = loadBinaryPage(imageURL);
      saveBinaryFile(file, data);
      return file;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public File DiskSnippetCache_file(long snippetID) {
    return new File(getGlobalCache(), "data_" + snippetID + ".jar");
  }

  public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
    File file = DiskSnippetCache_file(snippetID);
    return file.exists() ? file : null;
  }

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

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

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

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

  static public File loadDataSnippetToFile(String snippetID) {
    try {
      IResourceLoader rl = vm_getResourceLoader();
      if (rl != null)
        return rl.loadLibrary(snippetID);
      return loadDataSnippetToFile_noResourceLoader(snippetID);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

  static public byte[] isGIF_magic = bytesFromHex("47494638");

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

  static public boolean isGIF(File f) {
    return isGIF(loadBeginningOfBinaryFile(f, l(isGIF_magic)));
  }

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

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

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

  static public <A> void setVar(IVar<A> v, A value) {
    if (v != null)
      v.set(value);
  }

  static public java.awt.Color awtColor(String hex) {
    byte[] b = bytesFromHex(dropPrefix("#", hex));
    return new Color(ubyteToInt(b[0]), ubyteToInt(b[1]), ubyteToInt(b[2]));
  }

  static public boolean nempty(Collection c) {
    return !empty(c);
  }

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

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

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

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

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

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

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

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

  static public Class getMainClass() {
    return mc();
  }

  static public Class getMainClass(Object o) {
    try {
      if (o == null)
        return null;
      if (o instanceof Class && eq(((Class) o).getName(), "x30"))
        return (Class) o;
      ClassLoader cl = (o instanceof Class ? (Class) o : o.getClass()).getClassLoader();
      return cl == null ? null : cl.loadClass("main");
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public 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 public boolean emptyString(String s) {
    return s == null || s.length() == 0;
  }

  static public <A> WeakReference<A> newWeakReference(A a) {
    return a == null ? null : new WeakReference(a);
  }

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

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

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

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

  static public int structure_internStringsLongerThan = 50;

  static public int unstructure_unquoteBufSize = 100;

  static public int unstructure_tokrefs;

  abstract static public class unstructure_Receiver {

    abstract public void set(Object o);
  }

  static public Object unstructure(String text, boolean allDynamic, Object classFinder) {
    if (text == null)
      return null;
    return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder);
  }

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

  static public Object unstructure_tok(final Producer<String> tok, final boolean allDynamic, final Object _classFinder) {
    final boolean debug = unstructure_debug;
    final class X {

      public int i = -1;

      final public Object classFinder = _classFinder != null ? _classFinder : _defaultClassFinder();

      public HashMap<Integer, Object> refs = new HashMap();

      public HashMap<Integer, Object> tokrefs = new HashMap();

      public HashSet<String> concepts = new HashSet();

      public HashMap<String, Class> classesMap = new HashMap();

      public List<Runnable> stack = new ArrayList();

      public String curT;

      public char[] unquoteBuf = new char[unstructure_unquoteBufSize];

      public Class findAClass(String fullClassName) {
        return classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName);
      }

      public String unquote(String s) {
        return unquoteUsingCharArray(s, unquoteBuf);
      }

      public String t() {
        return curT;
      }

      public String tpp() {
        String t = curT;
        consume();
        return t;
      }

      public void parse(final unstructure_Receiver out) {
        String t = t();
        int refID = 0;
        if (structure_isMarker(t, 0, l(t))) {
          refID = parseInt(t.substring(1));
          consume();
        }
        final int _refID = refID;
        final int tokIndex = i;
        parse_inner(refID, tokIndex, new unstructure_Receiver() {

          public void set(Object o) {
            if (_refID != 0)
              refs.put(_refID, o);
            if (o != null)
              tokrefs.put(tokIndex, o);
            out.set(o);
          }
        });
      }

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

                public void set(Object value) {
                  if (value instanceof Map) {
                    if (value instanceof NavigableMap) {
                      out.set(Collections.synchronizedNavigableMap((NavigableMap) value));
                      return;
                    }
                    if (value instanceof SortedMap) {
                      out.set(Collections.synchronizedSortedMap((SortedMap) value));
                      return;
                    }
                    {
                      out.set(Collections.synchronizedMap((Map) value));
                      return;
                    }
                  } else {
                    out.set(Collections.synchronizedList((List) value));
                    return;
                  }
                }
              });
              return;
            }
          }
          if (t.equals("{")) {
            parseMap(out);
            return;
          }
          if (t.equals("[")) {
            this.parseList(new ArrayList(), out);
            return;
          }
          if (t.equals("bitset")) {
            parseBitSet(out);
            return;
          }
          if (t.equals("array") || t.equals("intarray") || t.equals("dblarray")) {
            parseArray(out);
            return;
          }
          if (t.equals("ba")) {
            consume();
            String hex = unquote(tpp());
            out.set(hexToBytes(hex));
            return;
          }
          if (t.equals("boolarray")) {
            consume();
            int n = parseInt(tpp());
            String hex = unquote(tpp());
            out.set(boolArrayFromBytes(hexToBytes(hex), n));
            return;
          }
          if (t.equals("class")) {
            out.set(parseClass());
            return;
          }
          if (t.equals("l")) {
            parseLisp(out);
            return;
          }
          if (t.equals("null")) {
            consume();
            out.set(null);
            return;
          }
          if (eq(t, "c")) {
            consume();
            t = t();
            assertTrue(isJavaIdentifier(t));
            concepts.add(t);
          }
          if (eq(t, "cu")) {
            consume();
            t = tpp();
            assertTrue(isJavaIdentifier(t));
            String fullClassName = "main$" + t;
            Class _c = findAClass(fullClassName);
            if (_c == null)
              throw fail("Class not found: " + fullClassName);
            parse(new unstructure_Receiver() {

              public void set(Object value) {
                out.set(call(_c, "_deserialize", value));
              }
            });
            return;
          }
        }
        if (eq(t, "j")) {
          consume("j");
          out.set(parseJava());
          return;
        }
        if (c == null && !isJavaIdentifier(t))
          throw new RuntimeException("Unknown token " + (i + 1) + ": " + quote(t));
        consume();
        String className, fullClassName;
        if (eq(t(), ".")) {
          consume();
          className = fullClassName = t + "." + assertIdentifier(tpp());
        } else {
          className = t;
          fullClassName = "main$" + t;
        }
        if (c == null) {
          if (allDynamic)
            c = null;
          else
            c = findAClass(fullClassName);
          if (c != null)
            classesMap.put(className, c);
        }
        boolean hasBracket = eq(t(), "(");
        if (hasBracket)
          consume();
        boolean hasOuter = hasBracket && eq(t(), "this$1");
        DynamicObject dO = null;
        Object o = null;
        final String thingName = t;
        if (c != null) {
          o = hasOuter ? nuStubInnerObject(c, classFinder) : nuEmptyObject(c);
          if (o instanceof DynamicObject)
            dO = (DynamicObject) o;
        } else {
          if (concepts.contains(t) && (c = findAClass("main$Concept")) != null)
            o = dO = (DynamicObject) nuEmptyObject(c);
          else
            dO = new DynamicObject();
          dO.className = className;
        }
        if (refID != 0)
          refs.put(refID, o != null ? o : dO);
        tokrefs.put(tokIndex, o != null ? o : dO);
        HashMap<String, Object> fields = new HashMap();
        Object _o = o;
        DynamicObject _dO = dO;
        if (hasBracket) {
          stack.add(new Runnable() {

            public void run() {
              try {
                if (eq(t(), ","))
                  consume();
                if (eq(t(), ")")) {
                  consume(")");
                  objRead(_o, _dO, fields, hasOuter);
                  out.set(_o != null ? _o : _dO);
                } else {
                  final String key = unquote(tpp());
                  String t = tpp();
                  if (!eq(t, "="))
                    throw fail("= expected, got " + t + " after " + quote(key) + " in object " + thingName);
                  stack.add(this);
                  parse(new unstructure_Receiver() {

                    public void set(Object value) {
                      fields.put(key, value);
                    }
                  });
                }
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "ifdef unstructure_debug\r\n            print(\"in object values, token: \" + t())...";
            }
          });
        } else {
          objRead(o, dO, fields, hasOuter);
          out.set(o != null ? o : dO);
        }
      }

      public void objRead(Object o, DynamicObject dO, Map<String, Object> fields, boolean hasOuter) {
        if (o != null) {
          if (dO != null) {
            setOptAllDyn_pcall(dO, fields);
          } else {
            setOptAll_pcall(o, fields);
          }
          if (hasOuter)
            fixOuterRefs(o);
        } else
          for (Map.Entry<String, Object> e : fields.entrySet()) setDynObjectValue(dO, intern(e.getKey()), e.getValue());
        if (o != null)
          pcallOpt_noArgs(o, "_doneLoading");
      }

      public void parseSet(final Set set, final unstructure_Receiver out) {
        this.parseList(new ArrayList(), new unstructure_Receiver() {

          public void set(Object o) {
            set.addAll((List) o);
            out.set(set);
          }
        });
      }

      public void parseLisp(final unstructure_Receiver out) {
        throw fail("class Lisp not included");
      }

      public void parseBitSet(final unstructure_Receiver out) {
        consume("bitset");
        consume("{");
        final BitSet bs = new BitSet();
        stack.add(new Runnable() {

          public void run() {
            try {
              if (eq(t(), "}")) {
                consume("}");
                out.set(bs);
              } else {
                stack.add(this);
                parse(new unstructure_Receiver() {

                  public void set(Object o) {
                    bs.set((Integer) o);
                    if (eq(t(), ","))
                      consume();
                  }
                });
              }
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "if (eq(t(), \"}\")) {\r\n          consume(\"}\");\r\n          out.set(bs);\r\n       ...";
          }
        });
      }

      public void parseList(final List list, final unstructure_Receiver out) {
        tokrefs.put(i, list);
        consume("[");
        stack.add(new Runnable() {

          public void run() {
            try {
              if (eq(t(), "]")) {
                consume();
                out.set(list);
              } else {
                stack.add(this);
                parse(new unstructure_Receiver() {

                  public void set(Object o) {
                    list.add(o);
                    if (eq(t(), ","))
                      consume();
                  }
                });
              }
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "if (eq(t(), \"]\")) {\r\n          consume();\r\n          ifdef unstructure_debug\r...";
          }
        });
      }

      public void parseArray(final unstructure_Receiver out) {
        final String type = tpp();
        consume("{");
        final List list = new ArrayList();
        stack.add(new Runnable() {

          public void run() {
            try {
              if (eq(t(), "}")) {
                consume("}");
                out.set(type.equals("intarray") ? toIntArray(list) : type.equals("dblarray") ? toDoubleArray(list) : list.toArray());
              } else {
                stack.add(this);
                parse(new unstructure_Receiver() {

                  public void set(Object o) {
                    list.add(o);
                    if (eq(t(), ","))
                      consume();
                  }
                });
              }
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "if (eq(t(), \"}\")) {\r\n          consume(\"}\");\r\n          out.set(\r\n           ...";
          }
        });
      }

      public Object parseClass() {
        consume("class");
        consume("(");
        String name = unquote(tpp());
        consume(")");
        Class c = allDynamic ? null : findAClass(name);
        if (c != null)
          return c;
        DynamicObject dO = new DynamicObject();
        dO.className = "java.lang.Class";
        name = dropPrefix("main$", name);
        dO.fieldValues.put("name", name);
        return dO;
      }

      public Object parseBigInt() {
        consume("bigint");
        consume("(");
        String val = tpp();
        if (eq(val, "-"))
          val = "-" + tpp();
        consume(")");
        return new BigInteger(val);
      }

      public Object parseDouble() {
        consume("d");
        consume("(");
        String val = unquote(tpp());
        consume(")");
        return Double.parseDouble(val);
      }

      public Object parseFloat() {
        consume("fl");
        String val;
        if (eq(t(), "(")) {
          consume("(");
          val = unquote(tpp());
          consume(")");
        } else {
          val = unquote(tpp());
        }
        return Float.parseFloat(val);
      }

      public void parseHashSet(unstructure_Receiver out) {
        consume("hashset");
        parseSet(new HashSet(), out);
      }

      public void parseLinkedHashSet(unstructure_Receiver out) {
        consume("lhs");
        parseSet(new LinkedHashSet(), out);
      }

      public void parseTreeSet(unstructure_Receiver out) {
        consume("treeset");
        parseSet(new TreeSet(), out);
      }

      public void parseCISet(unstructure_Receiver out) {
        consume("ciset");
        parseSet(ciSet(), out);
      }

      public void parseMap(unstructure_Receiver out) {
        parseMap(new TreeMap(), out);
      }

      public Object parseJava() {
        String j = unquote(tpp());
        Matches m = new Matches();
        if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m))
          return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2)));
        else {
          warn("Unknown Java object: " + j);
          return null;
        }
      }

      public void parseMap(final Map map, final unstructure_Receiver out) {
        consume("{");
        stack.add(new Runnable() {

          public boolean v = false;

          public Object key;

          public void run() {
            if (v) {
              v = false;
              stack.add(this);
              if (!eq(tpp(), "="))
                throw fail("= expected, got " + t() + " in map of size " + l(map));
              parse(new unstructure_Receiver() {

                public void set(Object value) {
                  map.put(key, value);
                  if (eq(t(), ","))
                    consume();
                }
              });
            } else {
              if (eq(t(), "}")) {
                consume("}");
                out.set(map);
              } else {
                v = true;
                stack.add(this);
                parse(new unstructure_Receiver() {

                  public void set(Object o) {
                    key = o;
                  }
                });
              }
            }
          }
        });
      }

      public void consume() {
        curT = tok.next();
        ++i;
      }

      public void consume(String s) {
        if (!eq(t(), s)) {
          throw fail(quote(s) + " expected, got " + quote(t()));
        }
        consume();
      }

      public void parse_initial(unstructure_Receiver out) {
        consume();
        parse(out);
        while (nempty(stack)) popLast(stack).run();
      }
    }
    ThreadLocal<Boolean> tlLoading = dynamicObjectIsLoading_threadLocal();
    Boolean b = tlLoading.get();
    tlLoading.set(true);
    try {
      final Var v = new Var();
      X x = new X();
      x.parse_initial(new unstructure_Receiver() {

        public void set(Object o) {
          v.set(o);
        }
      });
      unstructure_tokrefs = x.tokrefs.size();
      return v.get();
    } finally {
      tlLoading.set(b);
    }
  }

  static public boolean unstructure_debug = false;

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

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

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

  static public boolean tossACoin() {
    return tossCoin();
  }

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

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

  static public String trim(String s) {
    return s == null ? null : s.trim();
  }

  static public String trim(StringBuilder buf) {
    return buf.toString().trim();
  }

  static public String trim(StringBuffer buf) {
    return buf.toString().trim();
  }

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

  static public Graphics2D antiAliasOn(Graphics2D g) {
    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    return g;
  }

  static public <A, B> Map<A, B> synchroIdentityHashMap() {
    return synchroMap(new IdentityHashMap());
  }

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

  static public Throwable printStackTrace2(Throwable e) {
    print(getStackTrace2(e));
    return e;
  }

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

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

  static public boolean loadBufferedImage_useImageCache = true;

  static public BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) {
    try {
      ping();
      if (snippetIDOrURLOrFile == null)
        return null;
      if (isURL(snippetIDOrURLOrFile))
        return imageIO_readURL(snippetIDOrURLOrFile);
      if (isAbsolutePath(snippetIDOrURLOrFile))
        return loadBufferedImage(new File(snippetIDOrURLOrFile));
      if (!isSnippetID(snippetIDOrURLOrFile))
        throw fail("Not a URL or snippet ID or file: " + snippetIDOrURLOrFile);
      String snippetID = "" + parseSnippetID(snippetIDOrURLOrFile);
      IResourceLoader rl = vm_getResourceLoader();
      if (rl != null)
        return loadBufferedImage(rl.loadLibrary(snippetID));
      File dir = imageSnippetsCacheDir();
      if (loadBufferedImage_useImageCache) {
        dir.mkdirs();
        File file = new File(dir, snippetID + ".png");
        if (file.exists() && file.length() != 0)
          try {
            return ImageIO.read(file);
          } catch (Throwable e) {
            e.printStackTrace();
          }
      }
      String imageURL = snippetImageURL_http(snippetID);
      print("Loading image: " + imageURL);
      BufferedImage image = imageIO_readURL(imageURL);
      if (loadBufferedImage_useImageCache) {
        File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis());
        ImageIO.write(image, "png", tempFile);
        tempFile.renameTo(new File(dir, snippetID + ".png"));
      }
      return image;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

  static public List<String> javaTok_noMLS(String s) {
    ArrayList<String> tok = new ArrayList();
    int l = s == null ? 0 : s.length();
    int i = 0, n = 0;
    while (i < l) {
      int j = i;
      char c, d;
      while (j < l) {
        c = s.charAt(j);
        d = j + 1 >= l ? '\0' : s.charAt(j + 1);
        if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
          ++j;
        else if (c == '/' && d == '*') {
          do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
          j = Math.min(j + 2, l);
        } else if (c == '/' && d == '/') {
          do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
        } else
          break;
      }
      tok.add(javaTok_substringN(s, i, j));
      ++n;
      i = j;
      if (i >= l)
        break;
      c = s.charAt(i);
      d = i + 1 >= l ? '\0' : s.charAt(i + 1);
      if (c == '\'' || c == '"') {
        char opener = c;
        ++j;
        while (j < l) {
          int c2 = s.charAt(j);
          if (c2 == opener || c2 == '\n' && opener == '\'') {
            ++j;
            break;
          } else if (c2 == '\\' && j + 1 < l)
            j += 2;
          else
            ++j;
        }
      } else if (Character.isJavaIdentifierStart(c))
        do ++j; while (j < l && Character.isJavaIdentifierPart(s.charAt(j)));
      else if (Character.isDigit(c)) {
        do ++j; while (j < l && Character.isDigit(s.charAt(j)));
        if (j < l && s.charAt(j) == 'L')
          ++j;
      } else
        ++j;
      tok.add(javaTok_substringC(s, i, j));
      ++n;
      i = j;
    }
    if ((tok.size() % 2) == 0)
      tok.add("");
    return tok;
  }

  static public boolean isInteger(String s) {
    int n = l(s);
    if (n == 0)
      return false;
    int i = 0;
    if (s.charAt(0) == '-')
      if (++i >= n)
        return false;
    while (i < n) {
      char c = s.charAt(i);
      if (c < '0' || c > '9')
        return false;
      ++i;
    }
    return true;
  }

  static public int javaTok_n, javaTok_elements;

  static public boolean javaTok_opt = false;

  static public List<String> javaTok(String s) {
    ++javaTok_n;
    ArrayList<String> tok = new ArrayList();
    int l = s == null ? 0 : s.length();
    int i = 0;
    while (i < l) {
      int j = i;
      char c, d;
      while (j < l) {
        c = s.charAt(j);
        d = j + 1 >= l ? '\0' : s.charAt(j + 1);
        if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
          ++j;
        else if (c == '/' && d == '*') {
          do ++j; while (j < l && !regionMatches(s, j, "*/"));
          j = Math.min(j + 2, l);
        } else if (c == '/' && d == '/') {
          do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
        } else
          break;
      }
      tok.add(javaTok_substringN(s, i, j));
      i = j;
      if (i >= l)
        break;
      c = s.charAt(i);
      d = i + 1 >= l ? '\0' : s.charAt(i + 1);
      if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
        j += 2;
        while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
      } else if (c == '\'' || c == '"') {
        char opener = c;
        ++j;
        while (j < l) {
          int c2 = s.charAt(j);
          if (c2 == opener || c2 == '\n' && opener == '\'') {
            ++j;
            break;
          } else if (c2 == '\\' && j + 1 < l)
            j += 2;
          else
            ++j;
        }
      } else if (Character.isJavaIdentifierStart(c))
        do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\''));
      else if (Character.isDigit(c)) {
        do ++j; while (j < l && Character.isDigit(s.charAt(j)));
        if (j < l && s.charAt(j) == 'L')
          ++j;
      } else if (c == '[' && d == '[') {
        do ++j; while (j < l && !regionMatches(s, j, "]]"));
        j = Math.min(j + 2, l);
      } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
        do ++j; while (j + 2 < l && !regionMatches(s, j, "]=]"));
        j = Math.min(j + 3, l);
      } else
        ++j;
      tok.add(javaTok_substringC(s, i, j));
      i = j;
    }
    if ((tok.size() % 2) == 0)
      tok.add("");
    javaTok_elements += tok.size();
    return tok;
  }

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

  static public Map<String, String[]> javaTokForJFind_array_cache = synchronizedMRUCache(1000);

  static public String[] javaTokForJFind_array(String s) {
    String[] tok = javaTokForJFind_array_cache.get(s);
    if (tok == null)
      javaTokForJFind_array_cache.put(s, tok = codeTokensAsStringArray(jfind_preprocess(javaTok(s))));
    return tok;
  }

  static public int findCodeTokens(List<String> tok, String... tokens) {
    return findCodeTokens(tok, 1, false, tokens);
  }

  static public int findCodeTokens(List<String> tok, boolean ignoreCase, String... tokens) {
    return findCodeTokens(tok, 1, ignoreCase, tokens);
  }

  static public int findCodeTokens(List<String> tok, int startIdx, boolean ignoreCase, String... tokens) {
    return findCodeTokens(tok, startIdx, ignoreCase, tokens, null);
  }

  static public HashSet<String> findCodeTokens_specials = lithashset("*", "<quoted>", "<id>", "<int>", "\\*");

  static public int findCodeTokens_bails, findCodeTokens_nonbails;

  static public interface findCodeTokens_Matcher {

    public boolean get(String token);
  }

  static public int findCodeTokens(List<String> tok, int startIdx, boolean ignoreCase, String[] tokens, Object condition) {
    int end = tok.size() - tokens.length * 2 + 2, nTokens = tokens.length;
    int i = startIdx | 1;
    String firstToken = tokens[0];
    if (!ignoreCase && !findCodeTokens_specials.contains(firstToken)) {
      while (i < end && !firstToken.equals(tok.get(i))) i += 2;
    }
    findCodeTokens_Matcher[] matchers = new findCodeTokens_Matcher[nTokens];
    for (int j = 0; j < nTokens; j++) {
      String p = tokens[j];
      findCodeTokens_Matcher matcher;
      if (p.equals("*"))
        matcher = t -> true;
      else if (p.equals("<quoted>"))
        matcher = t -> isQuoted(t);
      else if (p.equals("<id>"))
        matcher = t -> isIdentifier(t);
      else if (p.equals("<int>"))
        matcher = t -> isInteger(t);
      else if (p.equals("\\*"))
        matcher = t -> t.equals("*");
      else if (ignoreCase)
        matcher = t -> eqic(p, t);
      else
        matcher = t -> t.equals(p);
      matchers[j] = matcher;
    }
    outer: for (; i < end; i += 2) {
      for (int j = 0; j < nTokens; j++) if (!matchers[j].get(tok.get(i + j * 2)))
        continue outer;
      if (condition == null || checkTokCondition(condition, tok, i - 1))
        return i;
    }
    return -1;
  }

  static public String jreplaceExpandRefs(String s, List<String> tokref) {
    if (!contains(s, '$'))
      return s;
    List<String> tok = javaTok(s);
    for (int i = 1; i < l(tok); i += 2) {
      String t = tok.get(i);
      if (t.startsWith("$") && isInteger(t.substring(1))) {
        String x = tokref.get(-1 + parseInt(t.substring(1)) * 2);
        tok.set(i, x);
      } else if (t.equals("\\")) {
        tok.set(i, "");
        i += 2;
      }
    }
    return join(tok);
  }

  static public void clearAllTokens(List<String> tok) {
    for (int i = 0; i < tok.size(); i++) tok.set(i, "");
  }

  static public void clearAllTokens(List<String> tok, int i, int j) {
    for (; i < j; i++) tok.set(i, "");
  }

  static public List<String> reTok(List<String> tok) {
    replaceCollection(tok, javaTok(tok));
    return tok;
  }

  static public List<String> reTok(List<String> tok, int i) {
    return reTok(tok, i, i + 1);
  }

  static public List<String> reTok(List<String> tok, int i, int j) {
    i = max(i & ~1, 0);
    j = min(l(tok), j | 1);
    if (i >= j)
      return tok;
    List<String> t = javaTok(joinSubList(tok, i, j));
    replaceListPart(tok, i, j, t);
    return tok;
  }

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

  static public 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 public 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 volatile public PersistableThrowable lastException_lastException;

  static public PersistableThrowable lastException() {
    return lastException_lastException;
  }

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

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

  static public 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 public String hideCredentials(Object o) {
    return hideCredentials(str(o));
  }

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

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

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

  static public <A> List<A> synchroList() {
    return Collections.synchronizedList(new ArrayList<A>());
  }

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

  static public <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 public PersistableThrowable persistableThrowable(Throwable e) {
    return e == null ? null : new PersistableThrowable(e);
  }

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

  static public KeyListener enterKeyListener(final Object action) {
    return new KeyAdapter() {

      public void keyPressed(KeyEvent ke) {
        if (ke.getKeyCode() == KeyEvent.VK_ENTER)
          pcallF(action);
      }
    };
  }

  static public Runnable rCallOnSelectedListItem(final JList list, final Object action) {
    return new Runnable() {

      public void run() {
        try {
          pcallF(action, getSelectedItem(list));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "pcallF(action, getSelectedItem(list))";
      }
    };
  }

  static public AbstractAction abstractAction(String name, final Object runnable) {
    return new AbstractAction(name) {

      public void actionPerformed(ActionEvent evt) {
        pcallF(runnable);
      }
    };
  }

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

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

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

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

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

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

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

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

  static public 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 public Map<String, Class> classForName_cache = synchroHashMap();

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

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

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

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

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

  static public Field makeAccessible(Field f) {
    try {
      f.setAccessible(true);
    } catch (Throwable e) {
      vmBus_send("makeAccessible_error", e, f);
    }
    return f;
  }

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

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

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

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

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

  static public int[] emptyIntArray_a = new int[0];

  static public int[] emptyIntArray() {
    return emptyIntArray_a;
  }

  static public char[] emptyCharArray = new char[0];

  static public char[] emptyCharArray() {
    return emptyCharArray;
  }

  static public double[] emptyDoubleArray = new double[0];

  static public double[] emptyDoubleArray() {
    return emptyDoubleArray;
  }

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

  static public Object[] emptyObjectArray_a = new Object[0];

  static public Object[] emptyObjectArray() {
    return emptyObjectArray_a;
  }

  static public boolean isAllUpperCase(String s) {
    return hasLettersAllUpperCase(s);
  }

  static public boolean isUpperCaseLetter(char c) {
    return Character.isUpperCase(c);
  }

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

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

  static public String substring(String s, CharSequence l) {
    return substring(s, l(l));
  }

  static public <A> void listThreadLocalAdd(ThreadLocal<List<A>> tl, A a) {
    List<A> l = tl.get();
    if (l == null)
      tl.set(l = new ArrayList());
    l.add(a);
  }

  static public <A> A listThreadLocalPopLast(ThreadLocal<List<A>> tl) {
    List<A> l = tl.get();
    if (l == null)
      return null;
    A a = popLast(l);
    if (empty(l))
      tl.set(null);
    return a;
  }

  static public boolean headless() {
    return isHeadless();
  }

  static public Throwable innerException2(Throwable e) {
    if (e == null)
      return null;
    while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause();
    return e;
  }

  static public Font loadFont(String snippetID) {
    try {
      return loadFont(snippetID, 12f);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Font loadFont(InputStream in) {
    try {
      return Font.createFont(Font.TRUETYPE_FONT, in);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Font loadFont(String snippetID, float fontSize) {
    return loadFont(loadLibrary(snippetID), fontSize);
  }

  static public Font loadFont(File f, float fontSize) {
    try {
      return Font.createFont(Font.TRUETYPE_FONT, f).deriveFont(fontSize);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Font loadFont(InputStream in, float fontSize) {
    try {
      return Font.createFont(Font.TRUETYPE_FONT, in).deriveFont(fontSize);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public 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 public boolean allPaused() {
    return ping_pauseAll;
  }

  static public void cancelTimer(javax.swing.Timer timer) {
    if (timer != null)
      timer.stop();
  }

  static public void cancelTimer(java.util.Timer timer) {
    if (timer != null)
      timer.cancel();
  }

  static public void cancelTimer(Object o) {
    if (o instanceof java.util.Timer)
      cancelTimer((java.util.Timer) o);
    else if (o instanceof javax.swing.Timer)
      cancelTimer((javax.swing.Timer) o);
    else if (o instanceof AutoCloseable) {
      try {
        ((AutoCloseable) o).close();
      } catch (Throwable __e) {
        _handleException(__e);
      }
    }
  }

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

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

      public void ancestorAdded(AncestorEvent event) {
        timer.start();
      }

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

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

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

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

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

  static public boolean containsNewLine(String s) {
    return contains(s, '\n');
  }

  static public <A> List<A> replace(List<A> l, A a, A b) {
    for (int i = 0; i < l(l); i++) if (eq(l.get(i), a))
      l.set(i, b);
    return l;
  }

  static public <A> List<A> replace(A a, A b, List<A> l) {
    return replace(l, a, b);
  }

  static public String replace(String s, String a, String b) {
    return s == null ? null : a == null || b == null ? s : s.replace(a, b);
  }

  static public String replace(String s, char a, char b) {
    return s == null ? null : s.replace(a, b);
  }

  static public String htmlencode(Object o) {
    return htmlencode(str(o));
  }

  static public String htmlencode(String s) {
    if (s == null)
      return "";
    StringBuilder out = new StringBuilder(Math.max(16, s.length()));
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') {
        int cp = s.codePointAt(i);
        out.append("&#x");
        out.append(intToHex_flexLength(cp));
        out.append(';');
        i += Character.charCount(cp) - 1;
      } else
        out.append(c);
    }
    return out.toString();
  }

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

  static public JMenuItem jMenuItem(String text, Object r) {
    return jmenuItem(text, r);
  }

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

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

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

  static public 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 public 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 public JMenuItem disableMenuItem(final JMenuItem mi) {
    if (mi != null) {
      swing(new Runnable() {

        public void run() {
          try {
            mi.setEnabled(false);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "mi.setEnabled(false);";
        }
      });
    }
    return mi;
  }

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

  static public ActionListener actionListenerInNewThread(final Object runnable, final Object instanceToHold) {
    if (runnable instanceof ActionListener)
      return (ActionListener) runnable;
    return new java.awt.event.ActionListener() {

      public void actionPerformed(java.awt.event.ActionEvent _evt) {
        try {
          startThread("Action Listener", new Runnable() {

            public void run() {
              try {
                AutoCloseable __1 = holdInstance(instanceToHold);
                try {
                  callF(runnable);
                } finally {
                  _close(__1);
                }
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "AutoCloseable __1 = holdInstance(instanceToHold); try {\r\n      callF(runnable...";
            }
          });
        } catch (Throwable __e) {
          messageBox(__e);
        }
      }
    };
  }

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

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

  static public 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 public boolean isURL(String s) {
    return startsWithOneOf(s, "http://", "https://", "file:");
  }

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

  static public File imageSnippetCacheFile(String snippetID) {
    File dir = imageSnippetsCacheDir();
    if (!loadBufferedImage_useImageCache)
      return null;
    return new File(dir, parseSnippetID(snippetID) + ".png");
  }

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

  static public String snippetImageURL_noHttps(String snippetID, String contentType) {
    return snippetImageURL(snippetID, contentType).replace("https://www.botcompany.de:8443/", "http://www.botcompany.de:8080/").replace("https://botcompany.de/", "http://botcompany.de/");
  }

  static public ThreadLocal<Map<String, List<String>>> loadBinaryPage_responseHeaders = new ThreadLocal();

  static public ThreadLocal<Map<String, String>> loadBinaryPage_extraHeaders = new ThreadLocal();

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

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

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

  public static byte[] saveBinaryFile(String fileName, byte[] contents) {
    try {
      File file = new File(fileName);
      File parentFile = file.getParentFile();
      if (parentFile != null)
        parentFile.mkdirs();
      String tempFileName = fileName + "_temp";
      FileOutputStream fileOutputStream = newFileOutputStream(tempFileName);
      fileOutputStream.write(contents);
      fileOutputStream.close();
      if (file.exists() && !file.delete())
        throw new IOException("Can't delete " + fileName);
      if (!new File(tempFileName).renameTo(file))
        throw new IOException("Can't rename " + tempFileName + " to " + fileName);
      vmBus_send("wroteFile", file);
      return contents;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public byte[] saveBinaryFile(File fileName, byte[] contents) {
    return saveBinaryFile(fileName.getPath(), contents);
  }

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

  static public String dataSnippetLink(String snippetID) {
    long id = parseSnippetID(snippetID);
    if (id >= 1100000 && id < 1200000)
      return imageServerURL() + id;
    if (id >= 1200000 && id < 1300000) {
      String pw = muricaPassword();
      if (empty(pw))
        throw fail("Please set 'murica password by running #1008829");
      return "https://botcompany.de/files/" + id + "?_pass=" + pw;
    }
    return fileServerURL() + "/" + id;
  }

  static public String tb_mainServer_default = "http://code.botcompany.de:8081";

  static public Object tb_mainServer_override;

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

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

  static public boolean tb_mainServer_isDefault() {
    return eq(tb_mainServer(), tb_mainServer_default);
  }

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

  static public void loadBinaryPageToFile(String url, File file) {
    try {
      print("Loading " + url);
      loadBinaryPageToFile(openConnection(new URL(url)), file);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

  static public URLConnection openConnection(URL url) {
    try {
      ping();
      callOpt(javax(), "recordOpenURLConnection", str(url));
      return url.openConnection();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

  static public byte[] bytesFromHex(String s) {
    return hexToBytes(s);
  }

  static public boolean byteArrayStartsWith(byte[] a, byte[] b) {
    if (a == null || b == null)
      return false;
    if (a.length < b.length)
      return false;
    for (int i = 0; i < b.length; i++) if (a[i] != b[i])
      return false;
    return true;
  }

  static public byte[] loadBeginningOfBinaryFile(File file, int maxBytes) {
    return loadBinaryFilePart(file, 0, maxBytes);
  }

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

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

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

  static public int ubyteToInt(byte b) {
    return b & 0x0FF;
  }

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

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

  static public <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 public <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 public Object collectionMutex(List l) {
    return l;
  }

  static public 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 public Producer<String> javaTokC_noMLS_iterator(final String s) {
    return javaTokC_noMLS_iterator(s, 0);
  }

  static public Producer<String> javaTokC_noMLS_iterator(final String s, final int startIndex) {
    return new Producer<String>() {

      final public int l = s.length();

      public int i = startIndex;

      public String next() {
        if (i >= l)
          return null;
        int j = i;
        char c, d;
        while (j < l) {
          c = s.charAt(j);
          d = j + 1 >= l ? '\0' : s.charAt(j + 1);
          if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
            ++j;
          else if (c == '/' && d == '*') {
            do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
            j = Math.min(j + 2, l);
          } else if (c == '/' && d == '/') {
            do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
          } else
            break;
        }
        i = j;
        if (i >= l)
          return null;
        c = s.charAt(i);
        d = i + 1 >= l ? '\0' : s.charAt(i + 1);
        if (c == '\'' || c == '"') {
          char opener = c;
          ++j;
          while (j < l) {
            if (s.charAt(j) == opener || s.charAt(j) == '\n') {
              ++j;
              break;
            } else if (s.charAt(j) == '\\' && j + 1 < l)
              j += 2;
            else
              ++j;
          }
        } else if (Character.isJavaIdentifierStart(c))
          do ++j; while (j < l && Character.isJavaIdentifierPart(s.charAt(j)));
        else if (Character.isDigit(c)) {
          do ++j; while (j < l && Character.isDigit(s.charAt(j)));
          if (j < l && s.charAt(j) == 'L')
            ++j;
        } else
          ++j;
        String t = quickSubstring(s, i, j);
        i = j;
        return t;
      }
    };
  }

  static public Producer<String> javaTokC_noMLS_onReader(final BufferedReader r) {
    final class X implements Producer<String> {

      public StringBuilder buf = new StringBuilder();

      public char c, d, e = 'x';

      public X() {
        nc();
        nc();
        nc();
      }

      public void nc() {
        try {
          c = d;
          d = e;
          if (e == '\0')
            return;
          int i = r.read();
          e = i < 0 ? '\0' : i == '\0' ? '_' : (char) i;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public void ncSave() {
        if (c != '\0') {
          buf.append(c);
          nc();
        }
      }

      public String next() {
        while (c != '\0') {
          if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
            nc();
          else if (c == '/' && d == '*') {
            do nc(); while (c != '\0' && !(c == '*' && d == '/'));
            nc();
            nc();
          } else if (c == '/' && d == '/') {
            do nc(); while (c != '\0' && "\r\n".indexOf(c) < 0);
          } else
            break;
        }
        if (c == '\0')
          return null;
        if (c == '\'' || c == '"') {
          char opener = c;
          ncSave();
          while (c != '\0') {
            if (c == opener || c == '\n') {
              ncSave();
              break;
            } else if (c == '\\') {
              ncSave();
              ncSave();
            } else
              ncSave();
          }
        } else if (Character.isJavaIdentifierStart(c))
          do ncSave(); while (Character.isJavaIdentifierPart(c) || c == '\'');
        else if (Character.isDigit(c)) {
          do ncSave(); while (Character.isDigit(c));
          if (c == 'L')
            ncSave();
        } else
          ncSave();
        String t = buf.toString();
        buf.setLength(0);
        return t;
      }
    }
    return new X();
  }

  static public String unquoteUsingCharArray(String s, char[] buf) {
    if (s == null)
      return null;
    if (startsWith(s, '[')) {
      int i = 1;
      while (i < s.length() && s.charAt(i) == '=') ++i;
      if (i < s.length() && s.charAt(i) == '[') {
        String m = s.substring(1, i);
        if (s.endsWith("]" + m + "]"))
          return s.substring(i + 1, s.length() - i - 1);
      }
    }
    if (s.length() > 1) {
      char c = s.charAt(0);
      if (c == '\"' || c == '\'') {
        int l = endsWith(s, c) ? s.length() - 1 : s.length();
        if (l > buf.length)
          return unquote(s);
        int n = 0;
        for (int i = 1; i < l; i++) {
          char ch = s.charAt(i);
          if (ch == '\\') {
            char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
            if (nextChar >= '0' && nextChar <= '7') {
              String code = "" + nextChar;
              i++;
              if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
                code += s.charAt(i + 1);
                i++;
                if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
                  code += s.charAt(i + 1);
                  i++;
                }
              }
              buf[n++] = (char) Integer.parseInt(code, 8);
              continue;
            }
            switch(nextChar) {
              case '\"':
                ch = '\"';
                break;
              case '\\':
                ch = '\\';
                break;
              case 'b':
                ch = '\b';
                break;
              case 'f':
                ch = '\f';
                break;
              case 'n':
                ch = '\n';
                break;
              case 'r':
                ch = '\r';
                break;
              case 't':
                ch = '\t';
                break;
              case '\'':
                ch = '\'';
                break;
              case 'u':
                if (i >= l - 5) {
                  ch = 'u';
                  break;
                }
                int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16);
                char[] x = Character.toChars(code);
                int lx = x.length;
                for (int j = 0; j < lx; j++) buf[n++] = x[j];
                i += 5;
                continue;
              default:
                ch = nextChar;
            }
            i++;
          }
          buf[n++] = ch;
        }
        return new String(buf, 0, n);
      }
    }
    return s;
  }

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

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

  static public 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);
            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;
              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;
            }
            i++;
          }
          sb.append(ch);
        }
        return sb.toString();
      }
    }
    return s;
  }

  static public 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 public BigInteger parseBigInt(String s) {
    return new BigInteger(s);
  }

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

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

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

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

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

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

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

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

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

  static public byte[] hexToBytes(String s) {
    if (odd(l(s)))
      throw fail("Hex string has odd length: " + quote(shorten(10, s)));
    int n = l(s) / 2;
    byte[] bytes = new byte[n];
    for (int i = 0; i < n; i++) {
      int a = parseHexChar(s.charAt(i * 2));
      int b = parseHexChar(s.charAt(i * 2 + 1));
      if (a < 0 || b < 0)
        throw fail("Bad hex byte: " + quote(substring(s, i * 2, i * 2 + 2)) + " at " + i * 2 + "/" + l(s));
      bytes[i] = (byte) ((a << 4) | b);
    }
    return bytes;
  }

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

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

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

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

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

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

  static public <A> A nuEmptyObject(Class<A> c) {
    try {
      Constructor ctr;
      synchronized (nuEmptyObject_cache) {
        ctr = nuEmptyObject_cache.get(c);
        if (ctr == null) {
          nuEmptyObject_cache.put(c, ctr = nuEmptyObject_findConstructor(c));
          makeAccessible(ctr);
        }
      }
      try {
        return (A) ctr.newInstance();
      } catch (InstantiationException e) {
        if (empty(e.getMessage()))
          if ((c.getModifiers() & Modifier.ABSTRACT) != 0)
            throw fail("Can't instantiate abstract class " + className(c), e);
          else
            throw fail("Can't instantiate " + className(c), e);
        else
          throw rethrow(e);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

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

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

  static public void setDynObjectValue(DynamicObject o, String field, Object value) {
    o.fieldValues = syncMapPut2_createLinkedHashMap(o.fieldValues, field, value);
  }

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

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

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

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

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

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

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

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

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

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

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

  static public boolean warn_on = true;

  static public ThreadLocal<List<String>> warn_warnings = new ThreadLocal();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  static public String javaTok_substringN(String s, int i, int j) {
    if (i == j)
      return "";
    if (j == i + 1 && s.charAt(i) == ' ')
      return " ";
    return s.substring(i, j);
  }

  static public String javaTok_substringC(String s, int i, int j) {
    return s.substring(i, j);
  }

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

  static public boolean regionMatches(String a, int offsetA, String b) {
    return regionMatches(a, offsetA, b, 0, l(b));
  }

  static public List<String> javaTokWithExisting(String s, List<String> existing) {
    ++javaTok_n;
    int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
    ArrayList<String> tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
    int l = s.length();
    int i = 0, n = 0;
    while (i < l) {
      int j = i;
      char c, d;
      while (j < l) {
        c = s.charAt(j);
        d = j + 1 >= l ? '\0' : s.charAt(j + 1);
        if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
          ++j;
        else if (c == '/' && d == '*') {
          do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
          j = Math.min(j + 2, l);
        } else if (c == '/' && d == '/') {
          do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
        } else
          break;
      }
      if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
        tok.add(existing.get(n));
      else
        tok.add(javaTok_substringN(s, i, j));
      ++n;
      i = j;
      if (i >= l)
        break;
      c = s.charAt(i);
      d = i + 1 >= l ? '\0' : s.charAt(i + 1);
      if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
        j += 2;
        while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
      } else if (c == '\'' || c == '"') {
        char opener = c;
        ++j;
        while (j < l) {
          if (s.charAt(j) == opener) {
            ++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));
      else if (Character.isDigit(c)) {
        do ++j; while (j < l && Character.isDigit(s.charAt(j)));
        if (j < l && s.charAt(j) == 'L')
          ++j;
      } else if (c == '[' && d == '[') {
        do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
        j = Math.min(j + 2, l);
      } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
        do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
        j = Math.min(j + 3, l);
      } else
        ++j;
      if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
        tok.add(existing.get(n));
      else
        tok.add(javaTok_substringC(s, i, j));
      ++n;
      i = j;
    }
    if ((tok.size() % 2) == 0)
      tok.add("");
    javaTok_elements += tok.size();
    return tok;
  }

  static public boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
    return t.length() == j - i && s.regionMatches(i, t, 0, j - i);
  }

  static public <A, B> Map<A, B> synchronizedMRUCache(int maxSize) {
    return synchroMap(new MRUCache(maxSize));
  }

  static public String[] codeTokensAsStringArray(List<String> tok) {
    int n = max(0, (l(tok) - 1) / 2);
    String[] out = new String[n];
    for (int i = 0; i < n; i++) out[i] = tok.get(i * 2 + 1);
    return out;
  }

  static public int jfind(String s, String in) {
    return jfind(javaTok(s), in);
  }

  static public int jfind(List<String> tok, String in) {
    return jfind(tok, 1, in);
  }

  static public int jfind(List<String> tok, int startIdx, String in) {
    return jfind(tok, startIdx, in, null);
  }

  static public int jfind(List<String> tok, String in, Object condition) {
    return jfind(tok, 1, in, condition);
  }

  static public int jfind(List<String> tok, int startIdx, String in, Object condition) {
    return jfind(tok, startIdx, javaTokForJFind_array(in), condition);
  }

  static public int jfind(List<String> tok, List<String> tokin) {
    return jfind(tok, 1, tokin);
  }

  static public int jfind(List<String> tok, int startIdx, List<String> tokin) {
    return jfind(tok, startIdx, tokin, null);
  }

  static public int jfind(List<String> tok, int startIdx, String[] tokinC, Object condition) {
    return findCodeTokens(tok, startIdx, false, tokinC, condition);
  }

  static public int jfind(List<String> tok, int startIdx, List<String> tokin, Object condition) {
    return jfind(tok, startIdx, codeTokensAsStringArray(tokin), condition);
  }

  static public List<String> jfind_preprocess(List<String> tok) {
    for (String type : litlist("quoted", "id", "int")) replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">"));
    replaceSublist(tok, ll("\\", "", "*"), ll("\\*"));
    return tok;
  }

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

  static public boolean isQuoted(String s) {
    if (isNormalQuoted(s))
      return true;
    return isMultilineQuoted(s);
  }

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

  static public 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 public boolean checkTokCondition(Object condition, List<String> tok, int i) {
    if (condition instanceof TokCondition)
      return ((TokCondition) condition).get(tok, i);
    return checkCondition(condition, tok, i);
  }

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

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

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

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

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

  static public <A> boolean contains(Producer<A> p, A a) {
    if (p != null && a != null)
      while (true) {
        A x = p.next();
        if (x == null)
          break;
        if (eq(x, a))
          return true;
      }
    return false;
  }

  static public <A> void replaceCollection(Collection<A> dest, Collection<A> src) {
    if (dest == src)
      return;
    dest.clear();
    dest.addAll(src);
  }

  static public String joinSubList(List<String> l, int i, int j) {
    return join(subList(l, i, j));
  }

  static public String joinSubList(List<String> l, int i) {
    return join(subList(l, i));
  }

  static public void replaceListPart(List l, int i, int j, List l2) {
    replaceSublist(l, i, j, l2);
  }

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

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

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

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

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

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

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

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

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

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

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

  static public boolean hasLettersAllUpperCase(String s) {
    return hasLetters(s) && !containsLowerCase(s);
  }

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

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

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

  static public String intToHex_flexLength(int i) {
    return Integer.toHexString(i);
  }

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

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

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

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

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

  static public boolean isInstance(Class type, Object arg) {
    return type.isInstance(arg);
  }

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

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

  static public String snippetImageURL(String snippetID, String contentType) {
    if (snippetID == null || isURL(snippetID))
      return snippetID;
    long id = parseSnippetID(snippetID);
    String url;
    if (isImageServerSnippet(id))
      url = imageServerLink(id);
    else
      url = "https://botcompany.de/img/" + id;
    return url;
  }

  static public int loadPage_defaultTimeout = 60000;

  static public ThreadLocal<String> loadPage_charset = new ThreadLocal();

  static public boolean loadPage_allowGzip = true, loadPage_debug;

  static public boolean loadPage_anonymous = false;

  static public int loadPage_verboseness = 100000;

  static public int loadPage_retries = 1;

  static public ThreadLocal<Boolean> loadPage_silent = new ThreadLocal();

  static volatile public int loadPage_forcedTimeout;

  static public ThreadLocal<Integer> loadPage_forcedTimeout_byThread = new ThreadLocal();

  static public ThreadLocal<Map<String, List<String>>> loadPage_responseHeaders = new ThreadLocal();

  static public ThreadLocal<Map<String, String>> loadPage_extraHeaders = new ThreadLocal();

  static public ThreadLocal<Long> loadPage_sizeLimit = new ThreadLocal();

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

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

  static public String loadPage_preprocess(String url) {
    if (url.startsWith("tb/"))
      url = tb_mainServer() + "/" + url;
    if (url.indexOf("://") < 0)
      url = "http://" + url;
    return url;
  }

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

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

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

  static public String loadPage(URLConnection con, URL url, boolean addHeaders) throws IOException {
    Map<String, String> extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders);
    Long limit = optPar(loadPage_sizeLimit);
    if (addHeaders)
      try {
        if (!loadPage_anonymous)
          setHeaders(con);
        if (loadPage_allowGzip)
          con.setRequestProperty("Accept-Encoding", "gzip");
        con.setRequestProperty("X-No-Cookies", "1");
        for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key));
      } catch (Throwable e) {
      }
    vm_generalSubMap("URLConnection per thread").put(currentThread(), con);
    loadPage_responseHeaders.set(con.getHeaderFields());
    InputStream in = null;
    try {
      in = urlConnection_getInputStream(con);
      if (loadPage_debug)
        print("Put stream in map: " + currentThread());
      String contentType = con.getContentType();
      if (contentType == null) {
        throw new IOException("Page could not be read: " + hideCredentials(url));
      }
      String charset = loadPage_charset == null ? null : loadPage_charset.get();
      if (charset == null)
        charset = loadPage_guessCharset(contentType);
      if ("gzip".equals(con.getContentEncoding())) {
        if (loadPage_debug)
          print("loadPage: Using gzip.");
        in = newGZIPInputStream(in);
      }
      Reader r;
      try {
        r = new InputStreamReader(in, unquote(charset));
      } catch (UnsupportedEncodingException e) {
        print(toHex(utf8(charset)));
        throw e;
      }
      boolean silent = isTrue(loadPage_silent.get());
      StringBuilder buf = new StringBuilder();
      int n = 0;
      while (limit == null || n < limit) {
        ping();
        int ch = r.read();
        if (ch < 0)
          break;
        buf.append((char) ch);
        ++n;
        if (!silent && (n % loadPage_verboseness) == 0)
          print("  " + n + " chars read");
      }
      return buf.toString();
    } finally {
      if (loadPage_debug)
        print("loadPage done");
      vm_generalSubMap("URLConnection per thread").remove(currentThread());
      if (in != null)
        in.close();
    }
  }

  static public String loadPage_guessCharset(String contentType) {
    Matcher m = regexpMatcher("text/[a-z]+;\\s*charset=([^\\s]+)\\s*", contentType);
    String match = m.matches() ? m.group(1) : null;
    if (loadPage_debug)
      print("loadPage: contentType=" + contentType + ", match: " + match);
    return or(match, "UTF-8");
  }

  static public URLConnection loadPage_openConnection(URL url) {
    URLConnection con = openConnection(url);
    int timeout = toInt(loadPage_forcedTimeout_byThread.get());
    if (timeout == 0)
      timeout = loadPage_forcedTimeout;
    if (timeout != 0)
      setURLConnectionTimeouts(con, loadPage_forcedTimeout);
    else
      setURLConnectionDefaultTimeouts(con, loadPage_defaultTimeout);
    return con;
  }

  static public <A> A getAndClearThreadLocal(ThreadLocal<A> tl) {
    A a = tl.get();
    tl.set(null);
    return a;
  }

  static public void setHeaders(URLConnection con) throws IOException {
    String computerID = getComputerID_quick();
    if (computerID != null)
      try {
        con.setRequestProperty("X-ComputerID", computerID);
        con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version"));
      } catch (Throwable e) {
      }
  }

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

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

  static public <A> Set<A> keys(MultiSet<A> ms) {
    return ms.keySet();
  }

  static public <A> A println(A a) {
    return print(a);
  }

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

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

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

  static public FileOutputStream newFileOutputStream(String path, boolean append) throws IOException {
    mkdirsForFile(path);
    FileOutputStream f = new FileOutputStream(path, append);
    _registerIO(f, path, true);
    return f;
  }

  static public File javaxCachesDir_dir;

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

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

  static public String imageServerURL() {
    return or2(trim(loadTextFile(javaxDataDir("image-server-url.txt"))), "http://botcompany.de/images/raw/");
  }

  static volatile public boolean muricaPassword_pretendNotAuthed = false;

  static public String muricaPassword() {
    if (muricaPassword_pretendNotAuthed)
      return null;
    return trim(loadTextFile(muricaPasswordFile()));
  }

  static public String fileServerURL() {
    return "https://botcompany.de/files";
  }

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

  static public String loadTextFile(File f, String defaultContents) {
    return loadTextFile(f, defaultContents, "UTF-8");
  }

  static public String loadTextFile(File f, String defaultContents, String encoding) {
    try {
      checkFileNotTooBigToRead(f);
      if (f == null || !f.exists())
        return defaultContents;
      FileInputStream fileInputStream = new FileInputStream(f);
      InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, encoding);
      return loadTextFile(inputStreamReader);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

  static public String loadTextFile(Reader reader) throws IOException {
    StringBuilder builder = new StringBuilder();
    try {
      char[] buffer = new char[1024];
      int n;
      while (-1 != (n = reader.read(buffer))) builder.append(buffer, 0, n);
    } finally {
      reader.close();
    }
    return str(builder);
  }

  static public File getProgramFile(String progID, String fileName) {
    if (new File(fileName).isAbsolute())
      return new File(fileName);
    return new File(getProgramDir(progID), fileName);
  }

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

  public static File mkdirsFor(File file) {
    return mkdirsForFile(file);
  }

  static public void copyStreamWithPrints(InputStream in, OutputStream out, String pat) {
    try {
      byte[] buf = new byte[65536];
      int total = 0;
      while (true) {
        int n = in.read(buf);
        if (n <= 0)
          return;
        out.write(buf, 0, n);
        if ((total + n) / 100000 > total / 100000)
          print(pat.replace("{*}", str(roundDownTo(100000, total))));
        total += n;
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void renameFile_assertTrue(File a, File b) {
    try {
      if (!a.exists())
        throw fail("Source file not found: " + f2s(a));
      if (b.exists())
        throw fail("Target file exists: " + f2s(b));
      mkdirsForFile(b);
      if (!a.renameTo(b))
        throw fail("Can't rename " + f2s(a) + " to " + f2s(b));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public byte[] loadBinaryFilePart(File file, long start, long end) {
    try {
      RandomAccessFile raf = new RandomAccessFile(file, "r");
      int n = toInt(min(raf.length(), end - start));
      byte[] buffer = new byte[n];
      try {
        raf.seek(start);
        raf.readFully(buffer, 0, n);
        return buffer;
      } finally {
        raf.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

  static public String quickSubstring(String s, int i, int j) {
    if (i == j)
      return "";
    return s.substring(i, j);
  }

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

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

  static public 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 public String dropSuffix(String suffix, String s) {
    return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s;
  }

  static public <A> TreeMap<String, A> caseInsensitiveMap() {
    return new TreeMap(caseInsensitiveComparator());
  }

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

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

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

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

  static public int parseHexChar(char c) {
    if (c >= '0' && c <= '9')
      return charDiff(c, '0');
    if (c >= 'a' && c <= 'f')
      return charDiff(c, 'a') + 10;
    if (c >= 'A' && c <= 'F')
      return charDiff(c, 'A') + 10;
    return -1;
  }

  static public String assertIsIdentifier(String s) {
    if (!isIdentifier(s))
      throw fail("Not an identifier: " + quote(s));
    return s;
  }

  static public String assertIsIdentifier(String msg, String s) {
    if (!isIdentifier(s))
      throw fail(msg + " - Not an identifier: " + quote(s));
    return s;
  }

  static public Class getOuterClass(Class c) {
    return getOuterClass(c, null);
  }

  static public Class getOuterClass(Class c, Object classFinder) {
    try {
      String s = c.getName();
      int i = s.lastIndexOf('$');
      String name = substring(s, 0, i);
      if (classFinder != null)
        return (Class) callF(classFinder, name);
      return Class.forName(name);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public HashMap<String, Field> instanceFieldsMap(Object o) {
    Class c = o.getClass();
    HashMap<String, Field> map;
    synchronized (getOpt_cache) {
      map = getOpt_cache.get(c);
      if (map == null)
        map = getOpt_makeCache(c);
    }
    return map;
  }

  static public void smartSet(Field f, Object o, Object value) throws Exception {
    try {
      f.set(o, value);
    } catch (Exception e) {
      Class type = f.getType();
      if (type == int.class && value instanceof Long)
        value = ((Long) value).intValue();
      if (type == LinkedHashMap.class && value instanceof Map) {
        f.set(o, asLinkedHashMap((Map) value));
        return;
      }
      try {
        if (f.getType() == Concept.Ref.class) {
          f.set(o, ((Concept) o).new Ref((Concept) value));
          return;
        }
        if (o instanceof Concept.Ref) {
          f.set(o, ((Concept.Ref) o).get());
          return;
        }
      } catch (Throwable _e) {
      }
      throw e;
    }
  }

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

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

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

  static public Map<Class, Field[]> thisDollarOneFields_cache = newDangerousWeakHashMap();

  static public Field[] thisDollarOneFields(Class c) {
    synchronized (thisDollarOneFields_cache) {
      Field[] l = thisDollarOneFields_cache.get(c);
      if (l == null)
        thisDollarOneFields_cache.put(c, l = thisDollarOneFields_uncached(c));
      return l;
    }
  }

  static public Field[] thisDollarOneFields_uncached(Class c) {
    List<Field> fields = new ArrayList();
    do {
      for (Field f : c.getDeclaredFields()) if (f.getName().equals("this$1"))
        fields.add(makeAccessible(f));
      c = c.getSuperclass();
    } while (c != null);
    return toArray(new Field[l(fields)], fields);
  }

  static public Method fastIntern_method;

  static public String fastIntern(String s) {
    try {
      if (s == null)
        return null;
      if (fastIntern_method == null) {
        fastIntern_method = findMethodNamed(javax(), "internPerProgram");
        if (fastIntern_method == null)
          upgradeJavaXAndRestart();
      }
      return (String) fastIntern_method.invoke(null, s);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Map<Class, HashMap<String, Method>> callOpt_noArgs_cache = newDangerousWeakHashMap();

  static public Object callOpt_noArgs(Object o, String method) {
    try {
      if (o == null)
        return null;
      if (o instanceof Class)
        return callOpt(o, method);
      Class c = o.getClass();
      HashMap<String, Method> map;
      synchronized (callOpt_noArgs_cache) {
        map = callOpt_noArgs_cache.get(c);
        if (map == null)
          map = callOpt_noArgs_makeCache(c);
      }
      Method m = map.get(method);
      return m != null ? m.invoke(o) : null;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public HashMap<String, Method> callOpt_noArgs_makeCache(Class c) {
    HashMap<String, Method> map = new HashMap();
    Class _c = c;
    do {
      for (Method m : c.getDeclaredMethods()) if (m.getParameterTypes().length == 0 && !reflection_isForbiddenMethod(m)) {
        makeAccessible(m);
        String name = m.getName();
        if (!map.containsKey(name))
          map.put(name, m);
      }
      _c = _c.getSuperclass();
    } while (_c != null);
    callOpt_noArgs_cache.put(c, map);
    return map;
  }

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

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

  static public String[] match2(List<String> pat, List<String> tok) {
    int i = pat.indexOf("...");
    if (i < 0)
      return match2_match(pat, tok);
    pat = new ArrayList<String>(pat);
    pat.set(i, "*");
    while (pat.size() < tok.size()) {
      pat.add(i, "*");
      pat.add(i + 1, "");
    }
    return match2_match(pat, tok);
  }

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

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

  static public <A> A liftLast(List<A> l) {
    if (empty(l))
      return null;
    int i = l(l) - 1;
    A a = l.get(i);
    l.remove(i);
    return a;
  }

  static public <A> List<A> liftLast(int n, List<A> l) {
    int i = l(l) - n;
    List<A> part = cloneSubList(l, i);
    removeSubList(l, i);
    return part;
  }

  static public 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 public <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 public <A> List<A> repeat(int n, A a) {
    return repeat(a, n);
  }

  static public class getOpt_Map extends WeakHashMap {

    public getOpt_Map() {
      if (getOpt_special == null)
        getOpt_special = new HashMap();
      clear();
    }

    public void clear() {
      super.clear();
      put(Class.class, getOpt_special);
      put(String.class, getOpt_special);
    }
  }

  static final public Map<Class, HashMap<String, Field>> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map()));

  static public HashMap getOpt_special;

  static public Object getOpt_cached(Object o, String field) {
    try {
      if (o == null)
        return null;
      Class c = o.getClass();
      HashMap<String, Field> map;
      synchronized (getOpt_cache) {
        map = getOpt_cache.get(c);
        if (map == null)
          map = getOpt_makeCache(c);
      }
      if (map == getOpt_special) {
        if (o instanceof Class)
          return getOpt((Class) o, field);
        if (o instanceof Map)
          return ((Map) o).get(field);
      }
      Field f = map.get(field);
      if (f != null)
        return f.get(o);
      if (o instanceof DynamicObject)
        return mapGet2(((DynamicObject) o).fieldValues, field);
      return null;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public 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 public 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 public String replacePrefix(String prefix, String replacement, String s) {
    if (!startsWith(s, prefix))
      return s;
    return replacement + substring(s, l(prefix));
  }

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

  static public <A> List<A> replaceSublist(List<A> l, List<A> x, List<A> y) {
    if (x == null)
      return l;
    int i = 0;
    while (true) {
      i = indexOfSubList(l, x, i);
      if (i < 0)
        break;
      replaceSublist(l, i, i + l(x), y);
      i += l(y);
    }
    return l;
  }

  static public <A> List<A> replaceSublist(List<A> l, int fromIndex, int toIndex, List<A> y) {
    int n = y.size(), toIndex_new = fromIndex + n;
    if (toIndex_new < toIndex) {
      removeSubList(l, toIndex_new, toIndex);
      copyListPart(y, 0, l, fromIndex, n);
    } else {
      copyListPart(y, 0, l, fromIndex, toIndex - fromIndex);
      if (toIndex_new > toIndex)
        l.addAll(toIndex, subList(y, toIndex - fromIndex));
    }
    return l;
  }

  static public boolean isNormalQuoted(String s) {
    int l = l(s);
    if (!(l >= 2 && s.charAt(0) == '"' && lastChar(s) == '"'))
      return false;
    int j = 1;
    while (j < l) if (s.charAt(j) == '"')
      return j == l - 1;
    else if (s.charAt(j) == '\\' && j + 1 < l)
      j += 2;
    else
      ++j;
    return false;
  }

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

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

  static public boolean checkCondition(Object condition, Object... args) {
    return isTrue(callF(condition, args));
  }

  static public <A> boolean checkCondition(IF1<A, Boolean> condition, A arg) {
    return isTrue(callF(condition, arg));
  }

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

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

  static public Throwable getException(Runnable r) {
    try {
      callF(r);
      return null;
    } catch (Throwable e) {
      return e;
    }
  }

  static public Class<?> getClass(String name) {
    try {
      return Class.forName(name);
    } catch (ClassNotFoundException e) {
      return null;
    }
  }

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

  static public Class getClass(Object realm, String name) {
    try {
      try {
        return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
      } catch (ClassNotFoundException e) {
        return null;
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String classNameToVM(String name) {
    return name.replace(".", "$");
  }

  static public boolean hasLetters(String s) {
    for (int i = 0; i < s.length(); i++) if (Character.isLetter(s.charAt(i)))
      return true;
    return false;
  }

  static public boolean containsLowerCase(String s) {
    for (int i = 0; i < l(s); i++) if (isLowerCase(s.charAt(i)))
      return true;
    return false;
  }

  static public String imageServerLink(String md5OrID) {
    if (possibleMD5(md5OrID))
      return "https://botcompany.de/images/md5/" + md5OrID;
    return imageServerLink(parseSnippetID(md5OrID));
  }

  static public String imageServerLink(long id) {
    return "https://botcompany.de/images/" + id;
  }

  static public boolean networkAllowanceTest(String url) {
    return isAllowed("networkAllowanceTest", url);
  }

  static final public boolean loadPageThroughProxy_enabled = false;

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

  static public void sleepSeconds(double s) {
    if (s > 0)
      sleep(round(s * 1000));
  }

  static public <A> A printWithTime(A a) {
    return printWithTime("", a);
  }

  static public <A> A printWithTime(String s, A a) {
    print(hmsWithColons() + ": " + s, a);
    return a;
  }

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

  static public InputStream urlConnection_getInputStream(URLConnection con) throws IOException {
    UnknownHostException lastException = null;
    for (int _repeat_0 = 0; _repeat_0 < 2; _repeat_0++) {
      try {
        if (con instanceof HttpURLConnection)
          if (((HttpURLConnection) con).getResponseCode() == 500)
            throw new IOException(joinNemptiesWithColonSpace("Server code 500", tryToReadErrorStreamFromURLConnection(((HttpURLConnection) con))));
        return con.getInputStream();
      } catch (UnknownHostException e) {
        lastException = e;
        print("Retrying because of: " + e);
        continue;
      }
    }
    throw lastException;
  }

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

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

  static public String toHex(byte[] bytes) {
    return bytesToHex(bytes);
  }

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

  static public byte[] utf8(String s) {
    return toUtf8(s);
  }

  static public Matcher regexpMatcher(String pat, String s) {
    return compileRegexp(pat).matcher(unnull(s));
  }

  static public URLConnection setURLConnectionTimeouts(URLConnection con, long timeout) {
    con.setConnectTimeout(toInt(timeout));
    con.setReadTimeout(toInt(timeout));
    if (con.getConnectTimeout() != timeout || con.getReadTimeout() != timeout)
      print("Warning: Timeouts not set by JDK.");
    return con;
  }

  static public URLConnection setURLConnectionDefaultTimeouts(URLConnection con, long timeout) {
    if (con.getConnectTimeout() == 0) {
      con.setConnectTimeout(toInt(timeout));
      if (con.getConnectTimeout() != timeout)
        print("Warning: URL connect timeout not set by JDK.");
    }
    if (con.getReadTimeout() == 0) {
      con.setReadTimeout(toInt(timeout));
      if (con.getReadTimeout() != timeout)
        print("Warning: URL read timeout not set by JDK.");
    }
    return con;
  }

  static public String getComputerID_quick() {
    return computerID();
  }

  public static File mkdirsForFile(File file) {
    File dir = file.getParentFile();
    if (dir != null) {
      dir.mkdirs();
      if (!dir.isDirectory())
        if (dir.isFile())
          throw fail("Please delete the file " + f2s(dir) + " - it is supposed to be a directory!");
        else
          throw fail("Unknown IO exception during mkdirs of " + f2s(file));
    }
    return file;
  }

  public static String mkdirsForFile(String path) {
    mkdirsForFile(new File(path));
    return path;
  }

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

  static public String _userHome;

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

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

  static public String or2(String a, String b) {
    return nempty(a) ? a : b;
  }

  static public String or2(String a, String b, String c) {
    return or2(or2(a, b), c);
  }

  static public File javaxDataDir_dir;

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

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

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

  static public ThreadLocal<VF1<File>> checkFileNotTooBigToRead_tl = new ThreadLocal();

  static public void checkFileNotTooBigToRead(File f) {
    callF(checkFileNotTooBigToRead_tl.get(), f);
  }

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

  static public File getProgramDir(String snippetID) {
    return programDir(snippetID);
  }

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

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

  static public char lastChar(String s) {
    return empty(s) ? '\0' : s.charAt(l(s) - 1);
  }

  static public <A> A[] dropLast(A[] a) {
    return dropLast(a, 1);
  }

  static public <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 public <A> List<A> dropLast(List<A> l) {
    return subList(l, 0, l(l) - 1);
  }

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

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

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

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

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

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

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

  static public int charDiff(String a, char b) {
    return charDiff(stringToChar(a), b);
  }

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

  static public String baseClassName(Object o) {
    return baseClassName(getClassName(o));
  }

  static public String prependIfNempty(String prefix, String s) {
    return empty(s) ? unnull(s) : prefix + s;
  }

  static public Object[] toArray(Collection c) {
    return toObjectArray(c);
  }

  static public <A> A[] toArray(Iterable<A> c, Class<A> type) {
    A[] a = arrayOfType(l(c), type);
    if (a.length == 0)
      return a;
    asList(c).toArray(a);
    return a;
  }

  static public <A> A[] toArray(A[] array, Collection c) {
    if (array == null || c == null)
      return null;
    asList(c).toArray(array);
    return array;
  }

  static public Method findMethodNamed(Object obj, String method) {
    if (obj == null)
      return null;
    if (obj instanceof Class)
      return findMethodNamed((Class) obj, method);
    return findMethodNamed(obj.getClass(), method);
  }

  static public Method findMethodNamed(Class c, String method) {
    while (c != null) {
      for (Method m : c.getDeclaredMethods()) if (m.getName().equals(method)) {
        makeAccessible(m);
        return m;
      }
      c = c.getSuperclass();
    }
    return null;
  }

  static public void upgradeJavaXAndRestart() {
    run("#1001639");
    restart();
    sleep();
  }

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

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

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

  static public boolean equalsIgnoreCase(String a, String b) {
    return eqic(a, b);
  }

  static public boolean equalsIgnoreCase(char a, char b) {
    return eqic(a, b);
  }

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

  static public <A> List<A> cloneSubList(List<A> l, int startIndex) {
    return newSubList(l, startIndex);
  }

  static public void removeSubList(List l, int from, int to) {
    if (l != null)
      subList(l, from, to).clear();
  }

  static public void removeSubList(List l, int from) {
    if (l != null)
      subList(l, from).clear();
  }

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

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

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

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

  static public List<Pair> _registerDangerousWeakMap_preList;

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

  static public <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) {
      if (_registerDangerousWeakMap_preList == null)
        _registerDangerousWeakMap_preList = synchroList();
      _registerDangerousWeakMap_preList.add(pair(map, init));
      return map;
    }
    call(javax(), "_registerDangerousWeakMap", map, init);
    return map;
  }

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

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

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

  static public boolean isSubtypeOf(Class a, Class b) {
    return b.isAssignableFrom(a);
  }

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

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

  static public <A> int indexOfSubList(List<A> x, List<A> y) {
    return indexOfSubList(x, y, 0);
  }

  static public <A> int indexOfSubList(List<A> x, List<A> y, int i) {
    outer: for (; i + l(y) <= l(x); i++) {
      for (int j = 0; j < l(y); j++) if (neq(x.get(i + j), y.get(j)))
        continue outer;
      return i;
    }
    return -1;
  }

  static public <A> int indexOfSubList(List<A> x, A[] y, int i) {
    outer: for (; i + l(y) <= l(x); i++) {
      for (int j = 0; j < l(y); j++) if (neq(x.get(i + j), y[j]))
        continue outer;
      return i;
    }
    return -1;
  }

  static public <A, B extends A> void copyListPart(List<B> a, int i1, List<A> b, int i2, int n) {
    if (a == null || b == null)
      return;
    for (int i = 0; i < n; i++) b.set(i2 + i, a.get(i1 + i));
  }

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

  static public boolean possibleMD5(String s) {
    return isMD5(s);
  }

  static volatile public Object isAllowed_function;

  static volatile public boolean isAllowed_all = true;

  static public boolean isAllowed(String askingMethod, Object... args) {
    Object f = vm_generalMap_get("isAllowed_function");
    if (f != null && !isTrue(callF(f, askingMethod, args)))
      return false;
    return isAllowed_all || isTrue(callF(isAllowed_function, askingMethod, args));
  }

  static volatile public boolean sleep_noSleep = false;

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

  static public void sleep() {
    try {
      if (sleep_noSleep)
        throw fail("nosleep");
      print("Sleeping.");
      sleepQuietly();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public long round(double d) {
    return Math.round(d);
  }

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

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

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

  static public String joinNemptiesWithColonSpace(String... strings) {
    return joinNempties(": ", strings);
  }

  static public String joinNemptiesWithColonSpace(Collection<String> strings) {
    return joinNempties(": ", strings);
  }

  static public String tryToReadErrorStreamFromURLConnection(URLConnection conn) {
    try {
      if (conn instanceof HttpURLConnection)
        return stream2string(((HttpURLConnection) conn).getErrorStream());
      return null;
    } catch (Throwable __e) {
      return null;
    }
  }

  static public int gzInputStream_defaultBufferSize = 65536;

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

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

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

  static public GZIPInputStream gzInputStream(InputStream in, int bufferSize) {
    try {
      return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static String bytesToHex(byte[] bytes) {
    return bytesToHex(bytes, 0, bytes.length);
  }

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

  static public byte[] toUtf8(String s) {
    try {
      return s.getBytes(utf8charset());
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

  static public 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 public String _computerID;

  static public Lock computerID_lock = lock();

  public static String computerID() {
    if (_computerID == null) {
      Lock __0 = computerID_lock;
      lock(__0);
      try {
        if (_computerID != null)
          return _computerID;
        File file = computerIDFile();
        _computerID = loadTextFile(file.getPath());
        if (_computerID == null) {
          _computerID = loadTextFile(userDir(".tinybrain/computer-id"));
          if (_computerID == null)
            _computerID = makeRandomID(12, new SecureRandom());
          saveTextFile(file, _computerID);
        }
      } finally {
        unlock(__0);
      }
    }
    return _computerID;
  }

  static public String actualUserHome_value;

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

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

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

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

  static public File javaxSecretDir_dir;

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

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

  static public File programDir_mine;

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

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

  static public File programDir(String snippetID, String subPath) {
    return new File(programDir(snippetID), subPath);
  }

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

  static public betterCIComparator_C betterCIComparator_instance;

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

  final static public 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) {
              return c1 - c2;
            }
          }
        }
      }
      return n1 - n2;
    }
  }

  static public char stringToChar(String s) {
    if (l(s) != 1)
      throw fail("bad stringToChar: " + s);
    return firstChar(s);
  }

  static public Class run(String progID, String... args) {
    Class main = hotwire(progID);
    callMain(main, args);
    return main;
  }

  static public void restart() {
    Object j = getJavaX();
    call(j, "cleanRestart", get(j, "fullArgs"));
  }

  static public TreeSet<String> toCaseInsensitiveSet_treeSet(Iterable<String> c) {
    if (isCISet(c))
      return (TreeSet) c;
    TreeSet<String> set = caseInsensitiveSet_treeSet();
    addAll(set, c);
    return set;
  }

  static public TreeSet<String> toCaseInsensitiveSet_treeSet(String... x) {
    TreeSet<String> set = caseInsensitiveSet_treeSet();
    addAll(set, x);
    return set;
  }

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

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

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

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

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

  static public boolean isMD5(String s) {
    return l(s) == 32 && isLowerHexString(s);
  }

  static public Object sleepQuietly_monitor = new Object();

  static public void sleepQuietly() {
    try {
      assertFalse(isAWTThread());
      synchronized (sleepQuietly_monitor) {
        sleepQuietly_monitor.wait();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public <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 public String joinNempties(String sep, String... strings) {
    return joinStrings(sep, strings);
  }

  static public String joinNempties(String sep, Collection<String> strings) {
    return joinStrings(sep, strings);
  }

  static public String stream2string(InputStream in) {
    return utf8streamToString(in);
  }

  static public <A> A _registerIOWrap(A wrapper, Object wrapped) {
    return wrapper;
  }

  static public Charset utf8charset_cache;

  static public Charset utf8charset() {
    if (utf8charset_cache == null)
      utf8charset_cache = utf8charset_load();
    return utf8charset_cache;
  }

  static public Charset utf8charset_load() {
    return Charset.forName("UTF-8");
  }

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

  static public File computerIDFile() {
    return javaxDataDir("Basic Info/computer-id.txt");
  }

  static public String makeRandomID(int length) {
    return makeRandomID(length, defaultRandomGenerator());
  }

  static public String makeRandomID(int length, Random random) {
    char[] id = new char[length];
    for (int i = 0; i < id.length; i++) id[i] = (char) ((int) 'a' + random.nextInt(26));
    return new String(id);
  }

  static public String makeRandomID(Random r, int length) {
    return makeRandomID(length, r);
  }

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

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

  static public boolean sameSnippetID(String a, String b) {
    if (!isSnippetID(a) || !isSnippetID(b))
      return false;
    return parseSnippetID(a) == parseSnippetID(b);
  }

  static volatile public String caseID_caseID;

  static public String caseID() {
    return caseID_caseID;
  }

  static public void caseID(String id) {
    caseID_caseID = id;
  }

  static public <A> A[] newObjectArrayOfSameType(A[] a, int n) {
    return (A[]) Array.newInstance(a.getClass().getComponentType(), n);
  }

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

  static public Class<?> hotwire(String src) {
    assertFalse(_inCore());
    Class j = getJavaX();
    if (isAndroid()) {
      synchronized (j) {
        List<File> libraries = new ArrayList<File>();
        File srcDir = (File) call(j, "transpileMain", src, libraries);
        if (srcDir == null)
          throw fail("transpileMain returned null (src=" + quote(src) + ")");
        Object androidContext = get(j, "androidContext");
        return (Class) call(j, "loadx2android", srcDir, src);
      }
    } else {
      Class c = (Class) (call(j, "hotwire", src));
      hotwire_copyOver(c);
      return c;
    }
  }

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

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

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

  static public <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 public <A, B extends A> boolean addAll(Collection<A> c, Collection<B> b) {
    return c != null && b != null && c.addAll(b);
  }

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

  static public <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 public boolean isLowerHexString(String s) {
    for (int i = 0; i < l(s); i++) {
      char c = s.charAt(i);
      if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
      } else
        return false;
    }
    return true;
  }

  static public void assertFalse(Object o) {
    if (!(eq(o, false)))
      throw fail(str(o));
  }

  static public boolean assertFalse(boolean b) {
    if (b)
      throw fail("oops");
    return b;
  }

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

  static public String joinStrings(String sep, String... strings) {
    return joinStrings(sep, Arrays.asList(strings));
  }

  static public String joinStrings(String sep, Collection<String> strings) {
    StringBuilder buf = new StringBuilder();
    for (String s : unnull(strings)) if (nempty(s)) {
      if (nempty(buf))
        buf.append(sep);
      buf.append(s);
    }
    return str(buf);
  }

  static public String utf8streamToString(InputStream in) {
    return readerToString(utf8bufferedReader(in));
  }

  static public Random defaultRandomGenerator() {
    return ThreadLocalRandom.current();
  }

  static public List<CriticalAction> beginCriticalAction_inFlight = synchroList();

  static public class CriticalAction {

    public String description;

    public CriticalAction() {
    }

    public CriticalAction(String description) {
      this.description = description;
    }

    public void done() {
      beginCriticalAction_inFlight.remove(this);
    }
  }

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

  static public void cleanMeUp_beginCriticalAction() {
    int n = 0;
    while (nempty(beginCriticalAction_inFlight)) {
      int m = l(beginCriticalAction_inFlight);
      if (m != n) {
        n = m;
        try {
          print("Waiting for " + n2(n, "critical actions") + ": " + join(", ", collect(beginCriticalAction_inFlight, "description")));
        } catch (Throwable __e) {
          _handleException(__e);
        }
      }
      sleepInCleanUp(10);
    }
  }

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

  static public boolean _inCore() {
    return false;
  }

  static public List hotwire_copyOver_after = synchroList();

  static public void hotwire_copyOver(Class c) {
    for (String field : ll("print_log", "print_silent", "androidContext", "_userHome")) setOptIfNotNull(c, field, getOpt(mc(), field));
    setOptIfNotNull(c, "mainBot", getMainBot());
    setOpt(c, "creator_class", new WeakReference(mc()));
    pcallFAll(hotwire_copyOver_after, c);
  }

  static public String readerToString(Reader r) {
    try {
      try {
        StringBuilder buf = new StringBuilder();
        int n = 0;
        while (true) {
          int ch = r.read();
          if (ch < 0)
            break;
          buf.append((char) ch);
          ++n;
        }
        return buf.toString();
      } finally {
        r.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public BufferedReader utf8bufferedReader(InputStream in) {
    try {
      return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

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

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

  static public void setOptIfNotNull(Object o, String field, Object value) {
    if (value != null)
      setOpt(o, field, value);
  }

  static public Object mainBot;

  static public Object getMainBot() {
    return mainBot;
  }

  static public BufferedReader bufferedReader(Reader r) {
    return bufferedReader(r, 8192);
  }

  static public BufferedReader bufferedReader(Reader r, int bufSize) {
    return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r, bufSize), r);
  }

  static public FileInputStream newFileInputStream(File path) throws IOException {
    return newFileInputStream(path.getPath());
  }

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

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

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

  final static public class _MethodCache {

    final public Class c;

    final public HashMap<String, List<Method>> cache = new HashMap();

    public _MethodCache(Class c) {
      this.c = c;
      _init();
    }

    public 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();
      }
      for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if (m.isDefault() && !reflection_isForbiddenMethod(m))
        multiMapPut(cache, m.getName(), makeAccessible(m));
    }

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

    public 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 public class JSection extends SingleComponentPanel {

    public JSection(Component c) {
      super(c);
    }

    public String getTitle() {
      Border border = getBorder();
      if (border instanceof TitledBorder)
        return ((TitledBorder) border).getTitle();
      return null;
    }
  }

  static public class Var<A> implements IVar<A> {

    public Var() {
    }

    public Var(A v) {
      this.v = v;
    }

    public A v;

    public synchronized void set(A a) {
      if (v != a) {
        v = a;
        notifyAll();
      }
    }

    public synchronized A get() {
      return v;
    }

    public synchronized boolean has() {
      return v != null;
    }

    public synchronized void clear() {
      v = null;
    }

    public String toString() {
      return str(get());
    }
  }

  abstract static public class AIStrategy<A> implements Steppable {

    public F1<A, Double> submit;

    public AIStrategy() {
    }

    public AIStrategy(F1<A, Double> submit) {
      this.submit = submit;
    }

    public int round;

    public Best<A> best = new Best();

    public boolean verbose = false;

    public void updateBest(A guess, double score) {
      best.put(guess, score);
    }

    public double submit(A guess) {
      if (guess == null)
        return minusInfinity();
      double score = callF(submit, guess);
      best.put(guess, score);
      return score;
    }
  }

  static abstract public class TokCondition {

    abstract public boolean get(List<String> tok, int i);
  }

  static abstract public class LiveValue<A> {

    abstract public Class<A> getType();

    abstract public A get();

    abstract public void onChange(Runnable l);

    abstract public void removeOnChangeListener(Runnable l);

    public void onChangeAndNow(Runnable l) {
      onChange(l);
      callF(l);
    }
  }

  static public class Dyn_FieldWatcher {

    public DynModule module;

    public String field;

    public Object value;

    public Runnable action;

    transient public IF1<Object, Object> cloneValue;

    public Object cloneValue(Object o) {
      return cloneValue != null ? cloneValue.get(o) : cloneValue_base(o);
    }

    final public Object cloneValue_fallback(IF1<Object, Object> _f, Object o) {
      return _f != null ? _f.get(o) : cloneValue_base(o);
    }

    public Object cloneValue_base(Object o) {
      return o;
    }

    public Dyn_FieldWatcher(DynModule module, String field, Runnable action) {
      this(module, field, action, null);
    }

    public Dyn_FieldWatcher(DynModule module, String field, Runnable action, IF1 cloneValue) {
      this.cloneValue = cloneValue;
      this.action = action;
      this.field = field;
      this.module = module;
      value = cloneValue(get(module, field));
      module.onChange(new Runnable() {

        public void run() {
          try {
            check();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "check();";
        }
      });
      module.onFieldChange(new VF1<String>() {

        public void get(String f) {
          try {
            if (eq(f, field))
              check();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (eq(f, field))\r\n        check();";
        }
      });
    }

    public void check() {
      Object newValue = cloneValue(get(module, field));
      if (eq(value, newValue))
        return;
      value = newValue;
      dm_q(module, action);
    }
  }

  static public class RightAlignedLine extends JPanel {

    public RightAlignedLine(Component... components) {
      setLayout(LetterLayout.rightAlignedRow());
      for (Component component : components) add(component);
    }

    public void add(String text) {
      add(new JLabel(text));
    }
  }

  static public class MRUCache<A, B> extends LinkedHashMap<A, B> {

    public int maxSize = 10;

    public MRUCache() {
    }

    public MRUCache(int maxSize) {
      this.maxSize = maxSize;
    }

    public boolean removeEldestEntry(Map.Entry eldest) {
      return size() > maxSize;
    }

    public Object _serialize() {
      return ll(maxSize, cloneLinkedHashMap(this));
    }

    static public MRUCache _deserialize(List l) {
      MRUCache m = new MRUCache();
      m.maxSize = (int) first(l);
      m.putAll((LinkedHashMap) second(l));
      return m;
    }
  }

  static public class SimpleLiveValue<A> extends LiveValue<A> {

    public Class<A> type;

    volatile public A value;

    transient public List onChange = synchroList();

    public SimpleLiveValue(Class<A> type) {
      this.type = type;
    }

    public SimpleLiveValue(Class<A> type, A value) {
      this.value = value;
      this.type = type;
    }

    public Class<A> getType() {
      return type;
    }

    public A get() {
      return value;
    }

    public void onChange(Runnable l) {
      onChange.add(l);
    }

    public void onChangeAndNow(Runnable l) {
      onChange(l);
      callF(l);
    }

    public void removeOnChangeListener(Runnable l) {
      onChange.remove(l);
    }

    public void fireChanged() {
      pcallFAll(onChange);
    }

    public void set(A a) {
      if (neq(value, a)) {
        value = a;
        fireChanged();
      }
    }
  }

  static public class BackgroundPlus<A> implements RenderableWithHints {

    public RGB background;

    public List<A> things = new ArrayList();

    public BackgroundPlus() {
    }

    public BackgroundPlus(RGB background, A... things) {
      this.things = asList(things);
      this.background = background;
    }

    public BackgroundPlus(RGB background, List<A> things) {
      this.things = things;
      this.background = background;
    }

    public BackgroundPlus(Color background, A... things) {
      this.background = new RGB(background);
      this.things = asList(things);
    }

    public void renderOn(Graphics2D g, int w, int h) {
      fillRect(g, 0, 0, w, h, toColor(background));
      for (A a : things) ((Renderable) a).renderOn(g, w, h);
    }

    public void renderHints(Graphics2D g, int w, int h) {
      renderOn(g, w, h);
      for (A a : things) if (a instanceof RenderableWithHints)
        ((RenderableWithHints) a).renderHints(g, w, h);
    }
  }

  static public interface Renderable {

    public void renderOn(Graphics2D g, int w, int h);
  }

  static public interface IFieldsToList {

    public Object[] _fieldsToList();
  }

  static public interface IF2<A, B, C> {

    public C get(A a, B b);
  }

  static public interface Producer<A> {

    public A next();
  }

  static public class AIStrategy_Racer_RandomWithVary<A> extends AIStrategy<A> {

    public F0<A> random;

    public F1<A, A> vary;

    public int discardEvery = 5000;

    public AIStrategy_RandomWithVariation<A> leader, overtaker;

    public Best<A> leadersBest = new Best();

    public int roundsSinceChange;

    public boolean step() {
      go();
      return false;
    }

    public AIStrategy_RandomWithVariation newAI() {
      return copyFields(this, new AIStrategy_RandomWithVariation(), "random", "vary");
    }

    public void go() {
      if (tossACoin()) {
        if (leader == null)
          leader = newAI();
        A guess = leader.guess();
        if (guess == null)
          return;
        double score = submit(guess);
        leader.updateBest(guess, score);
        leadersBest.put(guess, score);
      } else {
        if (overtaker == null)
          overtaker = newAI();
        A guess = overtaker.guess();
        if (guess == null)
          return;
        double score = submit(guess);
        overtaker.updateBest(guess, score);
        if (score > leadersBest.score()) {
          if (verbose)
            print("Overtake at " + formatScore(overtaker.best.score()) + " vs " + formatScore(leadersBest.score()));
          leader = overtaker;
          overtaker = null;
          roundsSinceChange = 0;
        } else if (roundsSinceChange++ >= discardEvery) {
          if (verbose)
            print("Discarding overtaker at " + formatScore(overtaker.best.score()) + " vs " + formatScore(leadersBest.score()));
          overtaker = null;
          roundsSinceChange = 0;
        }
      }
    }
  }

  static public interface IResourceLoader {

    public String loadSnippet(String snippetID);

    public String getTranspiled(String snippetID);

    public int getSnippetType(String snippetID);

    public String getSnippetTitle(String snippetID);

    public File loadLibrary(String snippetID);

    default public File pathToJavaXJar() {
      return pathToJavaxJar_noResourceLoader();
    }

    default public File getSnippetJar(String snippetID, String transpiledSrc) {
      return null;
    }
  }

  static public interface Steppable {

    public boolean step();
  }

  static public class proxy_InvocationHandler implements InvocationHandler {

    public Object target;

    public proxy_InvocationHandler() {
    }

    public proxy_InvocationHandler(Object target) {
      this.target = target;
    }

    public Object invoke(Object proxy, Method method, Object[] args) {
      return call(target, method.getName(), unnull(args));
    }
  }

  static public class Best<A> {

    public A best;

    public double score;

    public boolean verboseNewBest, replaceIfSameScore;

    transient public Object onChange;

    transient public Object stringifier;

    synchronized public boolean isNewBest(double score) {
      return best == null || !isNaN(score) && (replaceIfSameScore ? score >= this.score : score > this.score);
    }

    synchronized public double bestScore() {
      return best == null ? minusInfinity() : score;
    }

    public double score() {
      return bestScore();
    }

    public double getScore() {
      return bestScore();
    }

    synchronized public float floatScoreOr(float defaultValue) {
      return best == null ? defaultValue : (float) score;
    }

    public boolean put(Pair<? extends A, Double> p) {
      return p != null && put(p.a, p.b);
    }

    public boolean put(Best<? extends A> b) {
      return b != null && put(b.get(), b.score);
    }

    public boolean put(A a, double score) {
      ping();
      boolean change = false;
      if (a != null)
        synchronized (this) {
          if (isNewBest(score)) {
            best = a;
            this.score = score;
            change = true;
          }
        }
      if (change) {
        if (verboseNewBest)
          print("New best! " + this);
        pcallF(onChange);
      }
      return change;
    }

    synchronized public A get() {
      return best;
    }

    synchronized public boolean has() {
      return best != null;
    }

    synchronized public Pair<A, Double> pair() {
      return main.pair(best, bestScore());
    }

    synchronized public A getIfScoreAbove(double x) {
      return score() >= x ? best : null;
    }

    public String toString() {
      return "Score " + formatDouble_significant2(score, 4) + ": " + callStringifier(stringifier, best);
    }

    public boolean putAndPrintIfNewBest(A a, double score) {
      if (!put(a, score))
        return false;
      {
        print(this);
        return true;
      }
    }

    synchronized public void clear() {
      best = null;
      score = 0;
    }
  }

  static public class FixedRateTimer extends java.util.Timer {

    public FixedRateTimer() {
      this(false);
    }

    public FixedRateTimer(boolean daemon) {
      this(defaultTimerName(), daemon);
    }

    public FixedRateTimer(String name) {
      this(name, false);
    }

    public FixedRateTimer(String name, boolean daemon) {
      super(name, daemon);
      _registerTimer(this);
    }

    public List<Entry> entries = synchroList();

    static public class Entry implements IFieldsToList {

      public TimerTask task;

      public long firstTime;

      public long period;

      public Entry() {
      }

      public Entry(TimerTask task, long firstTime, long period) {
        this.period = period;
        this.firstTime = firstTime;
        this.task = task;
      }

      public String toString() {
        return shortClassName(this) + "(" + task + ", " + firstTime + ", " + period + ")";
      }

      public Object[] _fieldsToList() {
        return new Object[] { task, firstTime, period };
      }
    }

    public void scheduleAtFixedRate(TimerTask task, long delay, long period) {
      entries.add(new Entry(task, now() + delay, period));
      super.scheduleAtFixedRate(task, delay, period);
    }

    public void cancel() {
      entries.clear();
      super.cancel();
    }

    public int purge() {
      entries.clear();
      return super.purge();
    }

    public FixedRateTimer changeRate(int newPeriod) {
      Object r = ((SmartTimerTask) first(entries).task).r;
      cancel();
      return doEvery(newPeriod, r);
    }
  }

  static public interface IVar<A> extends IF0<A> {

    public void set(A a);

    public A get();

    default public boolean has() {
      return get() != null;
    }

    default public void clear() {
      set(null);
    }
  }

  static public class BoxWithColor implements RenderableWithHints {

    public Pt a, b;

    public RGB color;

    public BoxWithColor() {
    }

    public BoxWithColor(Pt a, Pt b, RGB color) {
      this.color = color;
      this.b = b;
      this.a = a;
    }

    public void renderOn(Graphics2D g, int w, int h) {
      int x1 = min(a.x, b.x), y1 = min(a.y, b.y);
      int x2 = max(a.x, b.x), y2 = max(a.y, b.y);
      fillRect(g, x1, y1, x2 - x1 + 1, y2 - y1 + 1, toColor(color));
    }

    public void renderHints(Graphics2D g, int w, int h) {
      int x1 = min(a.x, b.x), y1 = min(a.y, b.y);
      int x2 = max(a.x, b.x), y2 = max(a.y, b.y);
      drawRect(g, x1, y1, x2 - x1 + 1, y2 - y1 + 1, hintColor());
    }
  }

  static public class Pair<A, B> implements Comparable<Pair<A, B>> {

    public A a;

    public B b;

    public Pair() {
    }

    public 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 public class AIStrategy_RandomWithVariation<A> extends AIStrategy<A> {

    public F0<A> random;

    public F1<A, A> vary;

    public boolean step() {
      go();
      return false;
    }

    public void go() {
      submit(guess());
    }

    public A guess() {
      A a = null;
      if (odd(round++) && vary != null && best.has())
        a = callF(vary, best.get());
      if (a == null)
        a = callF(random);
      return a;
    }
  }

  static public interface RenderableWithHints extends Renderable {

    public void renderHints(Graphics2D g, int w, int h);
  }

  static public class LetterLayout implements LayoutManager {

    public String[] lines;

    public Map<String, Component> map = new TreeMap<String, Component>();

    public RC[] rows;

    public RC[] cols;

    public Cell[][] cells;

    public int spacingX = 10, spacingY = 10;

    public int insetTop, insetBottom, insetLeft, insetRight;

    public int template;

    public boolean formWideLeftSide, formWideRightSide;

    static final public int STALACTITE = 1, LEFT_ALIGNED_ROW = 2, CENTERED_ROW = 3, FORM = 4, RIGHT_ALIGNED_ROW = 5;

    public boolean debug = false;

    public void setLeftBorder(int border) {
      insetLeft = border;
    }

    public void setRightBorder(int border) {
      insetRight = border;
    }

    public static JComponent withBorder(JComponent component, int border) {
      JPanel panel = new JPanel(new LetterLayout("C").setBorder(border));
      panel.add("C", component);
      return panel;
    }

    public static JPanel panel(String... lines) {
      return new JPanel(new LetterLayout(lines));
    }

    public static JPanel stalactitePanel() {
      return new JPanel(stalactite());
    }

    static public class DummyComponent extends JComponent {
    }

    static public class Cell {

      public boolean aux = false;

      public int minWidth, minHeight;

      public Component component;

      public int colspan, rowspan;

      public double weightX, weightY;
    }

    static public class RC {

      public int min;

      public double weightSum;

      public int start;

      public int minEnd;
    }

    public LetterLayout(int template) {
      this.template = template;
    }

    public LetterLayout(String... lines) {
      this.lines = lines;
    }

    public void removeLayoutComponent(Component component) {
      map.values().remove(component);
    }

    public void layoutContainer(Container container) {
      prepareLayout(container);
      if (debug)
        System.out.println("Container size: " + container.getSize());
      Insets insets = getInsets(container);
      for (int r = 0; r < rows.length; r++) {
        for (int i = 0; i < cols.length; ) {
          Cell cell = cells[i][r];
          if (cell.aux)
            ++i;
          else {
            if (cell.component != null) {
              int x1 = cols[i].start;
              int y1 = rows[r].start;
              int x2 = i + cell.colspan < cols.length ? cols[i + cell.colspan].start - spacingX : container.getWidth() - insets.right;
              int y2 = r + cell.rowspan < rows.length ? rows[r + cell.rowspan].start - spacingY : container.getHeight() - insets.bottom;
              if (debug)
                System.out.println("Layouting (" + i + ", " + r + ", " + cell.component.getClass().getName() + "): " + x1 + " " + y1 + " " + x2 + " " + y2);
              cell.component.setBounds(x1, y1, x2 - x1, y2 - y1);
            }
            i += cells[i][r].colspan;
          }
        }
      }
    }

    final public void prepareLayout(Container container) {
      applyTemplate(container);
      int numRows = lines.length, numCols = lines[0].length();
      for (int i = 1; i < numRows; i++) if (lines[i].length() != numCols)
        throw new IllegalArgumentException("Lines have varying length");
      cells = new Cell[numCols][numRows];
      rows = new RC[numRows];
      cols = new RC[numCols];
      for (int r = 0; r < numRows; r++) rows[r] = new RC();
      for (int i = 0; i < numCols; i++) cols[i] = new RC();
      for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r] = new Cell();
      for (int r = 0; r < numRows; r++) {
        String line = lines[r];
        for (int i = 0; i < numCols; ) {
          Cell cell = cells[i][r];
          if (cell.aux) {
            ++i;
            continue;
          }
          char ch = line.charAt(i);
          int iNext = i;
          do ++iNext; while (iNext < numCols && ch == line.charAt(iNext));
          int rNext = r;
          do ++rNext; while (rNext < numRows && ch == lines[rNext].charAt(i));
          cell.weightX = numCols == 1 || iNext > i + 1 ? 1.0 : 0.0;
          cell.weightY = numRows == 1 || rNext > r + 1 ? 1.0 : 0.0;
          Component c = map.get(String.valueOf(ch));
          cell.component = c;
          if (c != null) {
            cell.minWidth = c.getMinimumSize().width + spacingX;
            cell.minHeight = getMinimumHeight(c) + spacingY;
          }
          cell.colspan = iNext - i;
          cell.rowspan = rNext - r;
          if (cell.colspan == 1)
            cols[i].min = Math.max(cols[i].min, cell.minWidth);
          if (cell.rowspan == 1)
            rows[r].min = Math.max(rows[r].min, cell.minHeight);
          for (int r2 = r; r2 < rNext; r2++) for (int i2 = i; i2 < iNext; i2++) if (r2 != r || i2 != i)
            cells[i2][r2].aux = true;
          i = iNext;
        }
      }
      while (true) {
        for (int i = 0; i < numCols; i++) {
          int minStart = i == 0 ? 0 : cols[i - 1].minEnd;
          double weightStart = i == 0 ? 0.0 : cols[i - 1].weightSum;
          for (int r = 0; r < numRows; r++) {
            Cell cell = cells[i][r];
            if (!cell.aux) {
              RC rc = cols[i + cell.colspan - 1];
              rc.minEnd = Math.max(rc.minEnd, minStart + cell.minWidth);
              rc.weightSum = Math.max(rc.weightSum, weightStart + cell.weightX);
            }
          }
        }
        for (int r = 0; r < numRows; r++) {
          int minStart = r == 0 ? 0 : rows[r - 1].minEnd;
          double weightStart = r == 0 ? 0.0 : rows[r - 1].weightSum;
          for (int i = 0; i < numCols; i++) {
            Cell cell = cells[i][r];
            if (!cell.aux) {
              RC rc = rows[r + cell.rowspan - 1];
              rc.minEnd = Math.max(rc.minEnd, minStart + cell.minHeight);
              rc.weightSum = Math.max(rc.weightSum, weightStart + cell.weightY);
            }
          }
        }
        if (allWeightsZero(cols)) {
          for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r].weightX = 1.0;
          continue;
        }
        if (allWeightsZero(rows)) {
          for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r].weightY = 1.0;
          continue;
        }
        break;
      }
      Insets insets = getInsets(container);
      determineStarts(cols, insets.left, container.getWidth() - insets.left - insets.right + spacingX, spacingX);
      determineStarts(rows, insets.top, container.getHeight() - insets.top - insets.bottom + spacingY, spacingY);
    }

    final public boolean allWeightsZero(RC[] rcs) {
      for (int i = 0; i < rcs.length; i++) if (rcs[i].weightSum != 0.0)
        return false;
      return true;
    }

    static public int getMinimumHeight(Component c) {
      return c.getMinimumSize().height;
    }

    final public void applyTemplate(Container container) {
      if (template == STALACTITE) {
        Component[] components = container.getComponents();
        lines = new String[components.length + 2];
        map.clear();
        for (int i = 0; i < components.length; i++) {
          String s = String.valueOf(makeIndexChar(i));
          map.put(s, components[i]);
          lines[i] = s;
        }
        lines[components.length] = lines[components.length + 1] = " ";
      } else if (template == FORM) {
        Component[] components = container.getComponents();
        int numRows = components.length / 2;
        lines = new String[numRows + 2];
        map.clear();
        for (int row = 0; row < numRows; row++) {
          String lower = String.valueOf(makeIndexChar(row));
          String upper = String.valueOf(makeAlternateIndexChar(row));
          Component rightComponent = components[row * 2 + 1];
          if (rightComponent instanceof DummyComponent)
            upper = lower;
          lines[row] = (formWideLeftSide ? lower + lower : lower) + (formWideRightSide ? upper + upper : upper);
          map.put(lower, components[row * 2]);
          if (!(rightComponent instanceof DummyComponent))
            map.put(upper, rightComponent);
        }
        lines[numRows] = lines[numRows + 1] = (formWideLeftSide ? "  " : " ") + (formWideRightSide ? "  " : " ");
      } else if (template == LEFT_ALIGNED_ROW) {
        lines = new String[] { makeSingleRow(container) + RIGHT_CHAR + RIGHT_CHAR };
      } else if (template == CENTERED_ROW) {
        lines = new String[] { "" + LEFT_CHAR + LEFT_CHAR + makeSingleRow(container) + RIGHT_CHAR + RIGHT_CHAR };
      } else if (template == RIGHT_ALIGNED_ROW) {
        lines = new String[] { "" + LEFT_CHAR + LEFT_CHAR + makeSingleRow(container) };
      }
    }

    final public String makeSingleRow(Container container) {
      Component[] components = container.getComponents();
      StringBuffer buf = new StringBuffer();
      map.clear();
      for (int i = 0; i < components.length; i++) {
        String s = String.valueOf(makeAlternateIndexChar(i));
        map.put(s, components[i]);
        buf.append(s);
      }
      return buf.toString();
    }

    static public void determineStarts(RC[] rcs, int start, int totalSize, int spacing) {
      int minTotal = rcs[rcs.length - 1].minEnd;
      double weightSum = rcs[rcs.length - 1].weightSum;
      int spare = (int) ((totalSize - minTotal) / (weightSum == 0.0 ? 1.0 : weightSum));
      int x = start, minSum = 0;
      double prevWeightSum = 0.0;
      for (int i = 0; i < rcs.length; i++) {
        int width = rcs[i].minEnd - minSum + (int) ((rcs[i].weightSum - prevWeightSum) * spare) - spacing;
        rcs[i].start = x;
        x += width + spacing;
        prevWeightSum = rcs[i].weightSum;
        minSum = rcs[i].minEnd;
      }
    }

    public void addLayoutComponent(String s, Component component) {
      map.put(s, component);
    }

    public Dimension minimumLayoutSize(Container container) {
      prepareLayout(container);
      Insets insets = getInsets(container);
      Dimension result = new Dimension(insets.left + cols[cols.length - 1].minEnd + insets.right - spacingX, insets.top + rows[rows.length - 1].minEnd + insets.bottom - spacingY);
      return result;
    }

    final public Insets getInsets(Container container) {
      Insets insets = container.getInsets();
      return new Insets(insets.top + insetTop, insets.left + insetLeft, insets.bottom + insetBottom, insets.right + insetRight);
    }

    public Dimension preferredLayoutSize(Container container) {
      return minimumLayoutSize(container);
    }

    public LetterLayout setSpacing(int x, int y) {
      spacingX = x;
      spacingY = y;
      return this;
    }

    public LetterLayout setSpacing(int spacing) {
      return setSpacing(spacing, spacing);
    }

    public LetterLayout setBorder(int top, int left, int bottom, int right) {
      insetTop = top;
      insetLeft = left;
      insetBottom = bottom;
      insetRight = right;
      return this;
    }

    public LetterLayout setBorder(int inset) {
      return setBorder(inset, inset, inset, inset);
    }

    public LetterLayout setTopBorder(int inset) {
      insetTop = inset;
      return this;
    }

    public static LetterLayout stalactite() {
      return new LetterLayout(STALACTITE);
    }

    public static LetterLayout leftAlignedRow() {
      return new LetterLayout(LEFT_ALIGNED_ROW);
    }

    public static LetterLayout leftAlignedRow(int spacing) {
      return leftAlignedRow().setSpacing(spacing);
    }

    public static LetterLayout centeredRow() {
      return new LetterLayout(CENTERED_ROW);
    }

    public static LetterLayout rightAlignedRow() {
      return new LetterLayout(RIGHT_ALIGNED_ROW);
    }

    public static JPanel rightAlignedRowPanel(JComponent... components) {
      return makePanel(new LetterLayout(RIGHT_ALIGNED_ROW), components);
    }

    static public JPanel makePanel(LetterLayout letterLayout, JComponent[] components) {
      JPanel panel = new JPanel(letterLayout);
      for (JComponent component : components) {
        panel.add(component);
      }
      return panel;
    }

    public static LetterLayout form() {
      LetterLayout letterLayout = new LetterLayout(FORM);
      letterLayout.formWideLeftSide = true;
      letterLayout.formWideRightSide = true;
      return letterLayout;
    }

    public static LetterLayout formWideRightSide() {
      LetterLayout letterLayout = new LetterLayout(FORM);
      letterLayout.formWideRightSide = true;
      return letterLayout;
    }

    public static Component getDummyComponent() {
      return new DummyComponent();
    }

    public static JPanel newPanel(String... lines) {
      return new JPanel(new LetterLayout(lines));
    }

    public boolean isDebug() {
      return debug;
    }

    public void setDebug(boolean debug) {
      this.debug = debug;
    }

    public static char makeIndexChar(int idx) {
      return (char) ('a' + idx * 2);
    }

    public static char makeAlternateIndexChar(int idx) {
      return (char) ('b' + idx * 2);
    }

    public static char LEFT_CHAR = ',', RIGHT_CHAR = '.';

    public static void main(String[] args) {
      System.out.println((int) makeIndexChar(0));
      System.out.println((int) makeAlternateIndexChar(0));
      System.out.println((int) makeIndexChar(32000));
      System.out.println((int) makeAlternateIndexChar(32000));
      System.out.println((int) LEFT_CHAR);
      System.out.println((int) RIGHT_CHAR);
    }
  }

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

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

  static public <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 public Set<Class> allInterfacesImplementedBy(Class c) {
    if (c == null)
      return null;
    HashSet<Class> set = new HashSet();
    allInterfacesImplementedBy_find(c, set);
    return set;
  }

  static public 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 public Method findMethod(Object o, String method, Object... args) {
    return findMethod_cached(o, method, args);
  }

  static public 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 public 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 public 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 public 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 public Border getBorder(final JComponent c) {
    return c == null ? null : swing(new F0<Border>() {

      public Border get() {
        try {
          return c.getBorder();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret c.getBorder();";
      }
    });
  }

  static public double minusInfinity() {
    return negativeInfinity();
  }

  static public Q dm_q() {
    return dm_current_mandatory().q();
  }

  static public void dm_q(Runnable r) {
    dm_inQ(r);
  }

  static public void dm_q(DynModule module, Runnable r) {
    module.q().add(r);
  }

  static public <A> A dm_q(IF0<A> f) {
    return dm_evalInQ(if0ToF0(f));
  }

  static public void add(BitSet bs, int i) {
    bs.set(i);
  }

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

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

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

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

  static public <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 public <A> A second(A[] bla) {
    return bla == null || bla.length <= 1 ? null : bla[1];
  }

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

  static public <A> A second(Producer<A> p) {
    if (p == null)
      return null;
    if (p.next() == null)
      return null;
    return p.next();
  }

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

  static public <A, B> B second(Either<A, B> e) {
    return e == null ? null : e.bOpt();
  }

  static public void fillRect(BufferedImage image, int x, int y, int w, int h, Color color) {
    Graphics2D g = imageGraphics(image);
    fillRect(g, x, y, w, h, color);
    g.dispose();
  }

  static public void fillRect(Graphics g, int x, int y, int w, int h, Color color) {
    g.setColor(color);
    g.fillRect(x, y, w, h);
  }

  static public void fillRect(int x, int y, int w, int h, Color color) {
    fillRect(currentImage(), x, y, w, h, color);
  }

  static public void fillRect(Rect r, Color color) {
    fillRect(r.x, r.y, r.w, r.h, color);
  }

  static public void fillRect(BufferedImage image, Rect r, Color c) {
    if (r != null)
      fillRect(image, r.x, r.y, r.w, r.h, c);
  }

  static public void fillRect(Graphics g, Rect r, Color c) {
    if (r != null)
      fillRect(g, r.x, r.y, r.w, r.h, c);
  }

  static public <A> A copyFields(Object x, A y, String... fields) {
    if (empty(fields)) {
      Map<String, Object> map = objectToMap(x);
      for (String field : map.keySet()) setOpt(y, field, map.get(field));
    } else
      for (String field : fields) {
        Object o = getOpt(x, field);
        if (o != null)
          setOpt(y, field, o);
      }
    return y;
  }

  static public <A> A copyFields(Object x, A y, Collection<String> fields) {
    return copyFields(x, y, asStringArray(fields));
  }

  static public String formatScore(double score) {
    return formatDouble(score, 2) + " %";
  }

  static public File pathToJavaxJar() {
    IResourceLoader rl = vm_getResourceLoader();
    if (rl != null)
      return rl.pathToJavaXJar();
    return pathToJavaxJar_noResourceLoader();
  }

  static public File pathToJavaxJar_noResourceLoader() {
    try {
      int x = latestInstalledJavaX();
      File xfile = new File(userHome(), ".javax/x" + Math.max(x, 30) + ".jar");
      if (!xfile.isFile()) {
        print("Saving " + f2s(xfile));
        String url = x30JarServerURL();
        byte[] data = loadBinaryPage(url);
        if (data.length < 1000000)
          throw fail("Could not load " + url);
        saveBinaryFile(xfile.getPath(), data);
      }
      return xfile;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean isNaN(double d) {
    return Double.isNaN(d);
  }

  static public boolean isNaN(float f) {
    return Float.isNaN(f);
  }

  static public float score(Scored s) {
    return s == null ? 0 : s.score();
  }

  static public <A> float getScore(Scored<A> s) {
    return s == null ? 0 : s.score;
  }

  static public String formatDouble_significant2(double d, int digits) {
    try {
      digits -= max(0, Math.floor(Math.log10(abs(d)) + 1));
      return formatDouble(d, digits);
    } catch (Throwable _e) {
      print("Had number: " + d + ", digits: " + digits);
      throw rethrow(_e);
    }
  }

  static public String defaultTimerName_name;

  static public String defaultTimerName() {
    if (defaultTimerName_name == null)
      defaultTimerName_name = "A timer by " + programID();
    return defaultTimerName_name;
  }

  static public Set<java.util.Timer> _registerTimer_list = newWeakHashSet();

  static public void _registerTimer(java.util.Timer timer) {
    _registerTimer_list.add(timer);
  }

  static public void cleanMeUp__registerTimer() {
    cancelTimers(getAndClearList(_registerTimer_list));
  }

  static public <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 public 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 public 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 public 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 public void drawRect(BufferedImage image, int x, int y, int w, int h, Color color) {
    Graphics2D g = imageGraphics(image);
    drawRect(g, x, y, w, h, color);
    g.dispose();
  }

  static public void drawRect(Graphics2D g, int x, int y, int w, int h, Color color) {
    g.setColor(color);
    g.drawRect(x, y, w, h);
  }

  static public void drawRect(int x, int y, int w, int h, Color color) {
    drawRect(currentImage(), x, y, w, h, color);
  }

  static public void drawRect(Rect r, Color color) {
    drawRect(r.x, r.y, r.w, r.h, color);
  }

  static public void drawRect(BufferedImage image, Rect r, Color c) {
    if (r != null)
      drawRect(image, r.x, r.y, r.w, r.h, c);
  }

  static public Color hintColor() {
    return halfBlack();
  }

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

  static public 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 public double negativeInfinity() {
    return Double.NEGATIVE_INFINITY;
  }

  static public void dm_inQ(Runnable r) {
    dm_q().add(r);
  }

  static public <A> A dm_evalInQ(F0<A> f) {
    return dm_evalInQ(dm_current_mandatory(), f);
  }

  static public <A> A dm_evalInQ(IF0<A> f) {
    return dm_evalInQ(dm_current_mandatory(), if0ToF0(f));
  }

  static public <A> A dm_evalInQ(DynModule module, F0<A> f) {
    return evalInQ(module.q(), f);
  }

  static public <A> F0<A> if0ToF0(IF0<A> f) {
    return f == null ? null : new F0<A>() {

      public A get() {
        try {
          return f.get();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret f.get();";
      }
    };
  }

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

  static public char charAt(String s, int i) {
    return s != null && i >= 0 && i < s.length() ? s.charAt(i) : '\0';
  }

  static public ThreadLocal<BufferedImage> currentImage_var = new ThreadLocal();

  static public BufferedImage currentImage() {
    return currentImage_var.get();
  }

  static public void currentImage(BufferedImage img) {
    currentImage_var.set(img);
  }

  static public Map<String, Object> objectToMap(Object o) {
    try {
      if (o instanceof Map)
        return (Map) o;
      TreeMap<String, Object> map = new TreeMap();
      Class c = o.getClass();
      while (c != Object.class) {
        Field[] fields = c.getDeclaredFields();
        for (final Field field : fields) {
          if ((field.getModifiers() & Modifier.STATIC) != 0)
            continue;
          field.setAccessible(true);
          final Object value = field.get(o);
          if (value != null)
            map.put(field.getName(), value);
        }
        c = c.getSuperclass();
      }
      if (o instanceof DynamicObject)
        map.putAll(((DynamicObject) o).fieldValues);
      return map;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public List<Map<String, Object>> objectToMap(Iterable l) {
    if (l == null)
      return null;
    List x = new ArrayList();
    for (Object o : l) x.add(objectToMap(o));
    return x;
  }

  static public String[] asStringArray(Collection<String> c) {
    return toStringArray(c);
  }

  static public String[] asStringArray(Object o) {
    return toStringArray(o);
  }

  static public int latestInstalledJavaX() {
    File[] files = new File(userHome(), ".javax").listFiles();
    int v = 0;
    if (files != null)
      for (File f : files) {
        Matcher m = Pattern.compile("x(\\d\\d\\d?)\\.jar").matcher(f.getName());
        if (m.matches())
          v = Math.max(v, Integer.parseInt(m.group(1)));
      }
    return v;
  }

  static public String x30JarServerURL() {
    return "http://botcompany.de:8081/x30.jar";
  }

  static public float abs(float f) {
    return Math.abs(f);
  }

  static public int abs(int i) {
    return Math.abs(i);
  }

  static public double abs(double d) {
    return Math.abs(d);
  }

  static public <A> Set<A> newWeakHashSet() {
    return synchroWeakHashSet();
  }

  static public void cancelTimers(Collection timers) {
    for (Object timer : timers) cancelTimer(timer);
  }

  static public <A> List<A> getAndClearList(Collection<A> l) {
    if (l == null)
      return emptyList();
    synchronized (collectionMutex(l)) {
      List<A> out = cloneList(l);
      l.clear();
      return out;
    }
  }

  static public Color halfBlack() {
    return colorWithAlpha(0.5, Color.black);
  }

  static public <A> A evalInQ(Q q, final F0<A> f) {
    if (isInQ(q))
      return callF(f);
    final Var<Either<A, Throwable>> var = new Var();
    q.add(new Runnable() {

      public void run() {
        try {
          try {
            var.set(eitherA(callF(f)));
          } catch (Throwable e) {
            var.set(eitherB(e));
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "try {\r\n      var.set(eitherA(callF(f)));\r\n    } catch (Throwable e) {\r\n      ...";
      }
    });
    return returnOrThrow_either(waitForVarToBeNotNull(var));
  }

  static public Iterator emptyIterator() {
    return Collections.emptyIterator();
  }

  static public 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 public 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 public <A> Set<A> synchroWeakHashSet() {
    return Collections.newSetFromMap((Map) newWeakHashMap());
  }

  static public Color colorWithAlpha(Color c, double alpha) {
    return new Color(c.getRed() / 255f, c.getGreen() / 255f, c.getBlue() / 255f, (float) alpha);
  }

  static public Color colorWithAlpha(double alpha, Color c) {
    return colorWithAlpha(c, alpha);
  }

  static public boolean isInQ(Q q) {
    return q != null && isCurrentThread(q.rst.thread);
  }

  static public <A, B> Either<A, B> eitherA(A a) {
    return new Either(1, a);
  }

  static public <A, B> Either<A, B> eitherB(B b) {
    return new Either(2, b);
  }

  static public <A> A returnOrThrow_either(Either<A, Throwable> e) {
    if (isEitherB(e))
      throw rethrow(e.b());
    return eitherAOpt(e);
  }

  static public <A> A waitForVarToBeNotNull(Var<A> v) {
    try {
      synchronized (v) {
        while (!v.has()) v.wait();
        return v.get();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean isCurrentThread(Thread t) {
    return t != null && t == currentThread();
  }

  static public <A, B> boolean isEitherB(Either<A, B> e) {
    return eitherIsB(e);
  }

  static public <A, B> A eitherAOpt(Either<A, B> e) {
    return e != null && e.isA() ? e.a() : null;
  }

  static public <A, B> boolean eitherIsB(Either<A, B> e) {
    return e != null && e.isB();
  }

  static public class Either<A, B> {

    public byte which;

    public Object value;

    public Either() {
    }

    public Either(int which, Object value) {
      this.which = (byte) which;
      this.value = value;
    }

    public boolean isA() {
      return which == 1;
    }

    public boolean isB() {
      return which == 2;
    }

    public A a() {
      if (which != 1)
        _failMe();
      return (A) value;
    }

    public B b() {
      if (which != 2)
        _failMe();
      return (B) value;
    }

    public A aOpt() {
      return which != 1 ? null : (A) value;
    }

    public B bOpt() {
      return which != 2 ? null : (B) value;
    }

    public void _failMe() {
      throw fail("Either object is of wrong type: " + shortClassName(value));
    }

    public String toString() {
      return "Either" + (isA() ? "A" : "B") + "(" + value + ")";
    }
  }

  static public class Scored<A> extends Var<A> {

    public float score;

    public Scored() {
    }

    public Scored(A a, float score) {
      super(a);
      this.score = score;
    }

    public Scored(A a, double score) {
      super(a);
      this.score = (float) score;
    }

    public float score() {
      return score;
    }

    public String toString() {
      return toIntPercent(score) + "%: " + str(get());
    }
  }

  static public String b(Object contents, Object... params) {
    return tag("b", contents, params);
  }

  static public <A, B> boolean isA(Either<A, B> e) {
    return eitherIsA(e);
  }

  static public int toIntPercent(double ratio) {
    return roundToInt(ratio * 100);
  }

  static public int toIntPercent(float ratio) {
    return toIntPercent((double) ratio);
  }

  static public String tag(String tag) {
    return htag(tag);
  }

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

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

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

  static public <A, B> boolean eitherIsA(Either<A, B> e) {
    return e != null && e.isA();
  }

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

  static public String htag(String tag) {
    return htag(tag, "");
  }

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

  static public String hopeningTag(String tag, Map params) {
    return hopeningTag(tag, mapToParams(params));
  }

  static public String hopeningTag(String tag, Object... params) {
    StringBuilder buf = new StringBuilder();
    buf.append("<" + tag);
    for (int i = 0; i < l(params); i += 2) {
      String name = (String) get(params, i);
      Object val = get(params, i + 1);
      if (nempty(name) && val != null) {
        if (val == html_valueLessParam())
          buf.append(" " + name);
        else {
          String s = str(val);
          if (!empty(s))
            buf.append(" " + name + "=" + htmlQuote(s));
        }
      }
    }
    buf.append(">");
    return str(buf);
  }

  static public boolean neqic(String a, String b) {
    return !eqic(a, b);
  }

  static public boolean neqic(char a, char b) {
    return !eqic(a, b);
  }

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

  static public Object html_valueLessParam_cache;

  static public Object html_valueLessParam() {
    if (html_valueLessParam_cache == null)
      html_valueLessParam_cache = html_valueLessParam_load();
    return html_valueLessParam_cache;
  }

  static public Object html_valueLessParam_load() {
    return new Object();
  }

  static public String htmlQuote(String s) {
    return "\"" + htmlencode_forParams(s) + "\"";
  }

  static public Object[] mapToObjectArray(Map map) {
    List l = new ArrayList();
    for (Object o : keys(map)) {
      l.add(o);
      l.add(map.get(o));
    }
    return toObjectArray(l);
  }

  static public Object[] mapToObjectArray(Object f, Collection l) {
    int n = l(l);
    Object[] array = new Object[n];
    if (n != 0) {
      Iterator it = iterator(l);
      for (int i = 0; i < n; i++) array[i] = callF(f, it.next());
    }
    return array;
  }

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

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

  static public ThreadLocal<Boolean> htmlencode_forParams_useV2 = new ThreadLocal();

  static public String htmlencode_forParams(String s) {
    if (s == null)
      return "";
    if (isTrue(htmlencode_forParams_useV2.get()))
      return htmlencode_forParams_v2(s);
    StringBuilder out = new StringBuilder(Math.max(16, s.length()));
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      if (c > 127 || c == '"' || c == '<' || c == '>') {
        out.append("&#");
        out.append((int) c);
        out.append(';');
      } else
        out.append(c);
    }
    return out.toString();
  }

  static public String htmlencode_forParams_v2(String s) {
    if (s == null)
      return "";
    StringBuilder out = new StringBuilder(Math.max(16, s.length()));
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') {
        out.append("&#");
        out.append((int) c);
        out.append(';');
      } else
        out.append(c);
    }
    return out.toString();
  }
}