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


public static void main(final String[] args) throws Exception {
  //set loadPage_debug;
  String baseURL = "http://legend.freebooks2017.org/Legend_1/";
  int page = 1;
  
  while (licensed()) {
    String html = loadPageWithUserAgent(pageURL(baseURL, page), "Mac Safari");
    List<String> paragraphs = map("htmldecode_dropAllTags", contentsOfPTags(html));
    //printNumberedLines(paragraphs);
    print("\n#PAGE " + page + "#");
    for (String p : paragraphs) {
      print("#P#");
      print(p);
    }
    ++page;
    if (!html.contains("index_" + page + ".html"))
      break;
  }
}

static String pageURL(String baseURL, int page) {
  baseURL = addSlash(baseURL);
  if (page <= 0) throw fail("woot");
  else if (page == 1) return baseURL;
  else return baseURL + "index_" + page + ".html";
}


static String loadPageWithUserAgent(String url, String userAgent) { try {
  URL tURL = new URL(url);
  URLConnection conn = tURL.openConnection();
  conn.setRequestProperty("User-Agent", userAgent);
  loadPage_anonymous = true;
  return loadPage(conn, tURL);
} catch (Exception __e) { throw rethrow(__e); } }
static RuntimeException fail() {
  throw new RuntimeException("fail");
}

static RuntimeException fail(Throwable e) {
  throw asRuntimeException(e);
}

static RuntimeException fail(Object msg) {
  throw new RuntimeException(String.valueOf(msg));
}

static RuntimeException fail(String msg) {
  throw new RuntimeException(unnull(msg));
}
 
static RuntimeException fail(String msg, Throwable innerException) {
  throw new RuntimeException(msg, innerException);
}

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 volatile ThreadLocal<F1<String, Boolean>> print_byThread; // special handling by thread

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

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

static void print_noNewLine(String s) {
  if (print_byThread != null) {
    F1<String, Boolean> f = print_byThread.get();
    if (f != null)
      if (isFalse(f.get(s))) return;
  }

  print_raw(s);
}

static void print_raw(String s) {
  s = fixNewLines(s);
  // 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);
}

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 List<String> contentsOfPTags(String html) {
  List<String> l = new ArrayList();
  for (List<String> tag : findContainerTag(htmlTok(html), "p"))
    l.add(trim(join(contentsOfContainerTag(tag))));
  return l;
}

static String addSlash(String s) {
  return empty(s) || s.endsWith("/") ? s : s + "/";
}
static Map<Thread, Boolean> _registerThread_threads = synchroMap(new WeakHashMap());

static Thread _registerThread(Thread t) {
  _registerThread_threads.put(t, true);
  return t;
}
static List map(Iterable l, Object f) {
  return map(f, l);
}

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

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

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

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


static String fixNewLines(String s) {
  return s.replace("\r\n", "\n").replace("\r", "\n");
}
static Map synchroMap() {
  return synchroHashMap();
}

static <A, B> Map<A, B> synchroMap(Map<A, B> map) {
  return Collections.synchronizedMap(map);
}
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());

// always returns true
static boolean ping() {
  if (ping_pauseAll || ping_anyActions) ping_impl();
  return true;
}

