import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import org.apache.commons.codec.net.URLCodec;
public class main {


 // commons codec


static boolean test;
  
public static void main(String[] args) throws Exception {
  String name = args[0]; // put file name here
  if (args.length > 1 && args[1].equals("test"))
    test = true;
  name = new File(name).getAbsolutePath();
  byte[] data  = loadBinaryFile(name);
  if (data == null)
    print("File not found: " + name);
  else
    if (test)
      print(binaryUrlencode(data));
    else
      uploadData("data-uploader " + programID(), "Data file " + name + " from " + computerID(), data, false);
}

static String uploadData(String gummipw, String title, byte[] data, boolean superhigh) throws IOException {
  if (gummipw == null || gummipw.length() == 0)
    throw new RuntimeException("Need gummi password.");
    
  System.out.println("Uploading:");
  System.out.println("  gummipw: " + gummipw);
  System.out.println("  " + title);
  int displayLength = 40;
  System.out.println("  " + data.length + " bytes of data");

  URL url = new URL("http://tinybrain.de:8080/tb-int/add_snippet.php");
  String base = base64encode(data);
  print("Base-encoded => " + l(base));
  data = null;
  String encoded = new URLCodec().encode(base, "UTF-8");
  base = null;
  print("URL-encoded => " + l(encoded));
  String postData =
    "gummipw=" + URLEncoder.encode(unnull(gummipw), "UTF-8")
    + "&blob=" + encoded
    + "&name=" + URLEncoder.encode(unnull(title), "UTF-8")
    + "&type=" + 37 /* SN_DATA */
    + "&" + (superhigh ? "superhigh" : "high") + "=1&public=1";
  System.out.println("Post data length: " + postData.length());

  String contents = doPost(postData, url.openConnection(), url);
  System.out.println(contents);

  if (isInteger(contents)) {
    long id = parseSnippetID(contents);
    System.out.println("=> #" + id);
    return "#" + id;
  } else
    throw new RuntimeException("Server error: " + contents);
}

static String _computerID;
public static String computerID() { try {
 
  if (_computerID == null) {
    File file = new File(userHome(), ".tinybrain/computer-id");
    _computerID = loadTextFile(file.getPath(), null);
    if (_computerID == null) {
      _computerID = makeRandomID(12);
      saveTextFile(file.getPath(), _computerID);
    }
  }
  return _computerID;

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile StringBuffer print_log = local_log; // might be redirected, e.g. to main bot

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

static boolean print_silent; // total mute if set

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

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

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

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

static void print_append(StringBuffer buf, String s, int max) {
  synchronized(buf) {
    buf.append(s);
    max /= 2;
    if (buf.length() > max) try {
      int newLength = max/2;
      int ofs = buf.length()-newLength;
      String newString = buf.substring(ofs);
      buf.setLength(0);
      buf.append("[...] ").append(newString);
    } catch (Exception e) {
      buf.setLength(0);
    }
  }
}
  public static String binaryUrlencode(byte[] bytes) {
    return binaryUrlencode(bytes, 0, bytes.length);
  }

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

static boolean isInteger(String s) {
  return s != null && Pattern.matches("\\-?\\d+", s);
}
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;
}
public static byte[] loadBinaryFile(String fileName) {
 try {
  if (!new File(fileName).exists())
    return null;

  FileInputStream in = new FileInputStream(fileName);

  byte buf[] = new byte[1024];
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  int l;
  while (true) {
    l = in.read(buf);
    if (l <= 0) break;
    out.write(buf, 0, l);
  }
  in.close();
  return out.toByteArray();
 } catch (IOException e) { throw new RuntimeException(e); }
}

public static byte[] loadBinaryFile(File file) {
  return loadBinaryFile(file.getPath());
}

  static String base64encode(byte[] a) {
    int aLen = a.length;
    int numFullGroups = aLen/3;
    int numBytesInPartialGroup = aLen - 3*numFullGroups;
    int resultLen = 4*((aLen + 2)/3);
    StringBuffer result = new StringBuffer(resultLen);
    char[] intToAlpha = intToBase64;

    // Translate all full groups from byte array elements to Base64
    int inCursor = 0;
    for (int i=0; i<numFullGroups; i++) {
      int byte0 = a[inCursor++] & 0xff;
      int byte1 = a[inCursor++] & 0xff;
      int byte2 = a[inCursor++] & 0xff;
      result.append(intToAlpha[byte0 >> 2]);
      result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]);
      result.append(intToAlpha[(byte1 << 2)&0x3f | (byte2 >> 6)]);
      result.append(intToAlpha[byte2 & 0x3f]);
    }

