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 android.app.*;
import android.content.*;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.widget.Button;
import android.widget.TextView;
import android.util.Log;
import android.media.*;
import android.app.Activity;
import android.widget.*;
import android.graphics.*;
import android.app.Activity;
import android.widget.*;
import android.graphics.*;
import android.app.*;
import android.media.*;
import android.net.*;
import android.app.Activity;
import android.app.Activity;
import android.speech.tts.*;
import android.view.View;
import android.app.Activity;
import android.speech.tts.*;
import android.content.Context;
public class main {

  static SpeechRecognizer sr;
  static final String TAG = "MyStt3Activity";
  static String language = "de-DE";
  static int extraResults = 1;
  
  static String voice = "Leopold";
  static boolean fastSynthesis = false; // use device voice (faster)
  static boolean noSpeech = false; // disable speech output
  
  static List<String> history = new ArrayList<String>();
   
  static void leoMain() {
    String hello = null;
    
    /*if (args.length != 0 && args[0].equals("nogfx"))
      setOpt(getMainClass(), "showPicture", false);*/
    
    try {
      history.add("*");
      //hello = callStaticAnswerMethod("*", history);
      if (hello == null) hello = "hallo";
    } catch (Throwable e) {
      e.printStackTrace();
      return;
    }

    say(hello);
    callOpt(getMainClass(), "happy");
      
    androidUI(new Runnable() { public void run() { try { 
      //androidMuteAudio(androidActivity());
      newRecognizer();
    
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } });
    sleep();
  }
  
  static void newRecognizer() {
    sr = SpeechRecognizer.createSpeechRecognizer(androidActivity());
    sr.setRecognitionListener(new listener());        
    recog();
  }

  static class listener implements RecognitionListener {
    public void onReadyForSpeech(Bundle params) {
      callOpt(getMainClass(), "setBorderColor", 0xFF66FF66);
      print("SAG WAS.");
    }
    
    public void onBeginningOfSpeech() {
      print("User talks");
      callOpt(getMainClass(), "oh");
      androidMuteAudio(); // Mute now, so we don't hear the end-of-speech sound
    }
    
    public void onRmsChanged(float rmsdB) {}
    public void onBufferReceived(byte[] buffer) {}
    
    public void onEndOfSpeech() {
      print("onEndOfSpeech");
      callOpt(getMainClass(), "setBorderColor", 0xFFFFFFFF);
    }
    
    public void onError(int error) {
       print( "error " +  error); // screw the errors!
       try {
         sr.destroy();
       } catch (Throwable e) {
         print(e);
       }
       newRecognizer();
       callOpt(getMainClass(), "happy");
    }
    
    public void onResults(Bundle results) {
      print("onResults " + results);
      ArrayList<String> data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
      final String s = data.get(0);
      print("Ich habe geh\u00f6rt: " + quote(s));
      //print("I heard: " +structure(data));
  
      // TODO: fix the java strings umlaut problem
       
      final boolean goodbye = match3("goodbye", s) || match3("bye", s) || match3("tsch\u00fcss", s) || match3("tsch\u00fcss ...", s);
      
      { Thread _t_0 = new Thread() {
public void run() { try { /* pcall 1*/ 
        // get answer
        
        history.add(s);
        
        String answer;
        try {
          answer = goodbye ? "tsch\u00fcss" : callStaticAnswerMethod(s, history);
        } catch (Throwable e) {
          e.printStackTrace();
          appendToFile(getProgramFile("errors.txt"), getTheStackTrace(e));
          answer = "Fehler";
        }
        
        if (answer != null)
          say(answer);
          
        androidUI(new Runnable() { public void run() { try { 
          if (goodbye) {
            print("\nGOODBYE!");
            sr.destroy();
            
            callOpt(getMainClass(), "disappear");
          } else {
            sr.stopListening();
            //newRecognizer(); // always make a new one - gives endless errors
            recog();
          }
        
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } });
      /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } }
};
_t_0.start(); } // end of thread
    }
    
    public void onPartialResults(Bundle partialResults) {
      print("onPartialResults");
    }
    
    public void onEvent(int eventType, Bundle params) {
      print("onEvent" + eventType);
    }
  }
   
  static void recog() {
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);        
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
    intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");

    intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, extraResults); 
    
    // customize recognition time settings
    callOpt(mc(), "recogTimeSettings", intent);
    
    sr.startListening(intent);
    //print("started listening");
  }
  