// returns true when it slept
static boolean ping_impl() { try {
  if (ping_pauseAll && !isAWTThread()) {
    do
      Thread.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;
} catch (Exception __e) { throw rethrow(__e); } }
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 WeakHashMap<Class, ArrayList<Method>> callF_cache = new WeakHashMap();

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

// used internally
static ArrayList<Method> callF_makeCache(Class c) {
  ArrayList<Method> l = new ArrayList();
  Class _c = c;
  do {
    for (Method m : _c.getDeclaredMethods())
      if (m.getName().equals("get")) {
        m.setAccessible(true);
        l.add(m);
      }
    if (!l.isEmpty()) break;
    _c = _c.getSuperclass();
  } while (_c != null);
  callF_cache.put(c, l);
  return l;
}
static List<String> htmlTok(String s) {
  return htmlcoarsetok(s);
}
  static ThreadLocal<String> loadPage_charset = new ThreadLocal();
  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
  static ThreadLocal<Boolean> loadPage_silent = new ThreadLocal();

  public static String loadPageSilently(String url) { try {
    return loadPageSilently(new URL(loadPage_preprocess(url)));
  } catch (Exception __e) { throw rethrow(__e); } }

  public static String loadPageSilently(URL url) { try {
    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;
        if (loadPageThroughProxy_enabled) {
          print("Trying proxy because of: " + e);
          try {
            return loadPageThroughProxy(str(url));
          } catch (Throwable e2) {
            print("  " + exceptionToStringShort(e2));
          }
        } else if (loadPage_debug)
          print(e);
        sleepSeconds(1);
      }
    throw e;
  } catch (Exception __e) { throw rethrow(__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);
    if (!isTrue(loadPage_silent.get()))
      print("Loading: " + hideCredentials(url));
    return loadPageSilently(new URL(url));
  } catch (Exception __e) { throw rethrow(__e); } }
  
  public static String loadPage(URL url) {
    print("Loading: " + hideCredentials(url.toExternalForm()));
    return loadPageSilently(url);
  }

  public static String loadPage(URLConnection con, URL url) throws IOException {
    try {
      if (!loadPage_anonymous)
        setHeaders(con);
      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);
    String match = m.matches() ? m.group(1) : null;
    if (loadPage_debug)
      print("loadPage: contentType=" + contentType + ", match: " + match);
    /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
    return or(match, "ISO-8859-1");
  }

static boolean isFalse(Object o) {
  return eq(false, o);
}
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;
}

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

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

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

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

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

static boolean empty(float[] a) { return a == null || a.length == 0; }
static RuntimeException asRuntimeException(Throwable t) {
  return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static String trim(String s) { return s == null ? null : s.trim(); }
static String trim(StringBuilder buf) { return buf.toString().trim(); }
static String trim(StringBuffer buf) { return buf.toString().trim(); }
static Object mc() {
  return getMainClass();
}
// tok must come from htmlTok
// returns all container tags found (including content) as CNC
// honors nested tags correctly
static List<List<String>> findContainerTag(List<String> tok, String tag) {
  List < List < String > > l = new ArrayList();
  for (int i = 1; i < l(tok); i += 2)
    if (isOpeningTag(tok.get(i), tag)) {
      int j, level = 1;
      for (j = i+2; j < tok.size(); j += 2)
        if (isOpeningTag(tok.get(j), tag))
          ++level;
        else if (isTag(tok.get(j), "/" + tag)) {
          --level;
          if (level == 0) {
            l.add(tok.subList(i-1, j+2)); // actual CNC
            break;
          }
        }
      i = j;
    }
  return l;
}

static List<List<String>> findContainerTag(String html, String tag) {
  return findContainerTag(htmlTok(html), tag);
}

  public static String join(String glue, Iterable<String> strings) {
    if (strings == null) return "";
    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);
  }

// drop opening and closing tag, return new CNC
static List<String> contentsOfContainerTag(List<String> tok) {
  return tok == null ? null : subList(tok, 2, l(tok)-2);
}

static List<String> contentsOfContainerTag(List<String> tok, String tagName) {
  return contentsOfContainerTag(first(findContainerTag(tok, tagName)));
}


// 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 final HashMap<String, List<Method>> callMC_cache = new HashMap();
static String callMC_key;
static Method callMC_value;

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