    // Translate partial group if present
    if (numBytesInPartialGroup != 0) {
      int byte0 = a[inCursor++] & 0xff;
      result.append(intToAlpha[byte0 >> 2]);
      if (numBytesInPartialGroup == 1) {
        result.append(intToAlpha[(byte0 << 4) & 0x3f]);
        result.append("==");
      } else {
        // assert numBytesInPartialGroup == 2;
        int byte1 = a[inCursor++] & 0xff;
        result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]);
        result.append(intToAlpha[(byte1 << 2)&0x3f]);
        result.append('=');
      }
    }
    // assert inCursor == a.length;
    // assert result.length() == resultLen;
    return result.toString();
  }

  /**
   * This array is a lookup table that translates 6-bit positive integer
   * index values into their "Base64 Alphabet" equivalents as specified
   * in Table 1 of RFC 2045.
   */
  static final char intToBase64[] = {
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
    'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
  };

  static String unnull(String s) {
    return s == null ? "" : s;
  }
  
  static <A> List<A> unnull(List<A> l) {
    return l == null ? emptyList() : l;
  }
  
  static <A> Iterable<A> unnull(Iterable<A> i) {
    return i == null ? emptyList() : i;
  }
  
  static Object[] unnull(Object[] a) {
    return a == null ? new Object[0] : a;
  }
static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] a) { return a == null ? 0 : a.length; }
static int l(char[] a) { return a == null ? 0 : a.length; }
static int l(Collection c) { return c == null ? 0 : c.size(); }
static int l(Map m) { return m == null ? 0 : m.size(); }
static int l(CharSequence s) { return s == null ? 0 : s.length(); } 

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

static String doPost(Map urlParameters, String url) {
  return doPost(makePostData(urlParameters), url);
}

