/* -*- Syntax: java; 

 javabuyer.java

 A simple buyer agent...

 The FishMarket project...

 Francisco J. Martin & Juan A. Rodriguez
 {martin,jar}@iiia.csic.es

 Copyright (c) 1998  by the 
 Institut d'Investigacion en Intel.ligencia Artificial (IIIA), CSIC
 Campus de la Universitat Autonoma de Barcelona
 08193 Bellaterra, Barcelona, Spain
  
    
   Permission to use, copy, modify, and distribute this software and its
   documentation for any purpose and without fee is hereby granted,
   provided that this copyright and permission notice appear in all
   copies and supporting documentation, and that the name of IIIA-CSIC not
   be used in advertising or publicity pertaining to distribution of the
   software without specific, written prior permission. IIIA-CSIC makes no
   representations about the suitability of this software for any
   purpose.  It is provided "as is" without express or implied warranty.
          
   IIIA-CSIC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
   ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
   IIIA-CSIC BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
   ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
   WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
   ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
   SOFTWARE.
                   
 Created: 1998 05 02 17:11

 Last modification: 1998 05 06 21:29  */

/* ------------------------------------------------------- */
/*  Buyer                                                  */
/* ------------------------------------------------------- */

import java.io.*;
import java.util.*;

final class DBPParameters {

  public final static int Ps               =    10;
  public final static int to               =   500;
  public final static int tr               = 2000;
  public final static int Cmax        =       3;
  public final static double Sf        =       0.25;
  public final static double Pi        =       0.25;
  public final static int e               =      10;
}

final class TDescriptor{
  public final static int n               =      21;
  public final static int ta              =  5000;
  public final static int credit        = 100000;
}

final class Errors{
  
  public final static String[] messages= {"Bidding round still on",
					  "Low credit",
					  "Market already closed",
					  "Already in the auction room",
					  "First move into the settlements office",
					  "There is no bidding round on",
					  "You are out of the auction room",
					  "You have not been admitted yet",
					  "You are out of the market",
					  "You have been already admitted",
					  "You are already in the settlements office",
					  "Premature bid",
					  "Bid already submitted"
  };
  
  public static void printError(int errorCode){
    System.out.println("Error: " + messages[errorCode]);
  }
}

class Predicates{
  Vector predicateList;

  public Predicates(){
    predicateList = new Vector();
    predicateList.addElement("accept");
    predicateList.addElement("deny");
    predicateList.addElement("open_auction");
    predicateList.addElement("open_round");
    predicateList.addElement("good");
    predicateList.addElement("buyers");
    predicateList.addElement("goods");
    predicateList.addElement("offer");
    predicateList.addElement("sold");
    predicateList.addElement("sanction");
    predicateList.addElement("expulsion");
    predicateList.addElement("collision");
    predicateList.addElement("out_of_market");
    predicateList.addElement("end_round");
    predicateList.addElement("end_auction");
    predicateList.addElement("closed_market");
  }

  public int indexOf(String predicate){
    return predicateList.indexOf(predicate);
  }
}



/* ------------------------------------------------------- */
/*  Memory                                                   */
/* ------------------------------------------------------- */

class caseMemory implements Serializable{
  
  Vector[] Memory;

  public caseMemory(){
  }

  public  caseMemory(int auctions){
    Memory = new Vector[auctions];
  }

  public caseMemory(Vector[] memory){
    Vector[] Memory = new Vector[memory.length];
    this.Memory = memory;
  }

  public Vector[] getMemory(){
    return Memory;
  }

  public void casesToAuctionMemory(Vector cases, int auction){
    Memory[auction-1] = cases;
  }

  public Vector getCases(int auction){
    return Memory[auction-1];
  }

  public Vector getCases(int auction,int firstRound,int lastRound){
    Vector v1 = new Vector();
    Vector v2 = Memory[auction-1];
    for (int i = firstRound; i <= lastRound; i++)
      v1.addElement((Case)v2.elementAt(i-1));
    return v1;
  }

  public Vector getCasesBuyer(int auction,String buyer){
    Case c = null;
    Vector v1 = new Vector();
    Vector v2 = Memory[auction-1];
    for (int i = 0; i < v2.size(); i++){
      c = (Case)v2.elementAt(i);
      if (c.getBuyer().equals(buyer)) v1.addElement(c);
    }
    return v1;
  }