static Object callMC(String method, Object... args) { try {
  Method me;
  synchronized(callMC_cache) {
    me = method == callMC_key ? callMC_value : null;
  }
  if (me != null) return callMC_value.invoke(null, args);

  List<Method> m;
  synchronized(callMC_cache) {
    m = callMC_cache.get(method);
  }
  if (m == null) {
    if (callMC_cache.isEmpty()) {
      callMC_makeCache();
      m = callMC_cache.get(method);
    }
    if (m == null) throw fail("Method named " + method + " not found in main");
  }
  int n = m.size();
  if (n == 1) {
    me = m.get(0);
    synchronized(callMC_cache) {
      callMC_key = method;
      callMC_value = me;
    }
    return me.invoke(null, args);
  }
  for (int i = 0; i < n; i++) {
    me = m.get(i);
    if (call_checkArgs(me, args, false))
      return me.invoke(null, args);
  }
  throw fail("No method called " + method + " with matching arguments found in main");
} catch (Exception __e) { throw rethrow(__e); } }

static void callMC_makeCache() {
  synchronized(callMC_cache) {
    callMC_cache.clear();
    Class _c = (Class) mc(), c = _c;
    while (c != null) {
      for (Method m : c.getDeclaredMethods())
        if ((m.getModifiers() & Modifier.STATIC) != 0) {
          m.setAccessible(true);
          multiMapPut(callMC_cache, m.getName(), m);
        }
      c = c.getSuperclass();
    }
  }
}
static boolean isOpeningTag(String token, String tag) {
  return isTag(token, tag) && !token.endsWith("/>");
}

static boolean isOpeningTag(String token) {
  return token.startsWith("<")
    && token.endsWith(">")
    && !token.endsWith("/>")
    && isLetter(token.charAt(1));
}    

// TODO: test if android complains about this
static boolean isAWTThread() {
  if (isAndroid()) return false;
  if (isHeadless()) return false;
  return isAWTThread_awt();
}

static boolean isAWTThread_awt() {
  return SwingUtilities.isEventDispatchThread();
}
static Thread currentThread() {
  return Thread.currentThread();
}
static URLConnection openConnection(URL url) { try {
  ping();
  return url.openConnection();
} catch (Exception __e) { throw rethrow(__e); } }
static boolean eq(Object a, Object b) {
  return a == null ? b == null : a == b || a.equals(b);
}
static String str(Object o) {
  return o == null ? "null" : o.toString();
}

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

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

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

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

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

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


static String getType(Object o) {
  return getClassName(o);
}
static String getClassName(Object o) {
  return o == null ? "null" : o.getClass().getName();
}
static void sleepSeconds(double s) {
  if (s > 0) sleep(round(s*1000));
}
static List emptyList() {
  return new ArrayList();
  //ret Collections.emptyList();
}
static String hideCredentials(String url) {
  return url.replaceAll("&_pass=[^&]*", "&_pass=<hidden>");
}
static void setHeaders(URLConnection con) throws IOException {
  String computerID = getComputerID_quick();
  if (computerID != null) try {
    con.setRequestProperty("X-ComputerID", computerID);
    con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version"));
  } catch (Throwable e) {
    //printShortException(e);
  }
}
static Class getMainClass() {
  return main.class;
}

static Class getMainClass(Object o) { try {
  return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) { throw rethrow(__e); } }
static <A> List<A> subList(List<A> l, int startIndex) {
  return subList(l, startIndex, l(l));
}

static <A> List<A> subList(List<A> l, int startIndex, int endIndex) {
  startIndex = max(0, min(l(l), startIndex));
  endIndex = max(0, min(l(l), endIndex));
  if (startIndex > endIndex) return litlist();
  return l.subList(startIndex, endIndex);
}
static <A> A or(A a, A b) {
  return a != null ? a : b;
}
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 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 long l(File f) { return f == null ? 0 : f.length(); }

static int l(Object o) {
  return o instanceof String ? l((String) o)
    : o instanceof Map ? l((Map) o)
    : l((Collection) o); // incomplete
}




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 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);
}
static boolean isTrue(Object o) {
  if (o instanceof Boolean)
    return ((Boolean) o).booleanValue();
  if (o == null) return false;
  throw fail(getClassName(o));
}
static Map synchroHashMap() {
  return Collections.synchronizedMap(new HashMap());
}

static final boolean loadPageThroughProxy_enabled = false;

