/**
 *  Short report, where the provided RNA sequence is expressed. Uses EST_reader and NCBI EST BLAST.
 *  Internet robot, whereExpressed, that uses form, located in page
 *  .
 *  It is your responsibility to find and cite appropriate references
 *  from this page.
 *  THIS AGENT IS NOT COMPLETE. YOU MUST FILL resultFromString method.
 *  Generated 2002.8.9  by Sight 2.0, Ulm university.
 */
package impl.rna_analysers;

import Sight.Agents.*;
import Sight.Structures.*;
import Sight.dds.*;
import java.io.*;
import java.util.*;
import Sight.Agents.util.*;

public class whereExpressed extends Sight.Agents.Prototypes.Wrapper implements Serializable {

   /** Implementation of the central go method. If string and not a
    *  request object is submitted, just url is loaded. */
   public Object go(Object iR) throws Exception
    {
      impl.Blast.blastN_ncbi.Request request = impl.Blast.blastN_ncbi.getDefaultRequest();
      request.Database="est_human";
      request.Descriptions="150";
      request.Expect="1E-3";
      request.Word_size="15";
      request.Query= ((Request) iR).Sequence.toString();

      impl.Blast.blastN_ncbi.Result blast = (Sight.Agents.Variants.sBlaster.Result)
       request.submit().getResult();

      if (blast==null)
       { p("null returned by similarity search");
         return null; };

      if (blast.a.length==0)
       { p("No similar sequences found in EST database.");
         return null; };

      p("Similarity search returned "+blast.a.length+" hits");

      impl.rna_analysers.EST_reader eAgent = new impl.rna_analysers.EST_reader();

      exprList Cells   = new exprList();
      exprList Tissues = new exprList();
      double E = 1.0;

      for (int i = 0; i < blast.a.length; i++) {
       impl.Blast.blastN_ncbi.Record r = blast.a[i];
       impl.rna_analysers.EST_reader.Request er = impl.rna_analysers.EST_reader.getDefaultRequest();
       er.Id = r.Gi.toString();
       try {
        E =  Double.parseDouble(r.E.toString().trim());
       } catch (Exception exc)
        { exc.printStackTrace(); };

       p("   checking "+er.Id);

       impl.rna_analysers.EST_reader.Result we =
        (impl.rna_analysers.EST_reader.Result) eAgent.go(er, er.Id);

       if (we!=null)
        p("N:"+we.a.length+" "+  we.getReport(0)+" Tissue "+we.a[0].Tissue+" Cell "+we.a[0].Cell);

       if (we!=null)
        if (we.a.length>0)
         for (int ii = 0; ii < we.a.length; ii++)
         {
           CharSequence Tissue = we.a[ii].Tissue;
           CharSequence Cell = we.a[ii].Cell;

           if (Tissue!=null)
            if (Tissue.toString().trim().length()>0)
             Tissues.mind(Tissue.toString().trim());

           if (Cell!=null)
            if (Cell.toString().trim().length()>0)
             Cells.mind(Cell.toString().trim());
         };
      }

      Result  result = new Result();

      StringBuffer bT = new StringBuffer();
      StringBuffer bC = new StringBuffer();

      Iterator iter;
      iter = Tissues.getList().iterator();
      while (iter.hasNext()) {
       bT.append(iter.next());
      }
      iter = Cells.getList().iterator();
      while (iter.hasNext()) {
       bC.append(iter.next());
      }

      Record [] a = new Record[1];
      a[0] = new Record();
      a[0].Cell = bC.toString();
      a[0].Tissue = bT.toString();
      result.a = a;

      result.setAgentSignature(getHTMLSignature());
      return result;
    };
 /* Data structure to pass query to this robot. */
  public class Request extends Sight.Request implements java.io.Serializable {

       public String Sequence = "";

       /** Submit request, compute key by SHA digesting algorithm. */
       public Sight.Agents.Request submit() { return Sight.Agents.Request.submit(Public, this, getKey()); };
       /** Submit request with the known key. */
       public Sight.Agents.Request submit(String key)
        { return Sight.Agents.Request.submit(Public, this, key); };
       };

