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