static String loadPageThroughProxy(String url) {
  return null;
}
static Object first(Object list) {
  return empty((List) list) ? null : ((List) list).get(0);
}

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

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

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

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



static Boolean isHeadless_cache;

static boolean isHeadless() {
  if (isHeadless_cache != null) return isHeadless_cache;
  if (GraphicsEnvironment.isHeadless()) return isHeadless_cache = true;
  
  // Also check if AWT actually works.
  // If DISPLAY variable is set but no X server up, this will notice.
  
  try {
    SwingUtilities.isEventDispatchThread();
    return isHeadless_cache = false;
  } catch (Throwable e) { return isHeadless_cache = true; }
}
static Object callFunction(Object f, Object... args) {
  return callF(f, args);
}
static String getComputerID_quick() {
  File file = new File(userHome(), ".tinybrain/computer-id");
  return assertNempty(loadTextFile(file.getPath(), null));
}
static <A, B> void multiMapPut(Map<A, List<B>> map, A a, B b) {
  List<B> l = map.get(a);
  if (l == null)
    map.put(a, l = new ArrayList());
  l.add(b);
}
// 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 isLetter(char c) {
  return Character.isLetter(c);
}
static void sleep(long ms) {
  ping();
  if (ms < 0) return;
  // allow spin locks
  if (isAWTThread() && ms > 100) throw fail("Should not sleep on AWT thread");
  try {
    Thread.sleep(ms);
  } catch (Exception e) { throw new RuntimeException(e); }
}

static void sleep() { try {
  print("Sleeping.");
  sleepQuietly();
} catch (Exception __e) { throw rethrow(__e); } }
static int min(int a, int b) {
  return Math.min(a, b);
}

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

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

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

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

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

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

static short min(short[] c) {
  short x = 0x7FFF;
  for (short d : c) if (d < x) x = d;
  return x;
}
static <A> ArrayList<A> litlist(A... a) {
  return new ArrayList<A>(Arrays.asList(a));
}
static String baseClassName(String className) {
  return substring(className, className.lastIndexOf('.')+1);
}

static String baseClassName(Object o) {
  return baseClassName(getClassName(o));
}
static int max(int a, int b) {
  return Math.max(a, b);
}

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

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

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

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

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

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

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

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

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

static short max(short[] c) {
  short x = -0x8000;
  for (short d : c) if (d > x) x = d;
  return x;
}
static Throwable getInnerException(Throwable e) {
  while (e.getCause() != null)
    e = e.getCause();
  return e;
}
static long round(double d) {
  return Math.round(d);
}
static int isAndroid_flag;

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



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