static String doPost(String urlParameters, String url) { try {
 
  URL _url = new URL(url);
  return doPost(urlParameters, _url.openConnection(), _url);

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

static String doPost(String urlParameters, URLConnection conn, URL url) { try {
 
  String computerID = getComputerID();
  if (computerID != null)
    conn.setRequestProperty("X-ComputerID", computerID);
    
  print("Sending POST request: " + url);
      
  // connect and do POST
  conn.setDoOutput(true);

  OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
  writer.write(urlParameters);
  writer.flush();

  String contents = loadPage(conn, url);
  writer.close();
  return contents;

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String programID() {
  return getProgramID();
}


  public static String loadTextFile(String fileName) {
    try {
      return loadTextFile(fileName, null);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  
  public static String loadTextFile(String fileName, String defaultContents) throws IOException {
    if (!new File(fileName).exists())
      return defaultContents;

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

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

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

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

static String getProgramID(Object o) {
  return getProgramID(getMainClass(o));
}
static String makeRandomID(int length) {
  Random random = new Random();
  char[] id = new char[length];
  for (int i = 0; i < id.length; i++)
    id[i] = (char) ((int) 'a' + random.nextInt(26));
  return new String(id);
}
static String getComputerID() { try {
 
  return computerID();

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
  static ThreadLocal<String> loadPage_charset = new ThreadLocal<String>();
  static boolean loadPage_allowGzip = true, loadPage_debug;
  static boolean loadPage_anonymous; // don't send computer ID
  static int loadPage_verboseness = 100000;
  static int loadPage_retries = 60; // seconds

  public static String loadPageSilently(String url) {
    try {
      return loadPageSilently(new URL(loadPage_preprocess(url)));
    } catch (IOException e) { throw new RuntimeException(e); }
  }

  public static String loadPageSilently(URL url) {
    try {
      IOException e = null;
      for (int tries = 0; tries < loadPage_retries; tries++)
        try {
          URLConnection con = openConnection(url);
          return loadPage(con, url);
        } catch (IOException _e) {
          e = _e;
          print("Trying proxy because of: " + e);
          try {
            return loadPageThroughProxy(str(url));
          } catch (Throwable e2) {
            print("  " + exceptionToStringShort(e2));
          }
          sleepSeconds(1);
        }
      throw e;
    } catch (IOException e) { throw new RuntimeException(e); }
  }

  static String loadPage_preprocess(String url) {  
    if (url.startsWith("tb/"))
      url = "tinybrain.de:8080/" + url;
    if (url.indexOf("://") < 0)
      url = "http://" + url;
    return url;
  }
  
  public static String loadPage(String url) {
    try {
      url = loadPage_preprocess(url);
      print("Loading: " + url);
      return loadPageSilently(new URL(url));
    } catch (IOException e) { throw new RuntimeException(e); }
  }
  
  public static String loadPage(URL url) {
    print("Loading: " + url.toExternalForm());
    return loadPageSilently(url);
  }

  public static String loadPage(URLConnection con, URL url) throws IOException {
    try {
      if (!loadPage_anonymous) {
        String computerID = getComputerID();
        if (computerID != null)
          con.setRequestProperty("X-ComputerID", computerID);
      }
      if (loadPage_allowGzip)
        con.setRequestProperty("Accept-Encoding", "gzip");
    } catch (Throwable e) {} // fails if within doPost
    String contentType = con.getContentType();
    if (contentType == null)
      throw new IOException("Page could not be read: " + url);
    //print("Content-Type: " + contentType);
    String charset = loadPage_charset == null ? null : loadPage_charset.get();
    if (charset == null) charset = loadPage_guessCharset(contentType);
    
    InputStream in = con.getInputStream();
    if ("gzip".equals(con.getContentEncoding())) {
      if (loadPage_debug)
        print("loadPage: Using gzip.");
      in = new GZIPInputStream(in);
    }
    Reader r = new InputStreamReader(in, charset);
    
    StringBuilder buf = new StringBuilder();
    int n = 0;
    while (true) {
      int ch = r.read();
      if (ch < 0)
        break;
      buf.append((char) ch);
      ++n;
      if ((n % loadPage_verboseness) == 0) print("  " + n + " chars read");
    }
    return buf.toString();
  }
  
  static String loadPage_guessCharset(String contentType) {
    Pattern p = Pattern.compile("text/[a-z]+;\\s+charset=([^\\s]+)\\s*");
    Matcher m = p.matcher(contentType);
    /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
    return m.matches() ? m.group(1) : "ISO-8859-1";
  }

  static RuntimeException fail() {
    throw new RuntimeException("fail");
  }
  
  static RuntimeException fail(Object msg) {
    throw new RuntimeException(String.valueOf(msg));
  }
  
  static RuntimeException fail(String msg) {
    throw new RuntimeException(unnull(msg));
  }
   
  // disabled for now to shorten some programs 
  /*static RuntimeException fail(S msg, O... args) {
    throw new RuntimeException(format(msg, args));
  }*/
static String _userHome;
static String userHome() {
  if (_userHome == null) {
    if (isAndroid())
      _userHome = "/storage/sdcard0/";
    else
      _userHome = System.getProperty("user.home");
    //System.out.println("userHome: " + _userHome);
  }
  return _userHome;
}

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

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

static String makePostData(Map<Object, Object> map) {
  List<String> l = new ArrayList<String>();
  for (Map.Entry<Object, Object> e : map.entrySet()) {
    String key = (String) ( e.getKey());
    String value = structureOrText(e.getValue());
    l.add(urlencode(key) + "=" + urlencode(value));
  }
  return join("&", l);
}

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

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


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

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static LinkedHashMap litorderedmap(Object... x) {
  LinkedHashMap map = new LinkedHashMap();
  litmap_impl(map, x);
  return map;
}
static void sleepSeconds(double s) {
  if (s > 0) sleep(round(s*1000));
}
static String urlencode(String x) {
  try {
    return URLEncoder.encode(unnull(x), "UTF-8");
  } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); }
}
static long now_virtualTime;
static long now() {
  return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}

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

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

static Class getMainClass() { try {
 
  return Class.forName("main");

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

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

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static void printStackTrace(Throwable e) {
  // we go to system.out now - system.err is nonsense
  print(getStackTrace(e));
}

static void printStackTrace() {
  printStackTrace(new Throwable());
}
static URLConnection openConnection(URL url) { try {
 
  ping();
  return url.openConnection();

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static boolean nempty(Collection c) {
  return !isEmpty(c);
}

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

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

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

static boolean nempty(Iterator i) {
  return i != null && i.hasNext();
}
static String exceptionToStringShort(Throwable e) {
  e = getInnerException(e);
  String msg = unnull(e.getMessage());
  if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
    return baseClassName(e) + ": " + msg;
  else
    return msg;
}
static String str(Object o) {
  return String.valueOf(o);
}
static String structureOrText(Object o) {
  return o instanceof String ? (String) o : structure(o);
}
static Object getOpt(Object o, String field) {
  if (o instanceof String) o = getBot ((String) o);
  if (o == null) return null;
  if (o instanceof Class) return getOpt((Class) o, field);
  
  if (o.getClass().getName().equals("main$DynamicObject"))
    return ((Map) getOpt_raw(o, "fieldValues")).get(field);
  
  if (o instanceof Map) return ((Map) o).get(field);
  
  return getOpt_raw(o, field);
}

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

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

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

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

static long parseLong(Object s) {
  return Long.parseLong((String) s);
}
static File userDir() {
  return new File(userHome());
}

static File userDir(String path) {
  return new File(userHome(), path);
}
static String loadPageThroughProxy(String url) {
  adbForward();
  DialogIO io = talkToOpt("localhost", 4995); // Test ADB Bridge
  if (io == null)
    io = talkToOpt(gateway(), 4999); // Phone, Public Comm Bot
  if (io == null) return null;
  String answer = unquote(io.ask(forward("Awareness", format("loadPage *", url))));
  io.close();
  if (swic(answer, "ok "))
    return answer.substring(3);
  throw fail(answer);
}
static boolean isAndroid() { return System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0; }


static String getStackTrace(Throwable throwable) {
  StringWriter writer = new StringWriter();
  throwable.printStackTrace(new PrintWriter(writer));
  return writer.toString();
}
static Object getBot(String botID) {
  return callOpt(getMainBot(), "getBot", botID);
}

  static String format(String pat, Object... args) {
    return format3(pat, args);
  }

static DialogIO talkToOpt(String host, int port) {
  try {
    return talkTo(host, port);
  } catch (Throwable e) {
    return null;
  }
}
static TimedCache<String> adbForward_list = new TimedCache(10);

static void adbForward() {
  if (!isOnPATH("adb"))
    print("adb not on path");
  else {
    backtick_verbose = true;
    String list = adbForward_list.get(new Object() { Object get() { return backtick("adb forward --list"); }});
    if (!contains(list, "4995"))
      backtick("adb forward tcp:4995 tcp:4999");
  }
}
public static File mkdirsForFile(File file) {
  File dir = file.getParentFile();
  if (dir != null) // is null if file is in current dir
    dir.mkdirs();
  return file;
}

static volatile boolean ping_pauseAll;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions;
static Map<Thread, Object> ping_actions = synchroMap(new WeakHashMap());

// returns true if it did anything
static boolean ping() {
  if (ping_pauseAll) {
    do
      sleep(ping_sleep);
    while (ping_pauseAll); return true;
  }
  
  if (ping_anyActions) {
    Object action;
    synchronized(mc()) {
      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;
}
static boolean swic(String a, String b) {
  return startsWithIgnoreCase(a, b);
}
static void sleep(long ms) {
  try {
    Thread.sleep(ms);
  } catch (Exception e) { throw new RuntimeException(e); }
}

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

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String baseClassName(String className) {
  return substring(className, className.lastIndexOf('.'));
}

static String baseClassName(Object o) {
  return baseClassName(getClassName(o));
}
  public static String unquote(String s) {
    if (s == null) return null;
    if (s.startsWith("[")) {
      int i = 1;
      while (i < s.length() && s.charAt(i) == '=') ++i;
      if (i < s.length() && s.charAt(i) == '[') {
        String m = s.substring(1, i);
        if (s.endsWith("]" + m + "]"))
          return s.substring(i+1, s.length()-i-1);
      }
    }
    
    if (s.startsWith("\"") /*&& s.endsWith("\"")*/ && s.length() > 1) {
      String st = s.substring(1, s.endsWith("\"") ? s.length()-1 : s.length());
      StringBuilder sb = new StringBuilder(st.length());
  
      for (int i = 0; i < st.length(); i++) {
        char ch = st.charAt(i);
        if (ch == '\\') {
          char nextChar = (i == st.length() - 1) ? '\\' : st
                  .charAt(i + 1);
          // Octal escape?
          if (nextChar >= '0' && nextChar <= '7') {
              String code = "" + nextChar;
              i++;
              if ((i < st.length() - 1) && st.charAt(i + 1) >= '0'
                      && st.charAt(i + 1) <= '7') {
                  code += st.charAt(i + 1);
                  i++;
                  if ((i < st.length() - 1) && st.charAt(i + 1) >= '0'
                          && st.charAt(i + 1) <= '7') {
                      code += st.charAt(i + 1);
                      i++;
                  }
              }
              sb.append((char) Integer.parseInt(code, 8));
              continue;
          }
          switch (nextChar) {
          case '\\':
              ch = '\\';
              break;
          case 'b':
              ch = '\b';
              break;
          case 'f':
              ch = '\f';
              break;
          case 'n':
              ch = '\n';
              break;
          case 'r':
              ch = '\r';
              break;
          case 't':
              ch = '\t';
              break;
          case '\"':
              ch = '\"';
              break;
          case '\'':
              ch = '\'';
              break;
          // Hex Unicode: u????
          case 'u':
              if (i >= st.length() - 5) {
                  ch = 'u';
                  break;
              }
              int code = Integer.parseInt(
                      "" + st.charAt(i + 2) + st.charAt(i + 3)
                              + st.charAt(i + 4) + st.charAt(i + 5), 16);
              sb.append(Character.toChars(code));
              i += 5;
              continue;
          default:
            ch = nextChar; // added by Stefan
          }
          i++;
        }
        sb.append(ch);
      }
      return sb.toString();      
    } else
      return s; // return original
  }
static String forward(String bot, String msg, Object... args) {
  return format("please forward to bot *: *", bot, format(msg, args));
}
static boolean isEmpty(Collection c) {
  return c == null || c.isEmpty();
}

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

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

static boolean isEmpty(Map map) {
  return map == null || map.isEmpty();
}
static String dropSuffix(String suffix, String s) {
  return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static Throwable getInnerException(Throwable e) {
  while (e.getCause() != null)
    e = e.getCause();
  return e;
}
static String structure(Object o) {
  HashSet refd = new HashSet();
  return structure_2(structure_1(o, 0, new IdentityHashMap(), refd), refd);
}

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

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

  String name = o.getClass().getName();

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

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

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

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

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

static long round(double d) {
  return Math.round(d);
}
static void copyStream(InputStream in, OutputStream out) { try {
 
  byte[] buf = new byte[65536];
  while (true) {
    int n = in.read(buf);
    if (n <= 0) return;
    out.write(buf, 0, n);
  }

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static Map litmap(Object... x) {
  TreeMap map = new TreeMap();
  litmap_impl(map, x);
  return map;
}

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


  static String format3(String pat, Object... args) {
    if (args.length == 0) return pat;
    
    List<String> tok = javaTokPlusPeriod(pat);
    int argidx = 0;
    for (int i = 1; i < tok.size(); i += 2)
      if (tok.get(i).equals("*"))
        tok.set(i, format3_formatArg(argidx < args.length ? args[argidx++] : "null"));
    return join(tok);
  }
  
  static String format3_formatArg(Object arg) {
    if (arg == null) return "null";
    if (arg instanceof String) {
      String s = (String) arg;
      return isIdentifier(s) || isNonNegativeInteger(s) ? s : quote(s);
    }
    if (arg instanceof Integer || arg instanceof Long) return String.valueOf(arg);
    return quote(structure(arg));
  }
  

static boolean isOnPATH(String cmd) {
  String path = System.getenv("PATH");
  List<String> dirs = splitAt(path, File.pathSeparator);
  String c = isWindows() ? cmd + ".exe" : cmd;
  for (String dir : dirs)
    if (new File(dir, c).isFile())
      return true;
  return false;
}
static <A> ArrayList<A> asList(A[] a) {
  return new ArrayList<A>(Arrays.asList(a));
}

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

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

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

static void swapElements(List l, int i, int j) {
  if (i == j) return;
  Object o = l.get(i);
  l.set(i, l.get(j));
  l.set(j, o);
}
  static String quote(String s) {
    if (s == null) return "null";
    return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r", "\\r").replace("\n", "\\n") + "\"";
  }
  
  static String quote(long l) {
    return quote("" + l);
  }
  
  static String quote(char c) {
    return quote("" + c);
  }

static String shorten(String s, int max) {
  if (s == null) return "";
  return s.length() <= max ? s : s.substring(0, Math.min(s.length(), max)) + "...";
}
static Class mc() {
  return getMainClass();
}
static String quoteCharacter(char c) {
  if (c == '\'') return "'\\''";
  if (c == '\\') return "'\\\\'";
  return "'" + c + "'";
}

static Thread currentThread() {
  return Thread.currentThread();
}
static boolean eq(Object a, Object b) {
  if (a == null) return b == null;
  if (a.equals(b)) return true;
  if (a instanceof BigInteger) {
    if (b instanceof Integer) return a.equals(BigInteger.valueOf((Integer) b));
    if (b instanceof Long) return a.equals(BigInteger.valueOf((Long) b));
  }
  return false;
}
static TimedCache<List<String>> detectGateways_cache = new TimedCache(5);

static synchronized List<String> detectGateways() { try {
 
  if (detectGateways_cache.has()) return detectGateways_cache.getNoClean();

  boolean win = isWindows();
  String s = backtick(win ? "ipconfig" : "ip route show");
  TreeSet<String> ips = new TreeSet<String>();
  for (String line : toLines(s))
    if (indexOfIgnoreCase(line, win ? "Gateway" : "via") >= 0)
      ips.addAll(regexpAll("\\d+\\.\\d+\\.\\d+\\.\\d+", line));
  return detectGateways_cache.set(new ArrayList<String>(ips));

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static boolean contains(Collection c, Object o) {
  return c != null && c.contains(o);
}

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

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

static boolean contains(String s, String b) {
  return s != null && s.indexOf(b) >= 0;
}
// get purpose 1: access a list/array (safer version of x.get(y))

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

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

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

static Object get(Object o, String field) {
  if (o instanceof Class) return get((Class) o, field);
  
  if (o instanceof Map)
    return ((Map) o).get(field);
    
  if (o.getClass().getName().equals("main$DynamicObject"))
    return call(get_raw(o, "fieldValues"), "get", field);
    
  return get_raw(o, field);
}

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

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

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

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

static int talkTo_defaultTimeout = 10000;

static DialogIO talkTo(String ip, int port) { try {
 
  final Socket s = new Socket();
  s.connect(new InetSocketAddress(ip, port), talkTo_defaultTimeout);
  //print("Talking to " + ip + ":" + port);

  final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
  final BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
  return new DialogIO() {
    boolean isLocalConnection() {
      return s.getInetAddress().isLoopbackAddress();
    }
    
    boolean isStillConnected() {
      return !(eos || s.isClosed());
    }
    
    void sendLine(String line) { try {
 
      w.write(line + "\n");
      w.flush();
    
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
    
    String readLineImpl() { try {
 
      return in.readLine();
    
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
    
    void close() {
      try {
        s.close();
      } catch (IOException e) {
        // whatever
      }
    }
    
    Socket getSocket() {
      return s;
    }
  };

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static Map synchroMap() {
  return synchroHashMap();
}

static <A, B> Map<A, B> synchroMap(Map<A, B> map) {
  return Collections.synchronizedMap(map);
}
static Object callOpt(Object o) {
  if (o == null) return null;
  return callF(o);
}

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

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

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

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

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

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


// replacement for class JavaTok
// maybe incomplete, might want to add floating point numbers
// todo also: extended multi-line strings

static int javaTok_n, javaTok_elements;
static boolean javaTok_opt;

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

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

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

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

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

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

static Object getMainBot() {
  return mainBot;
}
static String substring(String s, int x) {
  return safeSubstring(s, x);
}

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

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

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

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

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

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


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

static boolean isTrue(Object pred, Object arg) {
  return booleanValue(callF(pred, arg));
}
static int backtick_exitValue;
static boolean backtick_verbose;

public static String backtick(String cmd) { try {
 
  File outFile = File.createTempFile("_backtick", "");
  File scriptFile = File.createTempFile("_backtick", isWindows() ? ".bat" : "");

  String command = cmd + " >" + bashQuote(outFile.getPath()) + " 2>&1";
  //Log.info("[Backtick] " + command);
  try {
    if (backtick_verbose)
      print("backtick: command " + command);
    saveTextFile(scriptFile.getPath(), command);
    String[] command2;
    if (isWindows())
      command2 = new String[] { scriptFile.getPath() };
    else
      command2 = new String[] { "/bin/bash", scriptFile.getPath() };
    if (backtick_verbose)
      print("backtick: command2 " + structure(command2));
    Process process = Runtime.getRuntime().exec(command2);
    try {
      process.waitFor();
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }
    backtick_exitValue = process.exitValue();
    if (backtick_verbose)
      System.out.println("Process return code: " + backtick_exitValue);
    String result = loadTextFile(outFile.getPath(), "");
    if (backtick_verbose)
      print("[[\n" + result + "]]");
    return result;
  } finally {
    scriptFile.delete();
  }

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


static boolean startsWithIgnoreCase(String a, String b) {
  return a != null && a.regionMatches(true, 0, b, 0, b.length());
}
static Object first(Object list) {
  return ((List) list).isEmpty() ? null : ((List) list).get(0);
}

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

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

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



static Object callF(Object f, Object... args) {
  return callFunction(f, args);
}
static Object callFunction(Object f, Object... args) {
  if (f == null) return null;
  if (f instanceof Runnable) {
    ((Runnable) f).run();
    return null;
  } else if (f instanceof String)
    return call(mc(), (String) f, args);
  else
    return call(f, "get", args);
  //else throw fail("Can't call a " + getClassName(f));
}
// hopefully covers all cases :)
static String safeSubstring(String s, int x, int y) {
  if (s == null) return null;
  if (x < 0) x = 0;
  if (x > s.length()) return "";
  if (y < x) y = x;
  if (y > s.length()) y = s.length();
  return s.substring(x, y);
}

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

public static boolean isWindows() {
  return System.getProperty("os.name").contains("Windows");
}
/** possibly improvable */
static String bashQuote(String text) {
  if (text == null) return null;
  return "\"" + text
    .replace("\\", "\\\\")
    .replace("\"", "\\\"")
    .replace("\n", "\\n")
    .replace("\r", "\\r") + "\"";
}

static String bashQuote(File f) {
  return bashQuote(f.getAbsolutePath());
}
static String quickSubstring(String s, int i, int j) {
  if (i == j) return "";
  return s.substring(i, j);
}
static List<String> splitAt(String s, String splitter) {
  List<String> parts = new ArrayList<String>();
  int i = 0;
  if (s != null)
    while (i < l(s)) {
      int j = indexOf(s, splitter, i);
      if (j < 0) j = l(s);
      parts.add(substring(s, i, j));
      i = j+l(splitter);
    }
  return parts;
}
static List<String> toLines(File f) {
  return toLines(loadTextFile(f));
}

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

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

      start = i;
    }
    return lines;
  }

  private static int toLines_nextLineBreak(String s, int start) {
    for (int i = start; i < s.length(); i++) {
      char c = s.charAt(i);
      if (c == '\r' || c == '\n')
        return i;
    }
    return -1;
  }
// works on lists and strings and null

static int indexOfIgnoreCase(Object a, Object b) {
  if (a == null) return -1;
  if (a instanceof String) {
     Matcher m = Pattern.compile((String) b, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher((String) a);
     if (m.find()) return m.start(); else return -1;
  }
  if (a instanceof List) {
    for (int i = 0; i < ((List) a).size(); i++) {
      Object o = ((List) a).get(i);
      if (o != null && ((String) o).equalsIgnoreCase((String) b))
        return i;
    }
    return -1;
  }
  throw fail("Unknown type: " + a);
}
static boolean isIdentifier(String s) {
  return isJavaIdentifier(s);
}
static boolean empty(Collection c) {
  return isEmpty(c);
}

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

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

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

static boolean empty(Object o) {
  if (o instanceof Collection) return empty((Collection) o);
  if (o instanceof String) return empty((String) o);
  if (o instanceof Map) return empty((Map) o);
  if (o instanceof Object[]) return empty((Object[]) o);
  throw fail("unknown type for 'empty': " + getType(o));
}
// extended over Class.isInstance() to handle primitive types
static boolean isInstanceX(Class type, Object arg) {
  if (type == boolean.class) return arg instanceof Boolean;
  if (type == int.class) return arg instanceof Integer;
  if (type == long.class) return arg instanceof Long;
  if (type == float.class) return arg instanceof Float;
  if (type == short.class) return arg instanceof Short;
  if (type == char.class) return arg instanceof Character;
  if (type == byte.class) return arg instanceof Byte;
  if (type == double.class) return arg instanceof Double;
  return type.isInstance(arg);
}
static boolean isNonNegativeInteger(String s) {
  return s != null && Pattern.matches("\\d+", s);
}
// This is made for NL parsing.
// It's javaTok extended with "..." token, "$n" and "#n" and
// special quotes (which are converted to normal ones).

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

    // scan for non-whitespace
    if (c == '\u201C' || c == '\u201D') c = '"'; // normalize quotes
    if (c == '\'' || c == '"') {
      char opener = c;
      ++j;
      while (j < l) {
        char _c = s.charAt(j);
        if (_c == '\u201C' || _c == '\u201D') _c = '"'; // normalize quotes
        if (_c == opener) {
          ++j;
          break;
        } else if (s.charAt(j) == '\\' && j+1 < l)
          j += 2;
        else
          ++j;
      }
      if (j-1 >= i+1) {
        tok.add(opener + s.substring(i+1, j-1) + opener);
        i = j;
        continue;
      }
    } else if (Character.isJavaIdentifierStart(c))
      do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\'')); // for things like "this one's"
    else if (Character.isDigit(c))
      do ++j; while (j < l && Character.isDigit(s.charAt(j)));
    else if (cc.equals("[[")) {
      do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
      j = Math.min(j+2, l);
    } else if (cc.equals("[=") && i+2 < l && s.charAt(i+2) == '[') {
      do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
      j = Math.min(j+3, l);
    } else if (s.substring(j, Math.min(j+3, l)).equals("..."))
      j += 3;
    else if (c == '$' || c == '#')
      do ++j; while (j < l && Character.isDigit(s.charAt(j)));
    else
      ++j;

    tok.add(s.substring(i, j));
    i = j;
  }
  
  if ((tok.size() % 2) == 0) tok.add("");
  return tok;
}

static boolean booleanValue(Object o) {
  return eq(true, o);
}
static List<String> regexpAll(String pattern, String text) {
  List<String> matches = new ArrayList<String>();
  Matcher matcher = Pattern.compile(pattern).matcher(text);
  while (matcher.find())
    matches.add(matcher.group());
  return matches;
}
static Map synchroHashMap() {
  return Collections.synchronizedMap(new HashMap());
}



static String getType(Object o) {
  return getClassName(o);
}
static boolean isJavaIdentifier(String s) {
  if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0)))
    return false;
  for (int i = 1; i < s.length(); i++)
    if (!Character.isJavaIdentifierPart(s.charAt(i)))
      return false;
  return true;
}
static <A> int indexOf(List<A> l, A a, int startIndex) {
  if (l == null) return -1;
  for (int i = startIndex; i < l(l); i++)
    if (eq(l.get(i), a))
      return i;
  return -1;
}

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

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

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

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

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


static class TimedCache<A> {
  long timeout;
  A value;
  long set;
  
  // stats
  int stores, fails, hits;

  // 0 = no timeout  
  TimedCache(double timeoutSeconds) {
    timeout = toMS(timeoutSeconds);
  }
  
  synchronized A set(A a) {
    ++stores;
    value = a;
    set = now();
    return a;
  }
  
  synchronized boolean has() {
    clean();
    if (set != 0) {
      ++hits; return true;
    }
    ++fails; return false;
  }
  
  synchronized A get() {
    clean();
    if (set != 0) ++hits; else ++fails;
    return value;
  }
  
  synchronized A get(Object makerFunction) {
    if (has()) return getNoClean();
    A a = (A) ( callF(makerFunction));
    return set(a);
  }
  
  synchronized A getNoClean() {
    return value;
  }
  
  // clear if timed out
  synchronized void clean() {
    if (timeout > 0 && now() > set+timeout) clear();
  }
  
  // clear now
  synchronized void clear() {
    set = 0;
    value = null;
  }
  
  synchronized String stats() {
    return "Stores: " + stores + ", hits: " + hits + ", fails: " + fails;
  }
}

  static abstract class DialogIO {
    String line;
    boolean eos;
    
    abstract String readLineImpl();
    abstract boolean isStillConnected();
    abstract void sendLine(String line);
    abstract boolean isLocalConnection();
    abstract Socket getSocket();
    abstract void close();
    
    int getPort() { return getSocket().getPort(); }
    
    boolean helloRead;
    
    String readLineNoBlock() {
      String l = line;
      line = null;
      return l;
    }
    
    boolean waitForLine() { try {
 
      if (line != null) return true;
      //print("Readline");
      line = readLineImpl();
      //print("Readline done: " + line);
      if (line == null) eos = true;
      return line != null;
    
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
    
    String readLine() {
      waitForLine();
      helloRead = true;
      return readLineNoBlock();
    }
    
    String ask(String s, Object... args) {
      if (!helloRead) readLine();
      if (args.length != 0) s = format3(s, args);
      sendLine(s);
      return readLine();
    }
    
    String askLoudly(String s, Object... args) {
      if (!helloRead) readLine();
      if (args.length != 0) s = format3(s, args);
      print("> " + s);
      sendLine(s);
      String answer = readLine();
      print("< " + answer);
      return answer;
    }
    
    void pushback(String l) {
      if (line != null)
        throw fail();
      line = l;
      helloRead = false;
    }
  }
  
  static abstract class DialogHandler {
    abstract void run(DialogIO io);
  }

static long toMS(double seconds) {
  return (long) (seconds*1000);
}
static void set(Object o, String field, Object value) {
  if (o instanceof Class) set((Class) o, field, value);
  else try {
    Field f = set_findField(o.getClass(), field);
    smartSet(f, o, value);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

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

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

static String readLine() {
  return (String) call(getJavaX(), "readLine");
}


static Class __javax;

static Class getJavaX() {
  return __javax;
}
static void smartSet(Field f, Object o, Object value) throws Exception {
  f.setAccessible(true);
  
  // take care of common case (long to int)
  if (f.getType() == int.class && value instanceof Long)
    value = ((Long) value).intValue();
    
  f.set(o, value);
}

}