  static void say(String s) {
    history.add(s);
    androidUnmuteAudio(androidActivity());
    if (!noSpeech) {
      if (fastSynthesis) {
        androidSayInGerman(s);
      } else {
        File mp3 = new File(getProgramDir(), "bla.mp3");
        makeSpeechCereproc(s, voice, mp3);
        androidPlayMp3(androidActivity(), mp3);
      }
    }
    //androidMuteAudio();
  }
 // Leopold
  static boolean showPicture = true; // global switch. if false, you get the normal text display instead of the smiley
  
  static List<String> emotions = litlist(
    "#1001283", "happy",
    "#1001284", "unhappy",
    "#1001285", "oh",
    "#1001286", "bored",
    "#1001287", "wide mouth");
    
  static int borderColor = 0xFFFFFFFF;
  static String lastEmotion;
    
  static void emo(String emotion) {
    if (!showPicture) return;
    int i;
    for (i = 0; i < emotions.size(); i += 2)
      if (emotions.get(i+1).equalsIgnoreCase(emotion))
        break;
    if (i >= emotions.size()) {
      print("Emotion not found: " + emotion);
      // use the last one from the list as default
      i -= 2;
    }
    lastEmotion = emotions.get(i+1);
    androidShowFullScreenImage(emotions.get(i), borderColor);
  }
  
  static void setBorderColor(int color) {
    if (color != borderColor) {
      borderColor = color;
      if (lastEmotion != null)
        emo(lastEmotion);
    }
  }
      
  static void happy() { emo("happy"); }
  static void unhappy() { emo("unhappy"); }
  static void oh() { emo("oh"); }
  static void bored() { emo("bored"); }
  static void wideMouth() { emo("wide mouth"); }
  
