chiark / gitweb /
use "/who" rather than "/w" to find our island
[jarrg-ian.git] / src / net / chiark / yarrg / MarketUploader.java
1 package net.chiark.yarrg;
2
3 import java.awt.*;
4 import java.awt.event.*;
5
6 import javax.accessibility.*;
7 import javax.swing.*;
8
9 import com.sun.java.accessibility.util.*;
10
11 import java.util.*;
12 import java.io.*;
13 import java.util.*;
14 import java.net.URL;
15 import org.w3c.dom.*;
16 import javax.xml.parsers.DocumentBuilderFactory;
17 import org.xml.sax.InputSource;
18 import java.util.zip.GZIPOutputStream;
19 import net.chiark.yarrg.ClientHttpRequest;
20 import java.util.regex.*;
21 import java.util.prefs.Preferences;
22 import java.beans.*;
23
24 /*
25  *      MarketUploader is a class that handles the uploading of market
26  *      data from Yohoho! Puzzle Pirates via the Java Accessibility
27  *      API.
28  *
29  *      MarketUploader initializes after the main YPP window has
30  *      initialized. It provides a simple window with a "Capture
31  *      Market Data" button displayed.  Upon clicking this button, a
32  *      progress dialog is displayed, and the data is processed and
33  *      submitted to the YARRG and PCTB servers. If any errors occur,
34  *      an error dialog is shown, and processing returns, the button
35  *      becoming re-enabled.
36  */
37 public class MarketUploader
38 implements Runnable, TopLevelWindowListener, GUIInitializedListener {
39   // UI object references which are set during startup
40   private JFrame frame = null;
41   private Window window = null;
42
43   // Genuinely global variables
44   private PrintStream dtxt = null;
45   public int uploadcounter = 0;
46
47   // UI objects which are enabled/disabled, cleared/set, created/destroyed,
48   //  etc., for each upload
49   private JButton findMarket = null;
50   private JLabel resultSummary = null;
51   private JLabel arbitrageResult = null;
52   private ProgressMonitor progmon = null;
53
54   // PCTB protocol parameters
55   private final static String PCTB_LIVE_HOST_URL = "http://pctb.crabdance.com/";
56   private final static String PCTB_TEST_HOST_URL = "http://pctb.ilk.org/";
57   private String PCTB_HOST_URL;
58
59   // YARRG protocol parameters
60   private final static String YARRG_CLIENTNAME = "jpctb greenend";
61   private final static String YARRG_CLIENTVERSION =
62             net.chiark.yarrg.Version.version;
63   private final static String YARRG_CLIENTFIXES = "bug-094";
64   private final static String YARRG_LIVE_URL =
65     "http://upload.yarrg.chiark.net/commod-update-receiver";
66   private final static String YARRG_TEST_URL =
67     "http://upload.yarrg.chiark.net/test/commod-update-receiver";
68   private String YARRG_URL;
69
70   // Preferences
71   private boolean uploadToYarrg;
72   private boolean uploadToPCTB;
73   private boolean showArbitrage;
74
75   // Values cleared/set for each upload, or used during upload processing
76   private long startTime = 0;
77
78   private String islandName = null;
79   private String oceanName = null;
80   private java.util.concurrent.CountDownLatch latch = null;
81
82   private AccessibleContext sidePanel;
83
84   // PCTB-specific variables
85   private int unknownPCTBcommods = 0;
86   private HashMap<String,Integer> commodMap;
87
88
89   /*****************************************
90    * UPLOAD-TARGET-INDEPENDENT CODE        *
91    *****************************************/
92
93
94   /*
95    * UTILITY METHODS AND SUBCLASSES
96    *
97    * Useable on any thread.
98    *
99    */
100   private int parseQty(String str) {
101     if (str.equals(">1000")) {
102       return 1001;
103     } else {
104       return Integer.parseInt(str);
105     }
106   }
107
108   private void debuglog(String s) {
109     if (dtxt == null) return;
110     long now = new Date().getTime();
111     dtxt.println("progress "+(now - startTime)+"ms "
112                  +Thread.currentThread().getName()+": "+s);
113   }
114
115   private void debug_write_stringdata(String what, String data)
116   throws FileNotFoundException,IOException {
117     if (dtxt==null) return;
118     PrintStream strm = new PrintStream(new File("jarrg-debug-"+what));
119     strm.print(data);
120     strm.close();
121   }
122
123   private void debug_write_bytes(String what, byte[] data)
124   throws FileNotFoundException,IOException {
125     if (dtxt==null) return;
126     FileOutputStream strm = new FileOutputStream(new File("jarrg-debug-"+what));
127     strm.write(data);
128     strm.close();
129   }
130
131         
132   /*
133    * ENTRY POINT AND STARTUP
134    *
135    * Main thread and/or event thread
136    */
137
138   public static void main(String[] args) {
139     // This is not normally called, it seems.
140     new MarketUploader();
141   }
142
143   public MarketUploader() {
144     Preferences prefs = Preferences.userNodeForPackage(getClass());
145
146     if (prefs.getBoolean("writeDebugFiles", false)) {
147       try {
148         dtxt = new PrintStream(new File("jarrg-debug-log.txt"));
149       } catch (java.io.FileNotFoundException e) {
150         System.err.println("JARRG: Error opening debug log: "+e);
151       }
152     }
153
154     if (prefs.getBoolean("useLiveServers", true)) {
155       YARRG_URL = YARRG_LIVE_URL;
156       PCTB_HOST_URL = PCTB_LIVE_HOST_URL;
157     } else {
158       YARRG_URL = YARRG_TEST_URL;
159       PCTB_HOST_URL = PCTB_TEST_HOST_URL;
160     }
161                 
162     uploadToYarrg=prefs.getBoolean("uploadToYarrg", true);
163     uploadToPCTB=prefs.getBoolean("uploadToPCTB", true);
164     showArbitrage=prefs.getBoolean("showArbitrage", true);
165
166     debuglog("main on dispatch thread: "+EventQueue.isDispatchThread());
167     EventQueue.invokeLater(this);
168   }
169
170   /*
171    * We arrange to wait for the GUI to be initialised, then look at
172    * every top-level window to see if the Puzzle Pirates window turns up.
173    */
174   public void run() {
175     debuglog("MarketUploader run()...");
176     if (EventQueueMonitor.isGUIInitialized()) {
177       debuglog("MarketUploader GUI already ready");
178       guiInitialized();
179     } else {
180       debuglog("MarketUploader waiting for GUI");
181       EventQueueMonitor.addGUIInitializedListener(this);
182     }
183   }
184
185   public void guiInitialized() {
186     Window ws[]= EventQueueMonitor.getTopLevelWindows();
187     EventQueueMonitor.addTopLevelWindowListener(this);
188     for (int i=0; i<ws.length; i++) {
189       debuglog("MarketUploader existing toplevel "+i);
190       topLevelWindowCreated(ws[i]);
191     }
192   }
193
194   public void topLevelWindowDestroyed(Window w) {
195     debuglog("MarketUploader destroyed toplevel");
196   }
197         
198   public void topLevelWindowCreated(Window w) {
199     if (frame!=null) 
200       // already got it
201       return;
202     String name = w.getAccessibleContext().getAccessibleName();
203     debuglog("MarketUploader checking toplevel "+name);
204     if (!name.equals("Puzzle Pirates"))
205       // Only if we're running alongside a Window named "Puzzle Pirates"
206       return;
207     debuglog("MarketUploader found toplevel, creating gui");
208     window = w;
209     createGUI();
210     frame.setVisible(true);
211   }
212         
213   private void createGUI() {
214     // Actually set up our GUI
215     on_ui_thread();
216     frame = new JFrame("Jarrg Uploader");
217     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
218     GridLayout layout = new GridLayout(2,1);
219     frame.getContentPane().setLayout(layout);
220     //frame.setPreferredSize(new Dimension(200, 60));
221                 
222     findMarket = new JButton("Upload Market Data");
223     findMarket.addActionListener(new ActionListener() {
224         public void actionPerformed(ActionEvent e) {
225           // This is called when the user clicks "upload"
226           on_ui_thread();
227
228           uploadcounter++;
229           findMarket.setEnabled(false);
230           resultSummary.setText("");
231           arbitrageResult.setText("");
232           new Thread("MarketUploader-uploader-"+uploadcounter) {
233             public void run() {
234               startTime = new Date().getTime();
235               unknownPCTBcommods = 0;
236               try {
237                 runUpload(uploadcounter);
238               } catch(Exception e) {
239                 error(e.toString());
240                 e.printStackTrace();
241               }
242               try {
243                 new UIX() { public void body() { 
244                   if(sidePanel != null) {
245                     sidePanel.removePropertyChangeListener(changeListener);
246                   }
247                   if (progmon != null) {
248                     progmon.close();
249                     progmon = null;
250                   }
251                   findMarket.setEnabled(true);
252                 }}.exec("tidying");
253               } catch (Exception e) {
254                 System.err.println("exception tidying on UI thread:");
255                 e.printStackTrace();
256               }
257             }
258           }.start();
259         }
260       });
261     frame.add(findMarket);
262
263     resultSummary = new JLabel("ready");
264     frame.add(resultSummary);
265                 
266     arbitrageResult = new JLabel("");
267
268     if (showArbitrage) {
269       layout.setRows(layout.getRows() + 1);
270       frame.add(arbitrageResult);
271     }
272
273     frame.pack();
274   }
275
276   /*
277    * THREAD HANDLING
278    *
279    * Special measures are needed because:
280    *  - it is not permitted to use any Swing UI classes or objects
281    *    other than on the Swing event thread
282    *  - we want to run our upload asynchronously
283    *  - we want to do some computation asynchronously (eg, the
284    *    arbitrage and upload data prep)
285    *
286    * So what we do is this:
287    *  1. When the user asks to upload, we spawn a new thread
288    *     to do the upload ("MarketUploader-uploader-*", see
289    *     the call to "new Thread" inside createGUI.
290    *  2. Whenever that thread needs to touch a UI object it
291    *     uses EventQueue.invokeLater or .invokeAndWait to
292    *     perform the relevant action.  We wrap these calls up
293    *     in three utility classes:
294    *        UIA  - runs code on UI thread, asynchronously
295    *        UIX  - runs code on UI thread, waits for it to finish
296    *        UIXR - as UIX but also returns a value
297    *     These hide the details of the EventQueue class and also do
298    *     some debugging and argument shuffling; the calling syntax is
299    *     still painful, unfortunately, and there is a weird constraint
300    *     on variables used inside the inner body.  For a simple
301    *     example, see the handling of "summary" and "summary_final"
302    *     for the call to UIX at the bottom of runUpload.
303    *  3. Try to put everything back when that thread exits.
304    *
305    * Additionally:
306    *  a. There is another thread spawed early to get a timestamp from
307    *     YARRG, if we are uploading there.
308    *  b. Finding the island name can involve callbacks which run in
309    *     the UI event thread.  Basically we do the work there, and use
310    *     a CountDownLatch to cause the uploader thread to wait as
311    *     appropriate.
312    */
313
314   private void on_ui_thread() { assert(EventQueue.isDispatchThread()); }
315   private void on_our_thread() { assert(!EventQueue.isDispatchThread()); }
316
317   private abstract class UIA implements Runnable {
318     private String what;
319     public abstract void body();
320     public void run() {
321       debuglog("UIA 2 "+what+" begin");
322       body();
323       debuglog("UIA 3 "+what+" done");
324     }
325     public void exec(String what_in) {
326       what = what_in;
327       debuglog("UIA 1 "+what+" request");
328       EventQueue.invokeLater(this);
329     }
330   };
331   private abstract class UIXR<ReturnType> implements Runnable {
332     public abstract ReturnType bodyr();
333     public ReturnType return_value;
334     private String what;
335     public void run() { 
336       debuglog("UIX 2 "+what+" begin");
337       return_value = bodyr();
338       debuglog("UIX 3 "+what+" done");
339     }
340     public ReturnType exec(String what_in) throws Exception {
341       what = what_in;
342       if (EventQueue.isDispatchThread()) {
343         debuglog("UIX 1 "+what+" (event thread) entry");
344         this.run();
345         debuglog("UIX 4 "+what+" (event thread) exit");
346       } else {
347         debuglog("UIX 1 "+what+" (other thread) entry");
348         EventQueue.invokeAndWait(this);
349         debuglog("UIX 4 "+what+" (other thread) exit");
350       }
351       return return_value;
352     }
353   };
354   private abstract class UIX extends UIXR<Object> implements Runnable {
355     public abstract void body();
356     public Object bodyr() { body(); return null; }
357   };
358
359   /*
360    * ERROR REPORTING AND GENERAL UTILITIES
361    *
362    * Synchronous modal dialogues
363    * error and error_html may be called from any thread
364    */ 
365
366   public void error(final String msg) {
367     try {
368       new UIX() { public void body() {
369         resultSummary.setText("failed");
370         JOptionPane.showMessageDialog(frame,msg,"Error",
371                                       JOptionPane.ERROR_MESSAGE);
372       }}.exec("error()");
373     } catch (Exception e) {
374       System.err.println("exception reporting to UI thread:");
375       e.printStackTrace();
376     }
377   }
378         
379   public void error_html(final String msg, String html) {
380     Pattern body = Pattern.compile("<body>(.*)</body>",
381                                    Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
382     Matcher m = body.matcher(html);
383     if (m.find()) {
384       html = m.group(1);
385       Pattern fixup = Pattern.compile("<(\\w+) */>");;
386       m = fixup.matcher(html);
387       html = m.replaceAll("<$1>");
388       m = Pattern.compile("[\\r\\n]+").matcher(html);
389       html = m.replaceAll(" ");
390     }
391     String whole_msg = "<html><h1>Error</h1>"+msg
392       +"<h1>PCTB Server said:</h1><blockquote>"+html+"</blockquote>";
393     debuglog("###" + whole_msg + "###");
394   
395     error(whole_msg);
396   }
397
398   public void progressNote(final String s_in) throws Exception {
399     new UIA() { public void body() {
400       String arb = null;
401       arb = arbitrageResult.getText();
402       String s = s_in;
403       if (arb != null && arb.length() != 0)
404         s = "<html>" + arb + "<br>" + s;
405       progmon.setNote(s);
406     }}.exec("progressNote "+s_in);
407   }
408   public void setProgress(final int nv) throws Exception {
409     new UIA() { public void body() {
410       progmon.setProgress(nv);
411     }}.exec("setProgress "+nv);
412   }
413   public boolean checkCancelled() throws Exception {
414     return new UIXR<Boolean>() { public Boolean bodyr() {
415       boolean can = progmon.isCanceled();
416       if (can) resultSummary.setText("cancelled");
417       return new Boolean(can);
418     }}.exec("checkCancelled").booleanValue();
419   }
420
421
422   /*
423    * ACTUAL DATA COLLECTION AND UPLOAD
424    */
425
426   private void runUpload(int counter) throws Exception {
427     // Runs the data collection process, and upload the results.
428     // In most cases of error, we call error() (which synchronously
429     // reports the error) and then simply return.
430
431     on_our_thread();
432
433     boolean doneyarrg = false, donepctb = false;
434     YarrgTimestampFetcher yarrgts_thread = null;
435
436     debuglog("starting");
437
438     if (uploadToYarrg) {
439       debuglog("(async) yarrg timestamp...");
440       yarrgts_thread = new YarrgTimestampFetcher(counter);
441       yarrgts_thread.start();
442     }
443
444     final AccessibleTable accesstable = 
445     new UIXR<AccessibleTable>() { public AccessibleTable bodyr() {
446       progmon = new ProgressMonitor
447         (frame,"Processing Market Data","Getting table data",0,100);
448       progmon.setMillisToDecideToPopup(0);
449       progmon.setMillisToPopup(0);
450
451       AccessibleTable at = findMarketTable();
452       if(at == null) {
453         error("Market table not found!"+
454               " Please open the Buy/Sell Commodities interface.");
455         return null;
456       }
457       if(at.getAccessibleRowCount() == 0) {
458         error("No data found, please wait for the table to have data first!");
459         return null;
460       }
461       if(!isDisplayAll()) {
462         error("Please select \"All\" from the Display: popup menu.");
463         return null;
464       }
465
466       debuglog("(async) getisland...");
467       getIsland();
468       debuglog("getocean...");
469       getOcean();
470       debuglog("getocean done");
471
472       return at;
473     }}.exec("accesstable");
474     if (accesstable == null) return;
475
476     if (latch != null) {
477       latch.await(2, java.util.concurrent.TimeUnit.SECONDS);
478     }
479     debuglog("(async) getisland done");
480
481     String yarrgts = null;
482     if (yarrgts_thread != null) {
483       debuglog("(async) yarrg timestamp join...");
484       yarrgts_thread.join();
485       debuglog("(async) yarrg timestamp joined.");
486       yarrgts = yarrgts_thread.ts;
487     }
488
489     if (islandName == null) {
490       error("Could not find island name in YPP user interface.");
491       return;
492     }
493
494     debuglog("table check...");
495
496     final ArrayList<ArrayList<String>> data =
497     new UIXR<ArrayList<ArrayList<String>>>
498           () { public ArrayList<ArrayList<String>> bodyr() {
499       String headings_expected[] = new String[]
500         { "Commodity", "Trading outlet", "Buy price",
501           "Will buy", "Sell price", "Will sell" };
502
503       ArrayList<ArrayList<String>> headers =
504         getData(accesstable.getAccessibleColumnHeader());
505       if (headers.size() != 1) {
506         error("Table headings not one row! " + headers.toString());
507         return null;
508       }
509       if (headers.get(0).size() < 6 ||
510           headers.get(0).size() > 7) {
511         error("Table headings not six or seven columns! " + headers.toString());
512         return null;
513       }
514       for (int col=0; col<headings_expected.length; col++) {
515         String expd = headings_expected[col];
516         String got = headers.get(0).get(col);
517         if (expd.compareTo(got) != 0) {
518           error("Table heading for column "+col
519                 +" is not \""+expd+"\" but \""+got+"\".\n\n"
520                 +"Please do not reorder the table when using this tool.");
521           return null;
522         }
523       }
524
525       debuglog("table read...");
526
527       return getData(accesstable);
528     }}.exec("data");
529     if (data == null) return;
530
531     if (showArbitrage) {
532       debuglog("arbitrage...");
533       calculateArbitrage(data);
534       debuglog("arbitrage done.");
535     }
536
537     if (uploadToYarrg && yarrgts != null) {
538       debuglog("yarrg prepare...");
539       progressNote("Yarrg: Preparing data");
540       setProgress(10);
541
542       StringBuilder yarrgsb = new StringBuilder();
543       String yarrgdata; // string containing what we'll feed to yarrg
544                 
545       for (ArrayList<String> row : data) {
546         if (row.size() > 6) {
547           row.remove(6);
548         }
549         for (String rowitem : row) {
550           yarrgsb.append(rowitem != null ? rowitem : "");
551           yarrgsb.append("\t");
552         }
553         yarrgsb.setLength(yarrgsb.length()-1); // chop
554         yarrgsb.append("\n");
555       }
556
557       yarrgdata = yarrgsb.toString();
558
559       progressNote("Yarrg: Uploading");
560       debuglog("yarrg upload...");
561
562       doneyarrg = runYarrg(yarrgts, oceanName, islandName, yarrgdata);
563       debuglog("yarrg done.");
564     }
565
566     if (uploadToPCTB) {
567       debuglog("pctb prepare...");
568       progressNote("PCTB: Getting stall names");
569       setProgress(20);
570       if(checkCancelled()) {
571         return;
572       }
573       TreeSet<Offer> buys = new TreeSet<Offer>();
574       TreeSet<Offer> sells = new TreeSet<Offer>();
575       LinkedHashMap<String,Integer> stallMap = getStallMap(data);
576       setProgress(40);
577       progressNote("PCTB: Sorting offers");
578       if(checkCancelled()) {
579         return;
580       }
581       // get commod map
582                 
583       debuglog("pctb commodmap...");
584       HashMap<String,Integer> commodMap = getCommodMap();
585       if(commodMap == null) {
586         return;
587       }
588       debuglog("pctb commodmap done.");
589       int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
590       // debuglog(sells);
591       // debuglog("\n\n\n"+buys);
592
593       ByteArrayOutputStream outStream = new ByteArrayOutputStream();
594       setProgress(60);
595       progressNote("PCTB: Sending data");
596       if(checkCancelled()) {
597         return;
598       }
599       GZIPOutputStream out = new GZIPOutputStream(outStream);
600       DataOutputStream dos = new DataOutputStream(out);
601       dos.writeBytes("005y\n");
602       dos.writeBytes(stallMap.size()+"\n");
603       dos.writeBytes(getAbbrevStallList(stallMap));
604       writeBuySellOffers(buys,sells,offerCount,out);
605       out.finish();
606       debuglog("pctb send...");
607
608       byte[] ba = outStream.toByteArray();
609       debug_write_bytes("pctb-marketdata.gz", ba);
610
611       InputStream in = sendInitialData(new ByteArrayInputStream(ba));
612       debuglog("pctb sent.");
613       if (in == null) return;
614       setProgress(80);
615       if(checkCancelled()) {
616         return;
617       }
618       progressNote("PCTB: Waiting ...");
619       debuglog("pctb finish...");
620       donepctb = finishUpload(in);
621       debuglog("pctb done.");
622     }
623     setProgress(99);
624
625     String summary;
626     if ((uploadToPCTB && !donepctb) ||
627         (uploadToYarrg && !doneyarrg)) {
628       summary= "trouble";
629     } else if (unknownPCTBcommods != 0) {
630       summary= "PCTB lacks "+unknownPCTBcommods+" commod(s)";
631     } else if (donepctb || doneyarrg) {
632       summary= "Done " + islandName;
633     } else {
634       summary= "uploaded nowhere!";
635     }
636     final String summary_final = summary;
637     new UIX() { public void body() {
638       resultSummary.setText(summary_final);
639     }}.exec("resultSummary.setText");
640
641     debuglog("done.");
642   }
643
644   /*
645    * UPLOAD HELPER FUNCTIONS FOR EXTRACTING SPECIFIC UI DATA
646    */
647         
648   private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
649     // Gets the offer data out of the table and returns it as an ArrayList
650
651     on_ui_thread();
652     ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
653     for (int i = 0; i < table.getAccessibleRowCount(); i++) {
654       ArrayList<String> row = new ArrayList<String>();
655       for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
656         row.add(table.getAccessibleAt(i, j)
657                 .getAccessibleContext().getAccessibleName());
658       }
659       data.add(row);
660     }
661     return data;
662   }
663         
664   public AccessibleTable findMarketTable() {
665     // Return the table containing market data if it exists, otherwise null.
666     on_ui_thread();
667
668     Accessible node1 = window;
669     Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0}); 
670       // commod market
671     // commod market: {0,1,0,0,0,0,1,0,0,1,0}  {0,1,0,0,0,0,1,0,1,0,0,1,0,0})
672     // debuglog(node);
673     if (!(node instanceof JTable)) {
674       node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0});
675         // commod market
676     }
677     if (!(node instanceof JTable)) return null;
678     AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
679     // debuglog(table);
680     return table;
681   }
682         
683   private boolean isDisplayAll() {
684     // Returns true iff the "Display:" menu on the commodities
685     // interface in YPP is set to "All"
686     on_ui_thread();
687
688     Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
689     if(!(button instanceof JButton)) {
690       button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
691     }
692     String display = button.getAccessibleContext().getAccessibleName();
693     if(!display.equals("All")) {
694       return false;
695     }
696     return true;
697   }
698         
699   /*
700    * FUNCTIONS AND CALLBACKS FOR FINDING ISLAND AND OCEAN
701    */
702
703   private void getOcean() {
704     // Finds the ocean name from the window title.
705     // Stores it in the global oceanName
706     on_ui_thread();
707
708     oceanName = null;
709     AccessibleContext topwindow = window.getAccessibleContext();
710     oceanName = topwindow.getAccessibleName()
711       .replaceAll(".*on the (\\w+) ocean", "$1");
712   }
713
714   private void getIsland() {
715     // Tries to find the island name.  Either:
716     //  (a) sets the islandName global
717     // or
718     //  (b) sets latch to a new CountDownLatch, and arranges that 
719     //      at some point later, islandName will be set and the latch
720     //      decremented to zero
721     on_ui_thread();
722
723     // If the league tracker is there, we can skip the faff
724     // and ask for its tooltip, since we're on a boat
725
726     Accessible leagueTrackerContainer =
727       descendNodes(window,new int[] {0,1,0,0,2,1});
728     Accessible leagueTrackerItself =
729       descendByClass(leagueTrackerContainer,
730                      "com.threerings.yohoho.sea.client.LeagueTracker");
731     Accessible leagueTracker = descend(leagueTrackerItself, 1);
732     try {
733       islandName = ((JLabel)leagueTracker).getToolTipText();
734       latch = null;
735     } catch (NullPointerException e) {
736       // evidently we're actually on an island
737
738       islandName = null;
739       AccessibleContext chatArea =
740         descendNodes(window,new int[] {0,1,0,0,0,2,0,0,2})
741         .getAccessibleContext();
742       // attach the property change listener to the outer sunshine
743       // panel if the "ahoy" tab is not active, otherwise attach it to
744       // the scroll panel in the "ahoy" tab.
745       if(!"com.threerings.piracy.client.AttentionListPanel".
746          equals(descendNodes(window,new int[] {0,1,0,0,2,2,0})
747                 .getClass().getCanonicalName())) {
748         sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2})
749           .getAccessibleContext();
750       } else {
751         sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0})
752           .getAccessibleContext();
753       }
754       sidePanel.addPropertyChangeListener(changeListener);
755       latch = new java.util.concurrent.CountDownLatch(1);
756       // make the Players Online ("/who") panel appear
757       AccessibleEditableText chat = chatArea.getAccessibleEditableText();
758       chat.setTextContents("/who");
759       int c = chatArea.getAccessibleAction().getAccessibleActionCount();
760       for(int i=0;i<c;i++) {
761         if("notify-field-accept".equals(chatArea.getAccessibleAction()
762                                         .getAccessibleActionDescription(i))) {
763           chatArea.getAccessibleAction().doAccessibleAction(i);
764         }
765       }
766     }
767   }
768
769   private PropertyChangeListener changeListener = new PropertyChangeListener() {
770     // used by getIsland
771     public void propertyChange(PropertyChangeEvent e) {
772       on_ui_thread();
773       if(e.getNewValue() != null && 
774          e.getPropertyName().equals
775          (AccessibleContext.ACCESSIBLE_CHILD_PROPERTY)) {
776         Accessible islandInfo =
777           descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0,0,1,2});;
778         String text = islandInfo.getAccessibleContext().getAccessibleText()
779           .getAtIndex(AccessibleText.SENTENCE,0);
780         int index = text.indexOf(":");
781         String name = text.substring(0,index);
782         islandName = name;
783         // debuglog(islandName);
784         sidePanel.removePropertyChangeListener(this);
785         latch.countDown();
786       }
787     }
788   };
789
790   /*
791    * UTILITY FUNCTIONS FOR WALKING THE UI
792    *
793    * These functions all return null if the specified path or child
794    * was not found.
795    */
796
797   private Accessible descendNodes(Accessible parent, int[] path) {
798     // Descends through several levels of Accessible children in one call.
799     // path[] is an array of ints, each int being the index into the array
800     // of children at a particular point, and thus selects the specific
801     // accessible child to descend to.
802     on_ui_thread();
803
804     for(int i=0;i<path.length;i++) {
805       if (null == (parent = descend(parent, path[i]))) return null;
806     }
807     return parent;
808   }
809
810   private Accessible descend(Accessible parent, int childNum) {
811     // Descends one level to the specified child of the parent
812     // childNum is the index of the child within parent
813     on_ui_thread();
814
815     if (parent == null) return null;
816     int children = parent.getAccessibleContext().getAccessibleChildrenCount();
817     if (childNum >= children) {
818       debuglog("DESCEND "+childNum+" > "+children+" NOT FOUND");
819       return null;
820     }
821     Accessible child = parent.getAccessibleContext()
822       .getAccessibleChild(childNum);
823     debuglog("DESCEND "+childNum+" "+child.getClass().getName()+" OK");
824     return child;
825   }
826
827   private Accessible descendByClass(Accessible parent, String classname) {
828     // Descends one level to the first child which has the specified class.
829     on_ui_thread();
830
831     if (parent == null) return null;
832     AccessibleContext ac = parent.getAccessibleContext();
833     int children = ac.getAccessibleChildrenCount();
834     for (int i=0; i<children; i++) {
835       Accessible child = ac.getAccessibleChild(i);
836       if (child.getClass().getName() == classname) {
837         debuglog("DESCEND CLASS "+classname+" OK");
838         return child;
839       }
840     }
841     debuglog("DESCEND CLASS "+classname+" NOT FOUND");
842     return null;
843   }
844   
845
846   /*****************************************
847    * PCTB-SPECIFIC HELPER FUNCTIONS ETC.   *
848    *****************************************/
849
850   /**
851    *    An abstract market offer, entailing a commodity being bought or sold by
852    *    a shoppe, for a certain price in a certain quantity. Not instantiable.
853    *
854    *    @see Buy
855    *    @see Sell
856    */
857   abstract class Offer {
858     public int commodity, price, quantity, shoppe;
859     /**
860      *  Create an offer from <code>record</code>, determining the shoppe Id from
861      *  <code>stallMap</code> and the commodity Id from <code>commodMap</code>.
862      *  <code>priceIndex</code> should be the index of the price in the record
863      *  (the quantity will be <code>priceIndex + 1</code>).
864      *
865      *  @param record the record with data to create the offer from
866      *  @param stallMap a map containing the ids of the various stalls
867      *  @param commodMap a map containing the ids of the various commodities
868      *  @param priceIndex the index of the price in the record
869      */
870     public Offer(ArrayList<String> record, 
871                  LinkedHashMap<String,Integer> stallMap, 
872                  HashMap<String,Integer> commodMap,
873                  int priceIndex) {
874       Integer commodId = commodMap.get(record.get(0));
875       if(commodId == null) {
876         throw new IllegalArgumentException();
877       }
878       commodity = commodId.intValue();
879       price = Integer.parseInt(record.get(priceIndex));
880       String qty = record.get(priceIndex+1);
881       quantity = parseQty(qty);
882       shoppe = stallMap.get(record.get(1)).intValue();
883     }
884                 
885     /**
886      *  Returns a human-readable version of this offer, useful for debugging
887      *  
888      *  @return human-readable offer
889      */
890     public String toString() {
891       return "[C:" + commodity + ",$" + price + ",Q:"
892         + quantity + ",S:" + shoppe + "]";
893     }
894   }
895         
896   /**
897    *    An offer from a shoppe or stall to buy a certain quantity of a
898    *    commodity for a certain price. If placed in an ordered Set,
899    *    sorts by commodity index ascending, then by buy price
900    *    descending, and finally by stall id ascending.
901    */
902   class Buy extends Offer implements Comparable<Buy> {
903     /**
904      *  Creates a new <code>Buy</code> offer from the given
905      *  <code>record</code> using the other parameters to determine
906      *  stall id and commodity id of the offer.
907      *
908      *  @param record the record with data to create the offer from
909      *  @param stallMap a map containing the ids of the various stalls
910      *  @param commodMap a map containing the ids of the various commodities
911      */
912     public Buy(ArrayList<String> record,
913                LinkedHashMap<String,Integer> stallMap,
914                HashMap<String,Integer> commodMap) {
915       super(record,stallMap,commodMap,2);
916     }
917                 
918     /**
919      *  Sorts by commodity index ascending, then price descending,
920      *  then stall id ascending.
921      */
922     public int compareTo(Buy buy) {
923       // organize by: commodity index, price, stall index
924       if(commodity == buy.commodity) {
925         // organize by price, then by stall index
926         if(price == buy.price) {
927           // organize by stall index
928           return shoppe>buy.shoppe ? 1 : -1;
929         } else if(price > buy.price) {
930           return -1;
931         } else {
932           return 1;
933         }
934       } else if(commodity > buy.commodity) {
935         return 1;
936       } else {
937         return -1;
938       }
939     }
940   }
941         
942   /**
943    *    An offer from a shoppe or stall to sell a certain quantity of
944    *    a commodity for a certain price. If placed in an ordered Set,
945    *    sorts by commodity index ascending, then by sell price
946    *    ascending, and finally by stall id ascending.
947    */
948   class Sell extends Offer implements Comparable<Sell> {
949     /**
950      *  Creates a new <code>Sell</code> offer from the given
951      *  <code>record</code> using the other parameters to determine
952      *  stall id and commodity id of the offer.
953      *
954      *  @param record the record with data to create the offer from
955      *  @param stallMap a map containing the ids of the various stalls
956      *  @param commodMap a map containing the ids of the various commodities
957      */
958     public Sell(ArrayList<String> record,
959                 LinkedHashMap<String,Integer> stallMap,
960                 HashMap<String,Integer> commodMap) {
961       super(record,stallMap,commodMap,4);
962     }
963                 
964     /**
965      *  Sorts by commodity index ascending, then price ascending, then
966      *  stall id ascending.
967      */
968     public int compareTo(Sell sell) {
969       // organize by: commodity index, price, stall index
970       if(commodity == sell.commodity) {
971         // organize by price, then by stall index
972         if(price == sell.price) {
973           // organize by stall index
974           return shoppe>sell.shoppe ? 1 : -1;
975         } else if(price > sell.price) {
976           return 1;
977         } else {
978           return -1;
979         }
980       } else if(commodity > sell.commodity) {
981         return 1;
982       } else {
983         return -1;
984       }
985     }
986   }
987
988   /**
989    *    Gets the list of commodities and their associated commodity ids.
990    *
991    *    @return a map where the key is the commodity and the value is
992    *    the commodity id.
993    */
994   private HashMap<String,Integer> getCommodMap() {
995     on_our_thread();
996     if(commodMap != null) {
997       return commodMap;
998     }
999     HashMap<String,Integer> map = new HashMap<String,Integer>();
1000     String xml;
1001     try {
1002       URL host = new URL(PCTB_HOST_URL + "commodmap.php");
1003       BufferedReader br =
1004         new BufferedReader(new InputStreamReader(host.openStream()));
1005       StringBuilder sb = new StringBuilder();
1006       String str;
1007       while((str = br.readLine()) != null) {
1008         sb.append(str);
1009       }
1010       if (dtxt != null)
1011         debug_write_stringdata("pctb-commodmap.xmlish", sb.toString());
1012       int first = sb.indexOf("<pre>") + 5;
1013       int last = sb.indexOf("</body>");
1014       xml = sb.substring(first,last);
1015       Reader reader = new CharArrayReader(xml.toCharArray());
1016       Document d = DocumentBuilderFactory.newInstance()
1017         .newDocumentBuilder().parse(new InputSource(reader));
1018       NodeList maps = d.getElementsByTagName("CommodMap");
1019       for(int i=0;i<maps.getLength();i++) {
1020         NodeList content = maps.item(i).getChildNodes();
1021         Integer num = Integer.parseInt(content.item(1).getTextContent());
1022         map.put(content.item(0).getTextContent(),num);
1023       }
1024     } catch(Exception e) {
1025       e.printStackTrace();
1026       error("Unable to load Commodity list from server!");
1027       return null;
1028     }
1029     commodMap = map;
1030     return map;
1031   }
1032         
1033   /**
1034    *    Given the list of offers, this method will find all the unique
1035    *    stall names and return them in a <code>LinkedHashMap</code>
1036    *    where the key is the stall name and the value is the generated
1037    *    stall id (position in the list).  <p> The reason this method
1038    *    returns a LinkedHashMap instead of a simple HashMap is the
1039    *    need for iterating over the stall names in insertion order for
1040    *    output to the server.
1041    *
1042    *    @param offers the list of records from the commodity buy/sell interface
1043    *    @return an iterable ordered map of the stall names and
1044    *    generated stall ids
1045    */
1046   private LinkedHashMap<String,Integer> getStallMap
1047     (ArrayList<ArrayList<String>> offers) {
1048     int count = 0;
1049     LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
1050     for(ArrayList<String> offer : offers) {
1051       String shop = offer.get(1);
1052       if(!map.containsKey(shop)) {
1053         count++;
1054         map.put(shop,count);
1055       }
1056     }
1057     return map;
1058   }
1059         
1060   /**
1061    *    Gets a sorted list of Buys and Sells from the list of
1062    *    records. <code>buys</code> and <code>sells</code> should be
1063    *    pre-initialized and passed into the method to receive the
1064    *    data.  Returns a 2-length int array with the number of buys
1065    *    and sells found.
1066    *    
1067    *    @param offers the data found from the market table in-game
1068    *    @param buys an empty initialized <code>TreeSet&lt;Offer&gt;</code> to
1069    *    hold the Buy offers.
1070    *    @param sells an empty initialized <code>TreeSet&lt;Offer&gt;</code> to
1071    *    hold the Sell offers.
1072    *    @param stalls the map of stalls to their ids
1073    *    @param commodMap the map of commodities to their ids
1074    *    @return a 2-length int[] array containing the number of buys
1075    *    and sells, respectively
1076    */
1077   private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers, 
1078                                TreeSet<Offer> buys, 
1079                                TreeSet<Offer> sells, 
1080                                LinkedHashMap<String,Integer> stalls, 
1081                                HashMap<String,Integer> commodMap) {
1082     int[] buySellCount = new int[2];
1083     for(ArrayList<String> offer : offers) {
1084       try {
1085         if(offer.get(2) != null) {
1086           buys.add(new Buy(offer,stalls,commodMap));
1087           buySellCount[0]++;
1088         }
1089         if(offer.get(4) != null) {
1090           sells.add(new Sell(offer,stalls,commodMap));
1091           buySellCount[1]++;
1092         }
1093       } catch(IllegalArgumentException e) {
1094         unknownPCTBcommods++;
1095         debuglog("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
1096       }
1097     }
1098     if (buySellCount[0]==0 && buySellCount[1]==0) {
1099       error("No (valid) offers for PCTB?!");
1100       throw new IllegalArgumentException();
1101     }
1102     return buySellCount;
1103   }
1104         
1105   /**
1106    *    Prepares the list of stalls for writing to the output stream.
1107    *    The <code>String</code> returned by this method is ready to be
1108    *    written directly to the stream.  <p> All shoppe names are left
1109    *    as they are. Stall names are abbreviated just before the
1110    *    apostrophe in the possessive, with an "^" and a letter
1111    *    matching the stall's type appended. Example: "Burninator's
1112    *    Ironworking Stall" would become "Burninator^I".
1113    *
1114    *    @param stallMap the map of stalls and stall ids in an iterable order
1115    *    @return a <code>String</code> containing the list of stalls in
1116    *    format ready to be written to the output stream.
1117    */
1118   private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
1119     // set up some mapping
1120     HashMap<String,String> types = new HashMap<String,String>();
1121     types.put("Apothecary Stall", "A");
1122     types.put("Distilling Stall", "D");
1123     types.put("Furnishing Stall", "F");
1124     types.put("Ironworking Stall", "I");
1125     types.put("Shipbuilding Stall", "S");
1126     types.put("Tailoring Stall", "T");
1127     types.put("Weaving Stall", "W");
1128                 
1129     StringBuilder sb = new StringBuilder();
1130     for(String name : stallMap.keySet()) {
1131       int index = name.indexOf("'s");
1132       String finalName = name;
1133       String type = null;
1134       if (index > 0) {
1135         finalName = name.substring(0,index);
1136         if(index + 2 < name.length()) {
1137           String end = name.substring(index+2,name.length()).trim();
1138           type = types.get(end);
1139         }
1140       }
1141       if(type==null) {
1142         sb.append(name+"\n");
1143       } else {
1144         sb.append(finalName+"^"+type+"\n");
1145       }
1146     }
1147     return sb.toString();
1148   }
1149         
1150   /**
1151    *    Writes a list of offers in correct format to the output stream.
1152    *    <p>
1153    *    The format is thus: (all numbers are 2-byte integers in
1154    *    little-endian format) (number of offers of this type, aka
1155    *    buy/sell) (commodity ID) (number of offers for this commodity)
1156    *    [shopID price qty][shopID price qty]...
1157    *
1158    *    @param out the output stream to write the data to
1159    *    @param offers the offers to write
1160    */
1161   private void writeOffers(OutputStream out, TreeSet<Offer> offers)
1162   throws IOException {
1163     ByteArrayOutputStream buffer = new ByteArrayOutputStream();
1164     if(offers.size() == 0) {
1165       // nothing to write, and "0" has already been written
1166       return;
1167     }
1168     int commodity = offers.first().commodity;
1169     int count = 0;
1170     for(Offer offer : offers) {
1171       if(commodity != offer.commodity) {
1172         // write out buffer
1173         writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
1174         buffer.reset();
1175         commodity = offer.commodity;
1176         count = 0;
1177       }
1178       writeLEShort(offer.shoppe,buffer); // stall index
1179       writeLEShort(offer.price,buffer); // buy price
1180       writeLEShort(offer.quantity,buffer); // buy qty
1181       count++;
1182     }
1183     writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
1184   }
1185         
1186   /**
1187    *    Writes the buffered data to the output strea for one commodity.
1188    *    
1189    *    @param out the stream to write to
1190    *    @param buffer the buffered data to write
1191    *    @param commodity the commmodity id to write before the buffered data
1192    *    @param count the number of offers for this commodity to write
1193    *    before the data
1194    */
1195   private void writeBufferedOffers(OutputStream out, byte[] buffer, 
1196                                    int commodity, int count)
1197   throws IOException {
1198     writeLEShort(commodity,out); // commod index
1199     writeLEShort(count,out); // offer count
1200     out.write(buffer); // the buffered offers
1201   }
1202         
1203   /**
1204    *    Writes the buy and sell offers to the outputstream by calling
1205    *    other methods.
1206    *    
1207    *    @param buys list of Buy offers to write
1208    *    @param sells list of Sell offers to write
1209    *    @param offerCount 2-length int array containing the number of
1210    *    buys and sells to write out
1211    *    @param out the stream to write to
1212    */
1213   private void writeBuySellOffers(TreeSet<Offer> buys,
1214                                   TreeSet<Offer> sells,
1215                                   int[] offerCount, OutputStream out) 
1216   throws IOException {
1217     // # buy offers
1218     writeLEShort(offerCount[0],out);
1219     writeOffers(out,buys);
1220     // # sell offers
1221     writeLEShort(offerCount[1],out);
1222     writeOffers(out,sells);
1223   }
1224         
1225   private String readstreamstring(InputStream in) throws IOException {
1226     StringBuilder sb = new StringBuilder();
1227     BufferedReader br = new BufferedReader(new InputStreamReader(in));
1228     String str;
1229     while((str = br.readLine()) != null) {
1230       sb.append(str+"\n");
1231     }
1232     return sb.toString();
1233   }
1234
1235   /**
1236    *    Sends the data to the server via multipart-formdata POST,
1237    *    with the gzipped data as a file upload.
1238    *
1239    *    @param file an InputStream open to the gzipped data we want to send
1240    */
1241   private InputStream sendInitialData(InputStream file) throws IOException {
1242     on_our_thread();
1243     ClientHttpRequest http =
1244       new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
1245     http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
1246     if (!http.post()) {
1247       String err = readstreamstring(http.resultstream());
1248       error("Error sending initial data:\n"+err);
1249       return null;
1250     }
1251     return http.resultstream();
1252   }
1253         
1254   /**
1255    *    Utility method to write a 2-byte int in little-endian form to
1256    *    an output stream.
1257    *
1258    *    @param num an integer to write
1259    *    @param out stream to write to
1260    */
1261   private void writeLEShort(int num, OutputStream out) throws IOException {
1262     out.write(num & 0xFF);
1263     out.write((num >>> 8) & 0xFF);
1264   }
1265         
1266   /**
1267    *    Reads the response from the server, and selects the correct parameters
1268    *    which are sent in a GET request to the server asking it to confirm
1269    *    the upload and accept the data into the database. Notably, the island id
1270    *    and ocean id are determined, while other parameter such as the filename
1271    *    are determined from the hidden form fields.
1272    *
1273    *    @param in stream of data from the server to read
1274    */
1275   private boolean finishUpload(InputStream in) throws IOException {
1276     on_our_thread();
1277
1278     String html = readstreamstring(in);
1279     debug_write_stringdata("pctb-initial.html", html);
1280     Matcher m;
1281
1282     Pattern params = Pattern.compile
1283       ("(?s)<input type=\"hidden\" name=\"action\" value=\"setisland\" />"+
1284        ".+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />"+
1285        ".+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
1286     m = params.matcher(html);
1287     if(!m.find()) {
1288       error_html("The PCTB server returned unusual data."+
1289                  " Maybe you're using an old version of the uploader?",
1290                  html);
1291       return false;
1292     }
1293     String forceReload = m.group(1);
1294     String filename = m.group(2);
1295     
1296     Pattern oceanNumPat =
1297       Pattern.compile("<option value=\"(\\d+)\">"+oceanName+"</option>");
1298     m = oceanNumPat.matcher(html);
1299     if (!m.find()) {
1300       error_html("Unable to find the ocean in the server's list of oceans!",
1301                  html);
1302       return false;
1303     }
1304     String oceanNum = m.group(1);
1305
1306     Pattern oceanIslandNum =
1307       Pattern.compile("islands\\[" + oceanNum
1308                       + "\\]\\[\\d+\\]=new Option\\(\"" + islandName
1309                       + "\",(\\d+)");
1310     m = oceanIslandNum.matcher(html);
1311     if(!m.find()) {
1312       error_html("This does not seem to be a valid island! Unable to upload.",
1313                  html);
1314       return false;
1315     }
1316     String islandNum = m.group(1);
1317
1318     URL get = new URL(PCTB_HOST_URL +
1319                       "upload.php?action=setisland&ocean=" + oceanNum
1320                       + "&island=" + islandNum
1321                       + "&forcereload=" + forceReload
1322                       + "&filename=" + filename);
1323     String complete = readstreamstring(get.openStream());
1324     debug_write_stringdata("pctb-final.html", complete);
1325     Pattern done = Pattern.compile
1326       ("Your data has been integrated into the database. Thank you!");
1327     m = done.matcher(complete);
1328     if(m.find()) {
1329       return true;
1330     } else {
1331       error_html("Something was wrong with the final upload parameters!",
1332                  complete);
1333       return false;
1334     }
1335   }
1336
1337
1338   /*****************************************
1339    * YARRG-SPECIFIC HELPER FUNCTIONS ETC.  *
1340    *****************************************/
1341
1342   private InputStream post_for_yarrg(ClientHttpRequest http)
1343   throws IOException {
1344     on_our_thread();
1345     if (!http.post()) {
1346       String err = readstreamstring(http.resultstream());
1347       error("<html><h1>Error reported by YARRG server</h1>\n" + err);
1348       return null;
1349     }
1350     return http.resultstream();
1351   }
1352
1353   private class YarrgTimestampFetcher extends Thread {
1354     public YarrgTimestampFetcher(int counter) {
1355       super("MarketUploader-YarrgTimestampFetcher-"+uploadcounter);
1356     }
1357     public String ts = null;
1358     public void run() {
1359       try {
1360         ts = getYarrgTimestamp();
1361         debuglog("(async) yarrg timestamp ready.");
1362       } catch(Exception e) {
1363         error("Error getting YARRG timestamp: "+e);
1364       }
1365     }
1366   };
1367
1368   private String getYarrgTimestamp() throws IOException {
1369     ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1370     http.setParameter("clientname", YARRG_CLIENTNAME);
1371     http.setParameter("clientversion", YARRG_CLIENTVERSION);
1372     http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1373     http.setParameter("requesttimestamp", "y");
1374     InputStream in = post_for_yarrg(http);
1375     if (in == null) return null;
1376     BufferedReader br = new BufferedReader(new InputStreamReader(in));
1377     String tsresult = br.readLine();
1378     return tsresult.substring(3, tsresult.length()-1);
1379   }
1380
1381   private boolean runYarrg(String timestamp, String ocean, String island,
1382                            String yarrgdata) throws IOException {
1383     ByteArrayOutputStream bos = new ByteArrayOutputStream();
1384     BufferedOutputStream bufos =
1385       new BufferedOutputStream(new GZIPOutputStream(bos));
1386     bufos.write(yarrgdata.getBytes() );
1387     bufos.close();
1388     byte[] compressed = bos.toByteArray();
1389     debug_write_bytes("yarrg-deduped.tsv.gz", compressed);
1390     ByteArrayInputStream file = new ByteArrayInputStream(compressed);
1391
1392     ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1393     http.setParameter("clientname", YARRG_CLIENTNAME);
1394     http.setParameter("clientversion", YARRG_CLIENTVERSION);
1395     http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1396     http.setParameter("timestamp", timestamp);
1397     http.setParameter("ocean", ocean);
1398     http.setParameter("island", island);
1399     http.setParameter("data", "deduped.tsv.gz", file,
1400                       "application/octet-stream");
1401     InputStream in = post_for_yarrg(http);
1402     if (in == null) return false;
1403     String output = readstreamstring(in);
1404     if (!output.startsWith("OK")) {
1405       error("<html><h1>Unexpected output from YARRG server</h1>\n" + output);
1406       return false;
1407     }
1408     debug_write_stringdata("yarrg-result.txt", output);
1409     return true;
1410   }
1411
1412   private int calculateArbitrageCommodity(ArrayList<SortedSet<int[]>> arb_bs) {
1413     // debuglog("ARBITRAGE?");
1414     int profit = 0;
1415     SortedSet<int[]> buys = arb_bs.get(0);
1416     SortedSet<int[]> sells = arb_bs.get(1);
1417     while (true) {
1418       int[] buy, sell;
1419       try {
1420         // NB "sell" means they sell, ie we buy
1421         sell = sells.last();
1422         buy = buys.first();
1423       } catch (NoSuchElementException e) {
1424         break;
1425       }
1426
1427       int unitprofit = buy[0] - sell[0];
1428       int count = buy[1] < sell[1] ? buy[1] : sell[1];
1429       // debuglog(" sell @"+sell[0]+" x"+sell[1]
1430       //          +" buy @"+buy[0]+" x"+buy[1]
1431       //          +" => x"+count+" @"+unitprofit);
1432
1433       if (unitprofit <= 0)
1434         break;
1435             
1436       profit += count * unitprofit;
1437       buy[1] -= count;
1438       sell[1] -= count;
1439       if (buy[1]==0) buys.remove(buy);
1440       if (sell[1]==0) sells.remove(sell);
1441     }
1442     // debuglog(" PROFIT "+profit);
1443     return profit;
1444   }
1445
1446   /*****************************************
1447    * ARBITRAGE                             *
1448    *****************************************/
1449
1450   private class arbitrageOfferComparator implements Comparator {
1451     public int compare(Object o1, Object o2) {
1452       int p1 = ((int[])o1)[0];
1453       int p2 = ((int[])o2)[0];
1454       return p2 - p1;
1455     }
1456   }
1457
1458   private @SuppressWarnings("unchecked")
1459   void calculateArbitrage(ArrayList<ArrayList<String>> data) 
1460   throws InterruptedException {
1461     int arbitrage = 0;
1462     ArrayList<SortedSet<int[]>> arb_bs = null;
1463     String lastcommod = null;
1464     Comparator compar = new arbitrageOfferComparator();
1465
1466     for (ArrayList<String> row : data) {
1467       String thiscommod = row.get(0);
1468       // debuglog("ROW "+row.toString());
1469       if (lastcommod == null || !thiscommod.equals(lastcommod)) {
1470         if (lastcommod != null)
1471           arbitrage += calculateArbitrageCommodity(arb_bs);
1472         // debuglog("ROW rdy");
1473         arb_bs = new ArrayList<SortedSet<int[]>>(2);
1474         arb_bs.add(0, new TreeSet<int[]>(compar));
1475         arb_bs.add(1, new TreeSet<int[]>(compar));
1476         // debuglog("ROW init");
1477         lastcommod = thiscommod;
1478       }
1479       for (int bs = 0; bs < 2; bs++) {
1480         String pricestr = row.get(bs*2 + 2);
1481         if (pricestr == null)
1482           continue;
1483         int[] entry = new int[2];
1484         // debuglog("ROW BS "+bs);
1485         entry[0] = parseQty(pricestr);
1486         entry[1] = parseQty(row.get(bs*2 + 3));
1487         arb_bs.get(bs).add(entry);
1488       }
1489     }
1490     arbitrage += calculateArbitrageCommodity(arb_bs);
1491     String arb;
1492     if (arbitrage != 0) {
1493       arb = "<html><strong>arbitrage: "+arbitrage+" poe</strong>";
1494     } else {
1495       arb = "no arbitrage";
1496     }
1497     final String arb_final = arb;
1498     EventQueue.invokeLater(new Runnable() { public void run() {
1499       arbitrageResult.setText(arb_final);
1500     }});
1501   }
1502     
1503 }