  public void print(int auctionNumber){
    for (int i=0; i < auctionNumber; i++){
      System.out.println("<----------------------------------------->");
      System.out.println("                      AUCTION " + (i+1));
      System.out.println("<----------------------------------------->");
      Vector v = Memory[i];
      for (int k=0; k < v.size(); k++){
	Case c = (Case)v.elementAt(k);
	c.print();
      }
    }
  }

  public void print(){
    for (int i=0; i < Memory.length; i++){
      System.out.println("<----------------------------------------->");
      System.out.println("                      AUCTION " + (i+1));
      System.out.println("<----------------------------------------->");
      Vector v =
 Memory[i];
      for (int k=0; k < v.size(); k++){
	Case c = (Case)v.elementAt(k);
	c.print();
      }
    }
  }

  public void save(String filename){
     try {
       PrintWriter out  = new PrintWriter(new BufferedWriter(new FileWriter(filename)));
       for (int i=0; i < Memory.length; i++){
	 out.println("<----------------------------------------->");
	 out.println("                      AUCTION " + (i+1));
	 out.println("<----------------------------------------->");
	 Vector v = Memory[i];
	 for (int k=0; k < v.size(); k++){
	   Case c = (Case)v.elementAt(k);
	   c.print(out);
	 }
       }
       out.close();
     } catch (IOException e) { 
       System.err.println("I/O error " + e); 
       System.exit(1); 
     }
  }

  public void save(String filename,int auctions){
     try {
       PrintWriter out  = new PrintWriter(new BufferedWriter(new FileWriter(filename)));
       for (int i=0; i < auctions; i++){
	 out.println("<----------------------------------------->");
	 out.println("                      AUCTION " + (i+1));
	 out.println("<----------------------------------------->");
	 Vector v = Memory[i];
	 for (int k=0; k < v.size(); k++){
	   Case c = (Case)v.elementAt(k);
	   c.print(out);
	 }
       }
       out.close();
     } catch (IOException e) { 
       System.err.println("I/O error " + e); 
       System.exit(1); 
     }
  }
}

/* ------------------------------------------------------- */
/*  Auction                                                   */
/* ------------------------------------------------------- */
class Auction implements Serializable{

  Goods goods;
  Vector rounds;
  Buyers buyers;

  public Auction(){
    goods = new Goods();
    rounds = new Vector();
    buyers = new Buyers();
  }

  public Buyers getBuyers(){
    return buyers;
  }

  public Goods getGoods(){
    return goods;
  }

  public void addRound(Round round){
    rounds.addElement(round);
  }

  public void addSale(String goodId, String buyer, int salePrice, int resalePrice,int round){
    goods.addSale(goodId,buyer,salePrice,round);
    buyers.addSale(goodId,buyer,salePrice,resalePrice);
  }

  public void addRetention(String goodId, int retentionPrice, int round){
    goods.addRetention(goodId,retentionPrice,round);
  }

  public Round getRound(int round){
    Round r = null;
    int i = 0;
    boolean found = false;
    while (!rounds.isEmpty() && !found){
      r = (Round)rounds.elementAt(i);
      if (r.getRoundNumber()==round)
	found=true;
      else
	i++;
    }
    return found?r:null;
  }

  public void setGoods(String lot){
    goods.setLot(lot);
  }

  public Good getGood(String goodId){
    return goods.get(goodId);
  }

  public void setBuyers(String buyers, int credit){
    this.buyers.setBuyers(buyers,credit);
  }

  public void print(){
    Round r = null;
    System.out.println("\nGOODS");
    System.out.println("------");
    goods.print();
    System.out.println("\nBUYERS");
    System.out.println("-------");
    buyers.print();
    System.out.println("\nROUNDS");
    System.out.println("-------");
    for (int i = 0 ; i < rounds.size(); i++){
      r = (Round)rounds.elementAt(i);
      r.print();
      System.out.println();
    }
  }
}

class Round implements Serializable{
  /* change buyers,fines,collisions,expulsions a Vectors*/
  int roundNumber;
  String goodId;
  String buyers;
  String fines;
  String collisions;
  String expulsions;
  boolean withdrawal;