  static void disappear() {
    if (!showPicture) return;
    happy();
    androidLater(1000, new Runnable() { public void run() { try { 
      androidShowFullScreenColor(0xFFFFFFFF);
      androidLater(1000, new Runnable() { public void run() { try { 
        System.exit(0); // totally unrecommended but works
      
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } });
    
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } });
  }
  
 // Emoticons
static String answer(String s) {
  return s;
} // Logic (repeat input)

public static void main(String[] args) throws Exception {
  noSpeech = true; // Just recognition, don't talk
  showPicture = false; // Let us see the text output
  leoMain();
}

static void recogTimeSettings(Intent intent) {
  print("setting speech params");
  // 60 second minimum speech length
  intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 60000);
  
  // Stop listening after pause of 1 second
  //intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS, 1000);
  //intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, 1000);


}

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 File getProgramFile(String progID, String fileName) {
  if (new File(fileName).isAbsolute())
    return new File(fileName);
  return new File(getProgramDir(progID), fileName);
}

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

  // class Matches is added by #752
 
  static boolean match3(String pat, String s) {
    return match3(pat, s, null);
  }
  
  static boolean match3(String pat, String s, Matches matches) {
    if (s == null) return false;
    return match3(pat, parse3(s), matches);
  }
    
  static boolean match3(String pat, List<String> toks, Matches matches) {
    List<String> tokpat = parse3(pat);
    return match3(tokpat,toks,matches);
  }

  static boolean match3(List<String> tokpat, List<String> toks, Matches matches) {

    String[] m = match2(tokpat, toks);
    //print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m));
    if (m == null)
      return false;
    else {
      if (matches != null) matches.m = m;
      return true;
    }
  }
static String getTheStackTrace(Throwable throwable) {
  StringWriter writer = new StringWriter();
  throwable.printStackTrace(new PrintWriter(writer));
  return writer.toString();
}
static void androidSayInGerman(String text) {
  androidSay(text, Locale.GERMAN);
}
static Object callOpt(Object o) {
  if (o == null) return null;
  return callF(o);
}

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

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

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

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

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

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


  static void makeSpeechCereproc(String text, String voice, File destMp3) { try {
 
    String format = "mp3";
    
    String post = "<speakExtended key='p86ffzyal3tvgqfr'><voice>" + htmlencode(voice) + "</voice><text>" + /*htmlencode*/(text) + "</text><audioFormat>" + format + "</audioFormat>\n" +
"</speakExtended>";

    String url = "https://www.cereproc.com/livedemo.php";
    URL _url = new URL(url);
    URLConnection conn = _url.openConnection();
    conn.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
    conn.setRequestProperty("Accept-Language", "en-US,en;q=0.8,de;q=0.6");
    conn.setRequestProperty("Cookie", "has_js=1; Drupal.visitor.liveDemo=p86ffzyal3tvgqfr; _ga=GA1.2.1406621623.1444122980; _gat=1");
    conn.setRequestProperty("Origin", "https://www.cereproc.com");
    conn.setRequestProperty("Referer", "https://www.cereproc.com/");
    conn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/44.0.2403.89 Chrome/44.0.2403.89 Safari/537.36");
    
    conn.setDoOutput(true);
    
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(post);
    writer.flush();
    
    String encoding = conn.getContentEncoding();
    //print("Encoding: " + encoding);
    
    String contentType = conn.getContentType();
    //print("Content type: " + contentType);
  
    byte[] response = loadBinaryPage(conn);
    //print("Bytes read: " + response.length);
    
    if ("gzip".equals(encoding))
      response = gunzipBinaryData(response);
      
    //print("Bytes unpacked: " + response.length);
    String s = new String(response, "UTF-8");
    //print(s);
    
    String oggUrl = null;
    List<String> tok = htmlcoarsetok(s);
    for (int i = 1; i < tok.size(); i += 2)
      if (isTag(tok.get(i), "url")) {
        oggUrl = tok.get(i+1);
        break;
      }
    if (oggUrl == null) throw fail("No sound URL found");
    
    byte[] ogg = loadBinaryPage(oggUrl);

    saveBinaryFile(destMp3, ogg);
    //print("Saved: " + destMp3.getAbsolutePath() + " (" + ogg.length + " bytes)");
  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}

static String callStaticAnswerMethod(List bots, String s) {
  for (Object c : bots) try {
    String answer = callStaticAnswerMethod(c, s);
    if (!empty(answer)) return answer;
  } catch (Throwable e) {
    print("Error calling " + getProgramID(c));
    e.printStackTrace();
  }
  return null;
}

static String callStaticAnswerMethod(Object c, String s) {
  String answer = (String) callOpt(c, "answer", s, litlist(s));
  if (answer == null)
    answer = (String) callOpt(c, "answer", s);
  return emptyToNull(answer);
}

static String callStaticAnswerMethod(String s, List<String> history) {
  return callStaticAnswerMethod(mc(), s, history);
}

static String callStaticAnswerMethod(Object c, String s, List<String> history) {
  String answer = (String) callOpt(c, "answer", s, history);
  if (answer == null)
    answer = (String) callOpt(c, "answer", s);
  return emptyToNull(answer);
}
static void androidMuteAudio() {
  androidMuteAudio(androidActivity());
}

static void androidMuteAudio(Activity androidContext) {
  AudioManager amanager = (AudioManager) androidContext.getSystemService(Context.AUDIO_SERVICE);
  amanager.setStreamMute(AudioManager.STREAM_NOTIFICATION, true);
  amanager.setStreamMute(AudioManager.STREAM_ALARM, true);
  amanager.setStreamMute(AudioManager.STREAM_MUSIC, true);
  amanager.setStreamMute(AudioManager.STREAM_RING, true);
  amanager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
static void androidLater(final int delay, final Runnable r) {
  { Thread _t_1 = new Thread() {
public void run() { try { /* pcall 1*/ 
    sleep(delay);
    androidUI(r);
  /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } }
};
_t_1.start(); }
}
static File getProgramDir() {
  return programDir();
}

static File getProgramDir(String snippetID) {
  return programDir(snippetID);
}

static void androidShowFullScreenColor(int color) {
  ImageView iv = new ImageView(androidActivity());
  iv.setBackgroundColor(color);
  androidShow(iv);
}

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 volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile StringBuffer print_log = local_log; // might be redirected, e.g. to main bot

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

static boolean print_silent; // total mute if set

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

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

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

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

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

  static void androidShowFullScreenImage(final String imageID) {
    { /*nt*/ Thread _t_0 = new Thread("showimg") {
public void run() { /* in run */ try { /* pcall 1*/  /* in thread */ 
  
      ImageView iv = new ImageView(androidContext());
      iv.setImageBitmap(BitmapFactory.decodeFile(loadLibrary(imageID).getPath()));
      androidShow(iv);
    /* in thread */ /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } /* in run */ }
};
_t_0.start(); }
  }
  
  static void androidShowFullScreenImage(final String imageID, final int borderColor) {
    { /*nt*/ Thread _t_1 = new Thread("showimg") {
public void run() { /* in run */ try { /* pcall 1*/  /* in thread */ 
  
      ImageView iv = new ImageView(androidContext());
      iv.setBackgroundColor(borderColor);
      iv.setImageBitmap(BitmapFactory.decodeFile(loadLibrary(imageID).getPath()));
      androidShow(iv);
    /* in thread */ /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } /* in run */ }
};
_t_1.start(); }
  }

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


// do not call in ui thread.
// waits until playback done.

static void androidPlayMp3(Activity androidContext, File mp3) {
  final MediaPlayer mPlayer = MediaPlayer.create(androidContext, Uri.fromFile(mp3));
  
  final Flag done = new Flag();
  mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    public void onCompletion(MediaPlayer mp) {
      mPlayer.release();
      done.raise();
    }
  });

  mPlayer.start();
  done.waitUntilUp();
}
 // Let's just generally synchronize this to be safe.
 static synchronized void appendToFile(String path, String s) { try {
 
    new File(path).getParentFile().mkdirs();
    //print("[Logging to " + path + "]");
    Writer writer = new BufferedWriter(new OutputStreamWriter(
      new FileOutputStream(path, true), "UTF-8"));
    writer.write(s);
    writer.close();
  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
  
  static void appendToFile(File path, String s) {
    if (path != null)
      appendToFile(path.getPath(), s);
  }

static Object mc() {
  return getMainClass();
}
static <A> ArrayList<A> litlist(A... a) {
  return new ArrayList<A>(Arrays.asList(a));
}
static void androidUI( final Runnable r) {
  
    androidActivity ().runOnUiThread(r);
 
}
  
  static void androidUnmuteAudio(Activity androidContext) {
    AudioManager amanager = (AudioManager) androidContext.getSystemService(Context.AUDIO_SERVICE);
    amanager.setStreamMute(AudioManager.STREAM_NOTIFICATION, false);
    amanager.setStreamMute(AudioManager.STREAM_ALARM, false);
    amanager.setStreamMute(AudioManager.STREAM_MUSIC, false);
    amanager.setStreamMute(AudioManager.STREAM_RING, false);
    amanager.setStreamMute(AudioManager.STREAM_SYSTEM, false);
  }

static Activity androidActivity() {
  return (Activity) androidContext_gen();
}


// match2 matches multiple "*" (matches a single token) wildcards and zero or one "..." wildcards (matches multiple tokens)

static String[] match2(List<String> pat, List<String> tok) {
  // standard case (no ...)
  int i = pat.indexOf("...");
  if (i < 0) return match2_match(pat, tok);
  
  pat = new ArrayList<String>(pat); // We're modifying it, so copy first
  pat.set(i, "*");
  while (pat.size() < tok.size()) {
    pat.add(i, "*");
    pat.add(i+1, ""); // doesn't matter
  }
  
  return match2_match(pat, tok);
}

static String[] match2_match(List<String> pat, List<String> tok) {
  List<String> result = new ArrayList<String>();
  if (pat.size() != tok.size()) {
    /*if (debug)
      print("Size mismatch: " + structure(pat) + " vs " + structure(tok));*/
    return null;
  }
  for (int i = 1; i < pat.size(); i += 2) {
    String p = pat.get(i), t = tok.get(i);
    /*if (debug)
      print("Checking " + p + " against " + t);*/
    if (eq(p, "*"))
      result.add(t);
    else if (!equalsIgnoreCase(unquote(p), unquote(t))) // bold change - match quoted and unquoted now
      return null;
  }
  return result.toArray(new String[result.size()]);
}

// TODO: process CDATA?

static List<String> htmlcoarsetok(String s) {
  List<String> tok = new ArrayList<String>();
  int l = s.length();
  
  int i = 0;
  while (i < l) {
    int j = i;
    char c;
    
    // scan for non-tags
    while (j < l) {
      if (s.charAt(j) != '<')
        // regular character
        ++j;
      else if (s.substring(j, Math.min(j+4, l)).equals("<!--")) {
        // HTML comment
        j = j+4;
        do ++j; while (j < l && !s.substring(j, Math.min(j+3, l)).equals("-->"));
        j = Math.min(j+3, l);
      } else
        // it's a tag
        break;
    }
    tok.add(s.substring(i, j));
    i = j;
    if (i >= l) break;
    c = s.charAt(i);

    // scan for tags
    if (c == '<') {
      ++j;
      
      while (j < l && s.charAt(j) != '>') ++j; // TODO: strings?
      if (j < l) ++j;
    }

    tok.add(s.substring(i, j));
    i = j;
  }
  
  if ((tok.size() % 2) == 0) tok.add("");
  return tok;
}
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 Object callF(Object f, Object... args) {
  return callFunction(f, args);
}
  static List<String> parse3(String s) {
    return dropPunctuation(javaTokPlusPeriod(s));
  }
  /** writes safely (to temp file, then rename) */
  public static void saveBinaryFile(String fileName, byte[] contents) throws IOException {
    File file = new File(fileName);
    File parentFile = file.getParentFile();
    if (parentFile != null)
      parentFile.mkdirs();
    String tempFileName = fileName + "_temp";
    FileOutputStream fileOutputStream = new FileOutputStream(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);
  }

  static void saveBinaryFile(File fileName, byte[] contents) {
    try {
      saveBinaryFile(fileName.getPath(), contents);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
static boolean empty(Collection c) {
  return isEmpty(c);
}

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

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

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

static boolean empty(Object o) {
  if (o instanceof Collection) return empty((Collection) o);
  if (o instanceof String) return empty((String) o);
  if (o instanceof Map) return empty((Map) o);
  if (o instanceof Object[]) return empty((Object[]) o);
  throw fail("unknown type for 'empty': " + getType(o));
}
static File programDir_mine; // set this to relocate program's data

static File programDir() {
  return programDir(getProgramID());
}

static File programDir(String snippetID) {
  if (programDir_mine != null && sameSnippetID(snippetID, programID()))
    return programDir_mine;
  return new File(javaxDataDir(), formatSnippetID(snippetID));
}

static Object androidContext_gen() {
  return getAndroidContext_gen();
}
// 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 Context androidContext() {
  return getAndroidContext();
}
static File loadLibrary(String snippetID) {
  return loadBinarySnippet(snippetID);
}
static byte[] loadBinaryPage(String url) { try {
 
  return loadBinaryPage(new URL(url).openConnection());

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

public static byte[] loadBinaryPage(URLConnection con) { try {
 
  //setHeaders(con);
  ByteArrayOutputStream buf = new ByteArrayOutputStream();
  InputStream inputStream = con.getInputStream();
  int n = 0;
  while (true) {
    int ch = inputStream.read();
    if (ch < 0)
      break;
    buf.write(ch);
    if (++n % 100000 == 0)
      System.err.println("  " + n + " bytes loaded.");
  }
  inputStream.close();
  return buf.toByteArray();

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


static boolean androidSay_keepEngine = false;

// locale = language, e.g. Locale.GERMAN
static void androidSay(final String text, final Locale locale) {
  if (androidSay_keepEngine) {
    androidSay_keepEngine(text, locale);
    return;
  }
  
  final Flag flag = new Flag();
  
  final TextToSpeech[] tts = new TextToSpeech[1];
  tts[0] = new TextToSpeech(androidContext(), new TextToSpeech.OnInitListener() {
    public void onInit(int status) {
      try {
        if (status != TextToSpeech.SUCCESS)
          throw fail("Speech engine initialization failed");
  
        int result = tts[0].setLanguage(locale);
        if (result == TextToSpeech.LANG_MISSING_DATA
          || result == TextToSpeech.LANG_NOT_SUPPORTED)
          throw fail("German is not supported");
  
        result = tts[0].setOnUtteranceProgressListener(new UtteranceProgressListener() {
          public void onDone(String utteranceId) {
            tts[0].shutdown();
            flag.raise();
          }
  
          public void onError(String utteranceId) {
            print("onError");
            tts[0].shutdown();
            flag.raise();
          }
  
          public void onStart(String utteranceId) {
          }
        });
        
        if (result != TextToSpeech.SUCCESS)
          print("Could not set listener");
            
        print(text);
        HashMap params = new HashMap();
        params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, randomID(8));
        tts[0].speak(text, TextToSpeech.QUEUE_FLUSH, params);
      
      } catch (Throwable e) { e.printStackTrace(); flag.raise(); }
    }
  });
    
  flag.waitUntilUp();
}

static String emptyToNull(String s) {
  return eq(s, "") ? null : s;
}

static void androidShow(final View view) {
  androidActivity().runOnUiThread(new Runnable() { public void run() { try { 
    androidActivity().setContentView(view);
  
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } });
}
static boolean isTag(String token, String tag) {
  return token.regionMatches(true, 0, "<" + tag + " ", 0, tag.length()+2)
    || token.regionMatches(true, 0, "<" + tag + ">", 0, tag.length()+2);
}
  // automagically encode a whole map (keys+values)
  static Map htmlencode(Map o) {
    HashMap bla = new HashMap();
    for (Object key : keys(o)) {
      Object value = o.get(key);
      bla.put(htmlencode(key), htmlencode(value));
    }
    return bla;
  }

  static String htmlencode(Object o) {
    return htmlencode(string(o));
  }
  
  static 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 == '&') {
            out.append("&#");
            out.append((int) c);
            out.append(';');
        } else {
            out.append(c);
        }
    }
    return out.toString();
  }
  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 byte[] gunzipBinaryData(byte[] data) { try {
 
  InputStream fis = new ByteArrayInputStream(data);
  GZIPInputStream gis = new GZIPInputStream(fis);
  ByteArrayOutputStream fos = new ByteArrayOutputStream();
  byte[] buffer = new byte[1024];
  int len;
  while((len = gis.read(buffer)) != -1){
      fos.write(buffer, 0, len);
  }
  fis.close();
  fos.close();
  return fos.toByteArray();

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


static Object callFunction(Object f, Object... args) {
  if (f == null) return null;
  if (f instanceof Runnable) {
    ((Runnable) f).run();
    return null;
  } else if (f instanceof String)
    return call(mc(), (String) f, args);
  else
    return call(f, "get", args);
  //else throw fail("Can't call a " + getClassName(f));
}
static String formatSnippetID(String id) {
  return "#" + parseSnippetID(id);
}

static String formatSnippetID(long id) {
  return "#" + id;
}
static boolean equalsIgnoreCase(String a, String b) {
  return a == null ? b == null : a.equalsIgnoreCase(b);
}

static TextToSpeech androidSay_keepEngine_tts;

// TODO: better way to sync than synchronizing on main class

static synchronized void androidSay_keepEngine(final String text, final Locale locale) {
  final Flag flag = new Flag();
  
  if (androidSay_keepEngine_tts == null)
    androidSay_keepEngine_tts = new TextToSpeech(androidContext(), new TextToSpeech.OnInitListener() {
      public void onInit(int status) {
        try {
          if (status != TextToSpeech.SUCCESS)
            throw fail("Speech engine initialization failed");
    
          androidSay_keepEngine_go(text, locale, flag);
        } catch (Throwable e) { e.printStackTrace(); flag.raise(); }
      }
    });
  else
    androidSay_keepEngine_go(text, locale, flag);
    
  flag.waitUntilUp();
}

static void androidSay_keepEngine_go(String text, Locale locale, final Flag flag) {
  int result = androidSay_keepEngine_tts.setLanguage(locale);
  if (result == TextToSpeech.LANG_MISSING_DATA
    || result == TextToSpeech.LANG_NOT_SUPPORTED)
    throw fail("German is not supported");
    
  /*if (empty(text)) { // Empty text = Initialize engine only
    flag.raise();
    ret;
  }*/

  result = androidSay_keepEngine_tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
    public void onDone(String utteranceId) {
      flag.raise();
    }

    public void onError(String utteranceId) {
      print("onError");
      flag.raise();
    }

    public void onStart(String utteranceId) {
    }
  });
  
  if (result != TextToSpeech.SUCCESS)
    print("Could not set listener");
      
  print("[speech output] " + text);
  HashMap params = new HashMap();
  params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, randomID(8));
  androidSay_keepEngine_tts.speak(text, TextToSpeech.QUEUE_FLUSH, params);
}
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 Object androidContext;

static Object getAndroidContext_gen() {
  return androidContext;
}
static String getType(Object o) {
  return getClassName(o);
}
// 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 File loadBinarySnippet(String snippetID) { try {
 
  long id = parseSnippetID(snippetID);
  File f = DiskSnippetCache_getLibrary(id);
  if (f == null) {
    byte[] data = loadDataSnippetImpl(snippetID);
    DiskSnippetCache_putLibrary(id, data);
    f = DiskSnippetCache_getLibrary(id);
  }
  return f;

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static File javaxDataDir_dir; // can be set to work on different base dir

static File javaxDataDir() {
  return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
}
static String string(Object o) {
  return String.valueOf(o);
}
static <A, B> Set<A> keys(Map<A, B> map) {
  return map.keySet();
}

static Set keys(Object map) {
  return keys((Map) map);
}
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 BitSet unnull(BitSet b) {
  return b == null ? new BitSet() : b;
}

static Context getAndroidContext() {
  return (Context) getAndroidContext_gen();
}
  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 programID() {
  return getProgramID();
}
static List<String> dropPunctuation_keep = litlist("*", "<", ">");

static List<String> dropPunctuation(List<String> tok) {
  tok = new ArrayList<String>(tok);
  for (int i = 1; i < tok.size(); i += 2) {
    String t = tok.get(i);
    if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !dropPunctuation_keep.contains(t)) {
      tok.set(i-1, tok.get(i-1) + tok.get(i+1));
      tok.remove(i);
      tok.remove(i);
      i -= 2;
    }
  }
  return tok;
}

static String dropPunctuation(String s) {
  return join(dropPunctuation(nlTok(s)));
}
static 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 boolean isEmpty(Collection c) {
  return c == null || c.isEmpty();
}

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

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

static boolean isEmpty(Map map) {
  return map == null || map.isEmpty();
}
static boolean sameSnippetID(String a, String b) {
  return a != null && b != null && parseSnippetID(a) == parseSnippetID(b);
}
static int randomID_defaultLength = 12;

static String randomID(int length) {
  return makeRandomID(length);
}

static String randomID() {
  return randomID(randomID_defaultLength);
}
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 Object getBot(String botID) {
  return callOpt(getMainBot(), "getBot", botID);
}

  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 String getClassName(Object o) {
  return o == null ? "null" : o.getClass().getName();
}
  
  // Data files are immutable, use centralized cache
public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
  File file = new File(getGlobalCache(), "data_" + snippetID + ".jar");
  return file.exists() ? file : null;
}

public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
  saveBinaryFile(new File(getGlobalCache(), "data_" + snippetID).getPath() + ".jar", data);
}

static byte[] loadDataSnippetImpl(String snippetID) throws IOException {
  byte[] data;
  try {
    URL url = new URL("http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_"
      + parseSnippetID(snippetID) + "&contentType=application/binary");
    System.err.println("Loading library: " + url);
    try {
      data = loadBinaryPage(url.openConnection());
    } catch (RuntimeException e) {
      data = null;
    }
    
    if (data == null || data.length == 0) {
      url = new URL("http://data.tinybrain.de/blobs/"
        + parseSnippetID(snippetID));
      System.err.println("Loading library: " + url);
      data = loadBinaryPage(url.openConnection());
    }
    System.err.println("Bytes loaded: " + data.length);
  } catch (FileNotFoundException e) {
    throw new IOException("Binary snippet #" + snippetID + " not found or not public");
  }
  return data;
}
public static long parseSnippetID(String snippetID) {
  long id = Long.parseLong(shortenSnippetID(snippetID));
  if (id == 0) throw fail("0 is not a snippet ID");
  return id;
}
static String _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();
}
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 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 List<String> nlTok(String s) {
  return javaTokPlusPeriod(s);
}


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

static Object getMainBot() {
  return mainBot;
}
static File getGlobalCache() {
  File file = new File(userHome(), ".tinybrain/snippet-cache");
  file.mkdirs();
  return file;
}

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

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


static 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 String dropSuffix(String suffix, String s) {
  return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}


static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(boolean[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(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
}



/** this class is fully thread-safe */
static class Flag {
  private boolean up;

  /** returns true if flag was down before */
  public synchronized boolean raise() {
    return doRaise();
  }

  private synchronized boolean doRaise() {
    if (!up) {
      up = true;
      notifyAll();
      return true;
    } else
      return false;
  }

  public synchronized void waitUntilUp() {
    if (!up) {
      try {
        wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

  public synchronized void waitUntilUp(long timeout) {
    if (!up) {
      try {
        wait(timeout);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

  public synchronized boolean isUp() {
    return up;
  }

  public String toString() {
    return isUp() ? "up" : "down";
  }

  // currently does a semi-active wait with latency = 50 ms
  public void waitForThisOr(Flag otherFlag) { try {
 
    while (!isUp() && !otherFlag.isUp())
      Thread.sleep(50);
  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
}

  static class Matches {
    String[] m;
    String get(int i) { return i < m.length ? m[i] : null; }
    String unq(int i) { return unquote(get(i)); }
    String fsi(int i) { return formatSnippetID(unq(i)); }
    String fsi() { return fsi(0); }
    String tlc(int i) { return unq(i).toLowerCase(); }
    boolean bool(int i) { return "true".equals(unq(i)); }
    String rest() { return m[m.length-1]; } // for matchStart
    int psi(int i) { return Integer.parseInt(unq(i)); }
  }


static String fsi(String id) {
  return formatSnippetID(id);
}
// 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;
}

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

static Class get_dynamicObject = findClass("DynamicObject");

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

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

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

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

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

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


static RuntimeException asRuntimeException(Throwable t) {
  return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
// currently finds only inner classes of class "main"
// returns null on not found
// this is the simple version that is not case-tolerant
static Class findClass(String name) {
  if (!isJavaIdentifier(name)) return null;
  try {
    return Class.forName("main$" + name);
  } catch (ClassNotFoundException e) {
    return null;
  }
}


static 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 void printStackTrace(Throwable e) {
  // we go to system.out now - system.err is nonsense
  print(getStackTrace(e));
}

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

static void printStackTrace(String indent, Throwable e) {
  if (endsWithLetter(indent)) indent += " ";
  printIndent(indent, getStackTrace(e));
}


static void printIndent(Object o) {
  print(indentx(str(o)));
}

static void printIndent(String indent, Object o) {
  print(indentx(indent, str(o)));
}
static String getStackTrace(Throwable throwable) {
  StringWriter writer = new StringWriter();
  throwable.printStackTrace(new PrintWriter(writer));
  return writer.toString();
}
static boolean endsWithLetter(String s) {
  return nempty(s) && isLetter(last(s));
}


static String str(Object o) {
  return String.valueOf(o);
}
static String indentx(String s) {
  return dropSuffix(repeat(' ', indent_default), indent(indent_default, s));
}

static String indentx(String indent, String s) {
  return dropSuffix(indent, indent(indent, s));
}
static <A> A last(List<A> l) {
  return l.isEmpty() ? null : l.get(l.size()-1);
}

static char last(String s) {
  return empty(s) ? '#' : s.charAt(l(s)-1);
}
static boolean isLetter(char c) {
  return Character.isLetter(c);
}


static int indent_default = 2;

static String indent(int indent) {
  return repeat(' ', indent);
}

static String indent(int indent, String s) {
  return indent(repeat(' ', indent), s);
}

static String indent(String indent, String s) {
  return indent + s.replace("\n", "\n" + indent);
}

static String indent(String s) {
  return indent(indent_default, s);
}

static List<String> indent(String indent, List<String> lines) {
  List<String> l = new ArrayList<String>();
  for (String s : lines)
    l.add(indent + s);
  return l;
}
  static String repeat(char c, int n) {
    n = max(n, 0);
    char[] chars = new char[n];
    for (int i = 0; i < n; i++)
      chars[i] = c;
    return new String(chars);
  }

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



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

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

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

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

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

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

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

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

}