static String substring(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 _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 void sleepQuietly() { try {
  assertFalse(isAWTThread());
  synchronized(main.class) { main.class.wait(); }
} catch (Exception __e) { throw rethrow(__e); } }
  public static String loadTextFile(String fileName) {
    return loadTextFile(fileName, null);
  }
  
  public static String loadTextFile(String fileName, String defaultContents) {
    try {
      if (!new File(fileName).exists())
        return defaultContents;
  
      FileInputStream fileInputStream = new FileInputStream(fileName);
      InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
      return loadTextFile(inputStreamReader);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  
  public static String loadTextFile(File fileName) {
      return loadTextFile(fileName, null);
  }

  public static String loadTextFile(File fileName, String defaultContents) {
      return loadTextFile(fileName.getPath(), defaultContents);
  }
  
  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 <A> A assertNempty(A a) {
  if (empty(a))
    throw fail("empty: " + a);
  return a;
}


static void assertFalse(Object o) {
  assertEquals(false, o);
}
  
static boolean assertFalse(boolean b) {
  if (b) throw fail("oops");
  return b;
}

static boolean assertFalse(String msg, boolean b) {
  if (b) throw fail(msg);
  return b;
}

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

static File userDir(String path) {
  return new File(userHome(), path);
}


static <A> A assertEquals(Object x, A y) {
  return assertEquals(null, x, y);
}

static <A> A assertEquals(String msg, Object x, A y) {
  if (!(x == null ? y == null : x.equals(y)))
    throw fail((msg != null ? msg + ": " : "") + y + " != " + x);
  return y;
}


static abstract class F1<A, B> {
  abstract B get(A a);
}

static String htmldecode_dropAllTags(String html) {
  return htmldecode(dropAllTags(html));
}
// get purpose 1: access a list/array (safer version of x.get(y))

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

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

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

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

static Object get(Object o, String field) {
  try {
    if (o 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);
    }
      
    
  } 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 rethrow(Throwable e) {
  throw asRuntimeException(e);
}
static volatile boolean licensed_yes = true;

static boolean licensed() {
  ping();
  return licensed_yes;
}

static void licensed_off() {
  licensed_yes = false;
}


static String htmldecode(final String input) {
  if (input == null) return null;
  
  final int MIN_ESCAPE = 2;
  final int MAX_ESCAPE = 6;

  StringWriter writer = null;
  int len = input.length();
  int i = 1;
  int st = 0;
  while (true) {
      // look for '&'
      while (i < len && input.charAt(i-1) != '&')
          i++;
      if (i >= len)
          break;

      // found '&', look for ';'
      int j = i;
      while (j < len && j < i + MAX_ESCAPE + 1 && input.charAt(j) != ';')
          j++;
      if (j == len || j < i + MIN_ESCAPE || j == i + MAX_ESCAPE + 1) {
          i++;
          continue;
      }

      // found escape 
      if (input.charAt(i) == '#') {
          // numeric escape
          int k = i + 1;
          int radix = 10;

          final char firstChar = input.charAt(k);
          if (firstChar == 'x' || firstChar == 'X') {
              k++;
              radix = 16;
          }

          try {
              int entityValue = Integer.parseInt(input.substring(k, j), radix);

              if (writer == null) 
                  writer = new StringWriter(input.length());
              writer.append(input.substring(st, i - 1));

              if (entityValue > 0xFFFF) {
                  final char[] chrs = Character.toChars(entityValue);
                  writer.write(chrs[0]);
                  writer.write(chrs[1]);
              } else {
                  writer.write(entityValue);
              }

          } catch (NumberFormatException ex) { 
              i++;
              continue;
          }
      }
      else {
          // named escape
          CharSequence value = htmldecode_lookupMap.get(input.substring(i, j));
          if (value == null) {
              i++;
              continue;
          }

          if (writer == null) 
              writer = new StringWriter(input.length());
          writer.append(input.substring(st, i - 1));

          writer.append(value);
      }

      // skip escape
      st = j + 1;
      i = st;
  }

  if (writer != null) {
      writer.append(input.substring(st, len));
      return writer.toString();
  }
  return input;
}

private static final String[][] htmldecode_ESCAPES = {
    {"\"",     "quot"}, // " - double-quote
    {"&",      "amp"}, // & - ampersand
    {"<",      "lt"}, // < - less-than
    {">",      "gt"}, // > - greater-than

    // Mapping to escape ISO-8859-1 characters to their named HTML 3.x equivalents.
    {"\u00A0", "nbsp"}, // non-breaking space
    {"\u00A1", "iexcl"}, // inverted exclamation mark
    {"\u00A2", "cent"}, // cent sign
    {"\u00A3", "pound"}, // pound sign
    {"\u00A4", "curren"}, // currency sign
    {"\u00A5", "yen"}, // yen sign = yuan sign
    {"\u00A6", "brvbar"}, // broken bar = broken vertical bar
    {"\u00A7", "sect"}, // section sign
    {"\u00A8", "uml"}, // diaeresis = spacing diaeresis
    {"\u00A9", "copy"}, // copyright sign
    {"\u00AA", "ordf"}, // feminine ordinal indicator
    {"\u00AB", "laquo"}, // left-pointing double angle quotation mark = left pointing guillemet
    {"\u00AC", "not"}, // not sign
    {"\u00AD", "shy"}, // soft hyphen = discretionary hyphen
    {"\u00AE", "reg"}, // registered trademark sign
    {"\u00AF", "macr"}, // macron = spacing macron = overline = APL overbar
    {"\u00B0", "deg"}, // degree sign
    {"\u00B1", "plusmn"}, // plus-minus sign = plus-or-minus sign
    {"\u00B2", "sup2"}, // superscript two = superscript digit two = squared
    {"\u00B3", "sup3"}, // superscript three = superscript digit three = cubed
    {"\u00B4", "acute"}, // acute accent = spacing acute
    {"\u00B5", "micro"}, // micro sign
    {"\u00B6", "para"}, // pilcrow sign = paragraph sign
    {"\u00B7", "middot"}, // middle dot = Georgian comma = Greek middle dot
    {"\u00B8", "cedil"}, // cedilla = spacing cedilla
    {"\u00B9", "sup1"}, // superscript one = superscript digit one
    {"\u00BA", "ordm"}, // masculine ordinal indicator
    {"\u00BB", "raquo"}, // right-pointing double angle quotation mark = right pointing guillemet
    {"\u00BC", "frac14"}, // vulgar fraction one quarter = fraction one quarter
    {"\u00BD", "frac12"}, // vulgar fraction one half = fraction one half
    {"\u00BE", "frac34"}, // vulgar fraction three quarters = fraction three quarters
    {"\u00BF", "iquest"}, // inverted question mark = turned question mark
    {"\u00C0", "Agrave"}, // ? - uppercase A, grave accent
    {"\u00C1", "Aacute"}, // ? - uppercase A, acute accent
    {"\u00C2", "Acirc"}, // ? - uppercase A, circumflex accent
    {"\u00C3", "Atilde"}, // ? - uppercase A, tilde
    {"\u00C4", "Auml"}, // ? - uppercase A, umlaut
    {"\u00C5", "Aring"}, // ? - uppercase A, ring
    {"\u00C6", "AElig"}, // ? - uppercase AE
    {"\u00C7", "Ccedil"}, // ? - uppercase C, cedilla
    {"\u00C8", "Egrave"}, // ? - uppercase E, grave accent
    {"\u00C9", "Eacute"}, // ? - uppercase E, acute accent
    {"\u00CA", "Ecirc"}, // ? - uppercase E, circumflex accent
    {"\u00CB", "Euml"}, // ? - uppercase E, umlaut
    {"\u00CC", "Igrave"}, // ? - uppercase I, grave accent
    {"\u00CD", "Iacute"}, // ? - uppercase I, acute accent
    {"\u00CE", "Icirc"}, // ? - uppercase I, circumflex accent
    {"\u00CF", "Iuml"}, // ? - uppercase I, umlaut
    {"\u00D0", "ETH"}, // ? - uppercase Eth, Icelandic
    {"\u00D1", "Ntilde"}, // ? - uppercase N, tilde
    {"\u00D2", "Ograve"}, // ? - uppercase O, grave accent
    {"\u00D3", "Oacute"}, // ? - uppercase O, acute accent
    {"\u00D4", "Ocirc"}, // ? - uppercase O, circumflex accent
    {"\u00D5", "Otilde"}, // ? - uppercase O, tilde
    {"\u00D6", "Ouml"}, // ? - uppercase O, umlaut
    {"\u00D7", "times"}, // multiplication sign
    {"\u00D8", "Oslash"}, // ? - uppercase O, slash
    {"\u00D9", "Ugrave"}, // ? - uppercase U, grave accent
    {"\u00DA", "Uacute"}, // ? - uppercase U, acute accent
    {"\u00DB", "Ucirc"}, // ? - uppercase U, circumflex accent
    {"\u00DC", "Uuml"}, // ? - uppercase U, umlaut
    {"\u00DD", "Yacute"}, // ? - uppercase Y, acute accent
    {"\u00DE", "THORN"}, // ? - uppercase THORN, Icelandic
    {"\u00DF", "szlig"}, // ? - lowercase sharps, German
    {"\u00E0", "agrave"}, // ? - lowercase a, grave accent
    {"\u00E1", "aacute"}, // ? - lowercase a, acute accent
    {"\u00E2", "acirc"}, // ? - lowercase a, circumflex accent
    {"\u00E3", "atilde"}, // ? - lowercase a, tilde
    {"\u00E4", "auml"}, // ? - lowercase a, umlaut
    {"\u00E5", "aring"}, // ? - lowercase a, ring
    {"\u00E6", "aelig"}, // ? - lowercase ae
    {"\u00E7", "ccedil"}, // ? - lowercase c, cedilla
    {"\u00E8", "egrave"}, // ? - lowercase e, grave accent
    {"\u00E9", "eacute"}, // ? - lowercase e, acute accent
    {"\u00EA", "ecirc"}, // ? - lowercase e, circumflex accent
    {"\u00EB", "euml"}, // ? - lowercase e, umlaut
    {"\u00EC", "igrave"}, // ? - lowercase i, grave accent
    {"\u00ED", "iacute"}, // ? - lowercase i, acute accent
    {"\u00EE", "icirc"}, // ? - lowercase i, circumflex accent
    {"\u00EF", "iuml"}, // ? - lowercase i, umlaut
    {"\u00F0", "eth"}, // ? - lowercase eth, Icelandic
    {"\u00F1", "ntilde"}, // ? - lowercase n, tilde
    {"\u00F2", "ograve"}, // ? - lowercase o, grave accent
    {"\u00F3", "oacute"}, // ? - lowercase o, acute accent
    {"\u00F4", "ocirc"}, // ? - lowercase o, circumflex accent
    {"\u00F5", "otilde"}, // ? - lowercase o, tilde
    {"\u00F6", "ouml"}, // ? - lowercase o, umlaut
    {"\u00F7", "divide"}, // division sign
    {"\u00F8", "oslash"}, // ? - lowercase o, slash
    {"\u00F9", "ugrave"}, // ? - lowercase u, grave accent
    {"\u00FA", "uacute"}, // ? - lowercase u, acute accent
    {"\u00FB", "ucirc"}, // ? - lowercase u, circumflex accent
    {"\u00FC", "uuml"}, // ? - lowercase u, umlaut
    {"\u00FD", "yacute"}, // ? - lowercase y, acute accent
    {"\u00FE", "thorn"}, // ? - lowercase thorn, Icelandic
    {"\u00FF", "yuml"}, // ? - lowercase y, umlaut
    {"\u2013", "ndash"},
    {"\u2018", "lsquo"},
    {"\u2019", "rsquo"},
    {"\u201D", "rdquo"},
    {"\u201C", "ldquo"},
    {"\u2014", "mdash"},
    
    {"'", "apos"}, // the controversial (but who cares!) &apos;
      // stackoverflow.com/questions/2083754/why-shouldnt-apos-be-used-to-escape-single-quotes
  };

private static final HashMap<String, CharSequence> htmldecode_lookupMap;
static {
    htmldecode_lookupMap = new HashMap<String, CharSequence>();
    for (final CharSequence[] seq : htmldecode_ESCAPES) 
        htmldecode_lookupMap.put(seq[1].toString(), seq[0]);
}
// tok should be the output of htmlcoarsetok
static List<String> dropAllTags(List<String> tok) {
  List<String> list = new ArrayList();
  for (int i = 0; i < tok.size(); i++) {
    String t = tok.get(i);
    if (t.startsWith("<")) {
      list.set(list.size()-1, list.get(list.size()-1) + tok.get(i+1));
      ++i;
    } else
      list.add(tok.get(i));
  }
  return list;
}

// alternatively, call this convenient function
static String dropAllTags(String html) {
  return join(dropAllTags(htmlcoarsetok(html)));
}
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;
}

}