  public Round(){
    goodId = new String();
    buyers = new String();
    fines = null;
    collisions = null;
    expulsions = null;
    withdrawal = false;
  }

  public void setRoundNumber(int roundNumber){
    this.roundNumber = roundNumber;
  }

  public int getRoundNumber(){
    return roundNumber;
  }

  public void setGoodId(String goodId){
    this.goodId = goodId;
  }

  public void setBuyers(String buyers){
    this.buyers = buyers;
  }

  public void addFine(String buyerLogin){
    if (fines == null)
      fines = buyerLogin;
    else
      fines.concat(" " + buyerLogin);
  }

  public void addCollision(String collisionPrice){
    if (collisions == null)
      collisions = collisionPrice;
    else
      collisions.concat(" " + collisionPrice);
  }
  
  public void addExpulsion(String buyerExpelled){
    if (expulsions == null)
      expulsions = buyerExpelled;
    else
      expulsions.concat(" " + buyerExpelled);
  }

  public void setWithdrawal(boolean b){
    withdrawal = b;
  }

  public void print(){
    System.out.println("Round: " + roundNumber);
    System.out.println("Good: " + goodId);
    System.out.println("Buyers: " + buyers);
    System.out.println("Fines: " + fines);
    System.out.println("Collisions: " + collisions);
    System.out.println("Expulsions: " + expulsions);
    System.out.println("Withdrawal: " + withdrawal);
  }

  public String toString(){
    return roundNumber + "\n" + goodId + "\n" + buyers + "\n" + fines + "\n" + collisions + "\n" + expulsions + "\n" + withdrawal;
  }
}

/* ------------------------------------------------------- */
/*  Goods                                                  */
/* ------------------------------------------------------- */

class Goods implements Serializable{

  Hashtable goodsList;

  public Goods(){
    goodsList = new Hashtable();
  }

  public void setLot(String lot){
    Good g;
    String type, key, seller, startingPrice, resalePrice;
    StringTokenizer s = new StringTokenizer(lot);
    while (s.hasMoreTokens()){
      key = s.nextToken();
      type = s.nextToken();
      seller = s.nextToken();
      startingPrice = s.nextToken();
      resalePrice = s.nextToken();
      g = new Good(type, seller, Integer.parseInt(startingPrice),Integer.parseInt(resalePrice));
      goodsList.put(key,g);
    }
  }

  public Good get(String key){
    return (Good)goodsList.get(key);
  }

  public int getLotSize(){
    return goodsList.size();
  }

  public void addSale(String goodId, String buyer, int salePrice, int round){
    Good g = (Good)goodsList.get(goodId);
    g.addSale(buyer,salePrice,round);
  }

  public void addRetention(String goodId, int retentionPrice, int round){
    Good g = (Good)goodsList.get(goodId);
    g.addRetention(retentionPrice,round);
  }

  public void print(){
    Good g;
    Enumeration e, k;
    for (e = goodsList.elements(), k = goodsList.keys(); e.hasMoreElements() && k.hasMoreElements(); ){
      g = (Good)e.nextElement();
      System.out.println(k.nextElement() + ":" + g);
    }
  }
}

class Good implements Serializable{

  String type;
  String seller;
  int startingPrice;
  int resalePrice;
  int salePrice;
  int retentionPrice;
  String buyer;
  int round;

  public Good(String type, String seller, int startingPrice, int resalePrice){
    this.type = type;
    this.seller = seller;
    this.startingPrice = startingPrice;
    this.resalePrice = resalePrice;
    this.retentionPrice = 0;
    this.salePrice = 0;
    buyer = null;
    round = 0;
  }

  public int getResalePrice(){
    return resalePrice;
  }

  public void addSale(String buyer, int salePrice, int round){
    this.buyer = buyer;
    this.salePrice = salePrice;
    this.round = round;
  }

  public void addRetention(int retentionPrice, int round){
    this.retentionPrice = retentionPrice;
    this.round = round;
  }

  public String toString(){
    return type + ":" + seller + ":" + startingPrice + ":" + resalePrice + ":" + salePrice + ":" + retentionPrice + ":" + buyer + ":" + round;
  }
}