   /** Get the AMap data structure, required by post method. */
  protected AMap getFormParameters(Object req) {
   throw new java.lang.Error("The method is not used by this class and must never be called."); };

  /** Get default request for this robot. */
  public static Request getDefaultRequest() {
     return Public.getRequest(); }
  private Request getRequest() { return new Request(); }; // must be non static

    /** Type definitions for Request. */
   public dStructure getRequestDds() {
    return new Sight.dds.Records(true,
     new dField[] {
        new dField("Sequence","CharSequence",null,"") }
    );
   }
 /* Record type, used in results for this robot. */
 /* The result of this robot is an array of records. */
  public static class Record extends Sight.Record implements Serializable {
        public CharSequence Tissue = "";
        public CharSequence Cell = "";
      };
      /** The result of this robot. */
      public static class Result extends Sight.Result implements Serializable {
         public Record[] a; // array of results.
         /** Create report for one record. */
         public CharSequence getReportForRecord(Object ro, int level)
          { Record r = (Record) ro;
           switch (level) {
              case 0:  return ""+r.Tissue+" "+r.Cell+" ";
              default:  return " Tissue: "+r.Tissue+" Cell:"+r.Cell+" ";
            }
          };
      }

    /** Type definitions for Result. */
   public dStructure getResultDds() {
    return new Sight.dds.Records(true,
     new dField[] {
        new dField("Tissue","CharSequence",null,""),
        new dField("Cell","CharSequence",null,"")                 }
    );
   }

  public whereExpressed() {
   setDescription("Short report, where the provided RNA sequence is expressed. Uses EST_reader and NCBI EST BLAST.");
   setMasterURL("http://www.ncbi.nlm.nih.gov/");
   setReadCache(false);
   };
  /** Public instance of agent for user. */
  public static whereExpressed Public = new whereExpressed();
  public static Agent getAvailableAgent() { return Public; };
  /** main(..) method provided to check robot, launching it
   * as standalone program. */
  public static void main(String[] args) {
  Sight.Agents.util.Pind.showConsoles();
      try {
        Request request = getDefaultRequest();
        request.Sequence = new Sight.Agents.Clones.Clone("NM_014193").getSequence();
        // Now modify and assign request fields in accordance with task:
        Sight.Agents.Request submission = request.submit();
        // processing now started in separate thread:
        Result response = (Result) submission.getResult();
        // print report, verbosity level 2:
        System.out.println(response.getReport(2));
      } catch (Exception exc)
         { if (exc!=null) System.out.println(exc.getMessage());
           exc.printStackTrace();
         };
   }
;

 /** Get result from the given html content. */
  public Sight.Result resultFromString(String html) throws Exception
  {
      throw new java.lang.Error("The method is not used by this class and must never be called.");
  };
  }


  class expr implements Comparable
   {
     int n = 1;
     String key = "";
     expr(String k) { key = k; };
     public int compareTo(Object o) {
      expr x = (expr) o;
      if (x.n>n) return 1;
      if (x.n<n) return -1;
      return key.compareTo(x.key);
     }

     public String toString()
      { StringBuffer rkey = new StringBuffer(key);
        rkey.setCharAt(0, Character.toUpperCase(rkey.charAt(0)));
        if (n==1) return rkey+". ";
        return rkey+ "("+n+"). "; };
   };

  class exprList extends java.util.TreeMap
   {
     public void mind(String hit)
      {
        expr e = (expr) get(hit);
        if (e!=null) e.n++;
         else put(hit, new expr(hit));
      };

     public List getList()
      {
        Set s = new TreeSet();

        Iterator iter = keySet().iterator();
        while (iter.hasNext()) {
          String key = (String) iter.next();
          expr e = (expr) get(key);
          s.add(e);
        }

        ArrayList l = new ArrayList();
        l.addAll(s);

        return l;

      };
   };