/* ------------------------------------------------------- */
/*  Cases                                                                                                                */
/* ------------------------------------------------------- */

class buyerCase implements Serializable{

  int credit;
  int benefits;

  public buyerCase(int credit, int benefits){
    this.credit = credit;
    this.benefits = benefits;
  }

  public int getCredit(){
    return credit;
  }

  public int getBenefits(){
    return benefits;
  }

  public String toString(){
    return credit + ":" + benefits;
  }
}

class Case implements Serializable{

  int round;
  String goodType;
  int startingPrice;
  int resalePrice;
  Hashtable buyers;
  int rounds;
  String buyer;
  int salePrice;
  
  public Case(int round){
    this.round = round;
    buyers = new Hashtable();
  }

  public int getRound(){
    return round;
  }

  public int getStartingPrice(){
    return startingPrice;
  }

  public int getSalePrice(){
    return salePrice;
  }

  public int getResalePrice(){
    return resalePrice;
  }

  public String getBuyer(){
    return buyer;
  }

  public int getRounds(){
    return rounds;
  }

  public Hashtable getBuyers(){
    return buyers;
  }

  public int getCredit(String buyer){
    buyerCase b = (buyerCase)buyers.get(buyer);
    return b.getCredit();
  }

  public int getBenefits(String buyer){
    buyerCase b = (buyerCase)buyers.get(buyer);
    return b.getBenefits();
  }

  public void setGood(String goodType,int startingPrice,int resalePrice){
    this.goodType = goodType;
    this.startingPrice = startingPrice;
    this.resalePrice = resalePrice;
  }

  public void setRounds(int roundsLeft){
    this.rounds = roundsLeft;
  }

  public void setBuyers(Hashtable buyers){
    this.buyers = buyers;
  }

  public void addSale(String buyer, int salePrice){
    this.buyer = buyer;
    this.salePrice = salePrice;
  }

  public double attributeSimilarity(double x,double y,double delta,double epsilon){
    return Math.max(0, Math.min(1,(delta + epsilon - Math.abs(x - y)) / epsilon));
  }

  public void print(){
    buyerCase b;
    Enumeration e, k;
    System.out.println("@===CASE===@");
    System.out.println("Round: " + round);
    System.out.println("Good: " + goodType + ":" + startingPrice + ":" + resalePrice);
    System.out.print("Buyers: ");
    for (e = buyers.elements(), k = buyers.keys(); e.hasMoreElements() && k.hasMoreElements(); ){
      b = (buyerCase)e.nextElement();
      System.out.print(k.nextElement() + ":");
      System.out.print(b);
      System.out.print("#");
    }
    System.out.println();
    System.out.println("Sale:" + buyer + ":" + salePrice);
    System.out.println("Rounds left: " + rounds);
  }

   public void print(PrintWriter out){
    buyerCase b;
    Enumeration e, k;
    out.println("@=== CASE===@");
    out.println("Round: " + round);
    out.println("Good: " + goodType + ":" + startingPrice + ":" + resalePrice);
    out.print("Buyers: ");
    for (e = buyers.elements(), k = buyers.keys(); e.hasMoreElements() && k.hasMoreElements(); ){
      b = (buyerCase)e.nextElement();
      out.print(k.nextElement() + ":");
      out.print(b);
      out.print("#");
    }
    out.println();
    out.println("Sale:" + buyer + ":" + salePrice);
    out.println("Rounds left: " + rounds);
  }
}

/* ------------------------------------------------------- */
/*  Buyers                                                                                                              */
/* ------------------------------------------------------- */

class Buyers implements Serializable{

  Hashtable buyersList;

  public Buyers(){
    buyersList = new Hashtable();
  }

  public Enumeration getLogins(){
    return buyersList.keys();
  }

  public void setBuyers(String buyers,int credit){
    String buyer;
    StringTokenizer s = new StringTokenizer(buyers);
    while (s.hasMoreTokens()){
      buyer = s.nextToken();
      buyersList.put(buyer,new buyerRecord(credit));
    }
  }

  public buyerRecord getBuyer(String buyer){
    return (buyerRecord)buyersList.get(buyer);
  }

  public void addSale(String goodId, String buyer, int salePrice,int resalePrice){
    buyerRecord b = (buyerRecord)buyersList.get(buyer);
    b.addSale(goodId,salePrice,resalePrice);
  }

  public void addFine(String buyer, int finePrice, int round){
    buyerRecord b = (buyerRecord)buyersList.get(buyer);
    b.addFine(finePrice,round);
  }

  public void addExpulsion(String buyer,int round){
    buyerRecord b = (buyerRecord)buyersList.get(buyer);
    b.addExpulsion(round);
  }

/*   public int getBenefits(String buyer){ */
/*     buyerRecord b = (buyerRecord)buyersList.get(buyer); */
/*     return b.getBenefits(); */
/*   } */

  public Hashtable getBuyersFeaturesForCase(){
    Enumeration e, k;
    buyerRecord b;
    Hashtable h = new Hashtable();
     for (e = buyersList.elements(), k = buyersList.keys(); e.hasMoreElements() && k.hasMoreElements(); ){
      b = (buyerRecord)e.nextElement();
      h.put(k.nextElement(), new buyerCase(b.getCredit(),b.getBenefits()));
     }
     return h;
  }

  public void print(){
    buyerRecord b;
    Enumeration e, k;
    for (e = buyersList.elements(), k = buyersList.keys(); e.hasMoreElements() && k.hasMoreElements(); ){
      b = (buyerRecord)e.nextElement();
      System.out.println("Login: " + k.nextElement());
      b.print();
      System.out.println();
    }
  }
}

class buyerRecord implements Serializable{
  int credit;
  int benefits;
  int expenses;
  Vector goods;
  Vector fines;
  Vector expulsions;

  public buyerRecord(int credit){
    this.credit = credit;
    benefits = 0;
    expenses = 0;
    goods = new Vector();
    fines = new Vector();
    expulsions = new Vector();
  }

  public int getCredit(){
    return credit;
  }

  public int getBenefits(){
    return benefits;
  }

  public void addSale(String goodId, int salePrice, int resalePrice){
    credit -= salePrice;
    expenses += salePrice;
    benefits += resalePrice;
    goods.addElement(goodId);
  }  

  public void addFine(int finePrice, int round){
    fines.addElement(new Fine(finePrice,round));
  }

  public void addExpulsion(int round){
    expulsions.addElement(Integer.toString(round));
  }

  public void print(){
    System.out.println("Credit: " + credit);
    System.out.println("Benefits: " + benefits);
    System.out.println("Expenses: " + expenses);
    System.out.print("Goods: ");
    for (int i = 0; i < goods.size(); i++)
      System.out.print((String)goods.elementAt(i) + ":");
    System.out.print("\nFines: ");
    for (int i = 0; i < fines.size(); i++)
      System.out.print((Fine)fines.elementAt(i));
    System.out.print("\nExpulsions: ");
    for (int i = 0; i < expulsions.size(); i++)
      System.out.print((String)expulsions.elementAt(i));
    System.out.println();
  }
}

class Fine implements Serializable{

  int round;
  int fine;

  public Fine(int fine,int round){
    this.round = round;
    this.fine = fine;
  }

  public int getRound(){
    return round;
  }

  public int getFine(){
    return fine;
  }

  public String toString(){
    return fine + ":" + round;
  }
}

/* ------------------------------------------------------- */
/*  Queue                                                  */
/* ------------------------------------------------------- */

class Element{
  String contents;
  public Element next;

  public Element(String contents){
    this.contents = contents;
    next = null;
  }

  public String get(){
    return contents;
  }

  public String toString(){
    return contents;
  }
}

class Queue{

  Element head, tail;

  public synchronized void append(Element p){
    if (tail == null)
      head = p;
    else
      tail.next = p;
    p.next = null;
    tail = p;
    notify();
    }

  public synchronized Element get(){
    try{
      while (head == null)
	wait();
    }catch(InterruptedException e){
      return null;
    }
    Element p = head;
    head = head.next;
    if (head == null)
      tail = null;
    return p;
  }

  public synchronized boolean pool(){
    if (head == null)
      return false;
    else
      return true;
  }

  public synchronized String toString(){
    String queue = new String();
    Element p = head;
    if (p != null){ 
      queue = p.toString();
      while (p != null){
	queue.concat(p.toString());
	p = p.next;
      }
    }
      return queue;
  }
}

/* ------------------------------------------------------- */
/*  Remote Control                                                  */
/* ------------------------------------------------------- */

class ChannelOut extends Thread{
  
  PrintWriter out;
  String message = null;
  String output = null;
  Queue queueOut; 
   int priority; 

   public ChannelOut(PrintWriter out,Queue queueOut,int priority){ 
     this.out = out; 
     this.queueOut = queueOut; 
     this.setPriority(priority); 
   } 

  public String toString(){
    return queueOut.toString();
  }

  public void run(){
    while(true){
      Element element = queueOut.get(); 
      out.println(element.get()); 
      out.flush(); 
    }
  }
}

class ChannelIn extends Thread{

  BufferedReader in;
  String message;
  Queue queueIn;
   int priority; 

   public ChannelIn(BufferedReader in,Queue queueIn,int priority){
     this.in = in; 
     this.queueIn = queueIn; 
     this.setPriority(priority); 
  } 

  public String toString(){
    return queueIn.toString();
  }

  public void run(){
    while(true){
      try{
	message = in.readLine();
      } catch(IOException e){
	System.err.println("Error: " + e);
	System.exit(1);
      }
      queueIn.append(new Element(message));
    }
  }
}

/* ------------------------------------------------------- */
/*  Buyer                                                 */
/* ------------------------------------------------------- */

public class javabuyer extends Thread{

  Process remoteControl;
  Queue queueIn;
  Queue queueOut;
  Vector streams;
  String mylogin;
  String mypassword;
  String mode;
  String memoryFile;
  String tourFile;
  String machine;
  String port;
  String tracemode;
  Predicates predicates;
  int credit;
  int price;
  int currentAuction;
  int currentRound;
  Auction[] tournament;
  Auction auction;
  Round round;
  Goods goods;
  Good currentGood;
  Case currentCase;
  Vector auctionCases;
  caseMemory memory;

  public javabuyer(String mylogin,String mypassword,String machine,String port,String tracemode){
    this.mylogin = mylogin;
    this.mypassword = mypassword;
    this.machine = machine;
    this.port = port;
    this.tracemode = tracemode;
    predicates = new Predicates();
    queueIn = new Queue();
    queueOut = new Queue();
    streams = new Vector();
    tournament = new Auction[TDescriptor.n];
    memory = new caseMemory(TDescriptor.n);
    currentAuction = 0;
    currentRound = 0;
  }

/* ------------------------------------------------------- */
/*  Auxiliar functions                                     */
/* ------------------------------------------------------- */

  public String getToken(String message,int position){
    String token = null;
    StringTokenizer s = new StringTokenizer(message);
    if (position <= s.countTokens()){  
      for (int i = 0; i < position; i++){
	token = s.nextToken();
      }
    }
    return token;
  }

  public void printTournament(){
    for (int i = 0; i < currentAuction; i++)
      tournament[i].print();
  }

/* ------------------------------------------------------- */
/*  Communication functions                                */
/* ------------------------------------------------------- */

   public void send(String message){ 
     queueOut.append(new Element(message)); 
   } 

  public String receive(){
    String message = null;
    if (queueIn.pool() == true){
      message = queueIn.get().get();
    }
    return message;
  }

  public Vector catchRemoteControl(){
    BufferedReader pannel;
    PrintWriter remote;
    BufferedReader error;
    Vector streams = new Vector();
    String cmd[] = {"/opt/java/jdk1.1.4/bin/java","RemoteControl","-machine","oreig","-port","4400","-trace","off","-login", mylogin};
    try{
      remoteControl = Runtime.getRuntime().exec(cmd);
      pannel = new BufferedReader(new InputStreamReader(remoteControl.getInputStream()));
      remote = new PrintWriter(remoteControl.getOutputStream());
      error = new BufferedReader(new InputStreamReader(remoteControl.getErrorStream()));
      streams.addElement(pannel);
      streams.addElement(remote);
      streams.addElement(error);
    } catch (IOException e){
      System.err.println("Couldn't create child process.");
      System.exit(1);
    }
    return streams;
  }

/* ------------------------------------------------------- */
/*  Buyer messages                                     */
/* ------------------------------------------------------- */

  public void goIntoAuctionRoom(){
    String admission = "admission " + mylogin + " " + mypassword;
    send(admission);
  }

  public void bid(){
    send("bid");
    price = 0; /* Delete this when building the agent properly */
  }

  public void exit(){
    send("exit");
  }

/* ------------------------------------------------------- */
/*                                 Remote control messages                                                 */
/* ------------------------------------------------------- */

  public void openAuction(int auctionNumber){
    currentAuction = auctionNumber;
    auction = new Auction();
    auctionCases = new Vector();
  }

 public void closeAuction(int auctionNumber){
   tournament[auctionNumber-1] = auction;
   memory.casesToAuctionMemory(auctionCases, auctionNumber);
 }

 public void openRound(int roundNumber){
   currentRound = roundNumber;
   round = new Round();
   round.setRoundNumber(roundNumber);
   currentCase = new Case(roundNumber);
   currentCase.setRounds(auction.getGoods().getLotSize() - roundNumber);
 }

 public void closeRound(int roundNumber){
   auction.addRound(round);
   auctionCases.addElement(currentCase);
 }
 
 public void processMessage(String message){
   String predicate = getToken(message,1);
   switch(predicates.indexOf(predicate)){
   case 0:
      System.out.println("Welcome to the fishmarket");
      break;
    case 1:
      Errors.printError(new Integer(getToken(message,2)).intValue());
      break;
    case 2:
      openAuction(new Integer(getToken(message,2)).intValue());
      break;
    case 3:
      openRound(new Integer(getToken(message,2)).intValue());
      break;
    case 4:
      round.setGoodId(getToken(message,2));
      currentGood = auction.getGood(getToken(message,2));
      currentCase.setGood(getToken(message,3),Integer.parseInt(getToken(message,5)),Integer.parseInt(getToken(message,6)));
      break;
    case 5:
      round.setBuyers(message.substring(message.indexOf(' ')));
      if (currentRound ==1)
	auction.setBuyers(message.substring(message.indexOf(' ')),TDescriptor.credit);
      currentCase.setBuyers(auction.getBuyers().getBuyersFeaturesForCase());
      break;
    case 6:   
      auction.setGoods(message.substring(message.indexOf(' ')));
      break;
    case 7:
      price = Integer.parseInt(getToken(message,3));
      break;
    case 8:
      auction.addSale(getToken(message,2),getToken(message,3),Integer.parseInt(getToken(message,4)),currentGood.getResalePrice(),currentRound);
      currentCase.addSale(getToken(message,3),Integer.parseInt(getToken(message,4)));
      break;
    case 9:
      round.addFine(getToken(message,2));
      auction.getBuyers().addFine(getToken(message,2),Integer.parseInt(getToken(message,3)),currentRound);
      break;
    case 10:
      round.addExpulsion(getToken(message,2));
      auction.getBuyers().addExpulsion(getToken(message,2),currentRound);
      break;
    case 11:
      round.addCollision(getToken(message,2));
      break;
    case 12:
      round.setWithdrawal(true);
      auction.addRetention(getToken(message,2),Integer.parseInt(getToken(message,3)),currentRound);
      break;
    case 13:
     closeRound(new Integer(getToken(message,2)).intValue());
      break;
    case 14:
      closeAuction(new Integer(getToken(message,2)).intValue());
      break;
    case 15:
      System.exit(0);
      break;
    }
  }

 public void run(){
   streams = catchRemoteControl();
   BufferedReader pannel = (BufferedReader)streams.elementAt(0);
   PrintWriter remote = (PrintWriter)streams.elementAt(1);
   new ChannelIn(pannel,queueIn,Thread.MAX_PRIORITY).start(); 
   new ChannelOut(remote,queueOut,Thread.MAX_PRIORITY).start(); 
   goIntoAuctionRoom();
   while (currentAuction < TDescriptor.n){
     String message = receive();
     if (message != null){
       System.out.println("Received: " + message);
       processMessage(message);
       if (price == 1000)
	   bid();
     }
   }
 }

  public static void main(String[] args) {
      new javabuyer(args[0],args[1],args[2],args[3],args[4]).start();
  }
}


















