JAL-1712 fixes/tests for Castor binding and 'show flanking regions'
[jalview.git] / src / jalview / datamodel / xdb / embl / EmblEntry.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.datamodel.xdb.embl;
22
23 import java.util.Enumeration;
24 import java.util.Hashtable;
25 import java.util.Iterator;
26 import java.util.Vector;
27
28 import jalview.datamodel.DBRefEntry;
29 import jalview.datamodel.DBRefSource;
30 import jalview.datamodel.FeatureProperties;
31 import jalview.datamodel.Mapping;
32 import jalview.datamodel.Sequence;
33 import jalview.datamodel.SequenceFeature;
34 import jalview.datamodel.SequenceI;
35
36 /**
37  * Data model for one entry returned from an EMBL query, as marshalled by a
38  * Castor binding file
39  * 
40  * For example: http://www.ebi.ac.uk/Tools/dbfetch/dbfetch/embl/x53828/emblxml
41  * 
42  * @see embl_mapping.xml
43  */
44 public class EmblEntry
45 {
46   String accession;
47
48   String version;
49
50   String taxDivision;
51
52   String desc;
53
54   String rCreated;
55
56   String rLastUpdated;
57
58   String lastUpdated;
59
60   Vector<String> keywords;
61
62   Vector<DBRefEntry> dbRefs;
63
64   Vector<EmblFeature> features;
65
66   EmblSequence sequence;
67
68   /**
69    * @return the accession
70    */
71   public String getAccession()
72   {
73     return accession;
74   }
75
76   /**
77    * @param accession
78    *          the accession to set
79    */
80   public void setAccession(String accession)
81   {
82     this.accession = accession;
83   }
84
85   /**
86    * @return the dbRefs
87    */
88   public Vector<DBRefEntry> getDbRefs()
89   {
90     return dbRefs;
91   }
92
93   /**
94    * @param dbRefs
95    *          the dbRefs to set
96    */
97   public void setDbRefs(Vector<DBRefEntry> dbRefs)
98   {
99     this.dbRefs = dbRefs;
100   }
101
102   /**
103    * @return the desc
104    */
105   public String getDesc()
106   {
107     return desc;
108   }
109
110   /**
111    * @param desc
112    *          the desc to set
113    */
114   public void setDesc(String desc)
115   {
116     this.desc = desc;
117   }
118
119   /**
120    * @return the features
121    */
122   public Vector<EmblFeature> getFeatures()
123   {
124     return features;
125   }
126
127   /**
128    * @param features
129    *          the features to set
130    */
131   public void setFeatures(Vector<EmblFeature> features)
132   {
133     this.features = features;
134   }
135
136   /**
137    * @return the keywords
138    */
139   public Vector<String> getKeywords()
140   {
141     return keywords;
142   }
143
144   /**
145    * @param keywords
146    *          the keywords to set
147    */
148   public void setKeywords(Vector<String> keywords)
149   {
150     this.keywords = keywords;
151   }
152
153   /**
154    * @return the lastUpdated
155    */
156   public String getLastUpdated()
157   {
158     return lastUpdated;
159   }
160
161   /**
162    * @param lastUpdated
163    *          the lastUpdated to set
164    */
165   public void setLastUpdated(String lastUpdated)
166   {
167     this.lastUpdated = lastUpdated;
168   }
169
170   /**
171    * @return the releaseCreated
172    */
173   public String getRCreated()
174   {
175     return rCreated;
176   }
177
178   /**
179    * @param releaseCreated
180    *          the releaseCreated to set
181    */
182   public void setRCreated(String releaseCreated)
183   {
184     this.rCreated = releaseCreated;
185   }
186
187   /**
188    * @return the releaseLastUpdated
189    */
190   public String getRLastUpdated()
191   {
192     return rLastUpdated;
193   }
194
195   /**
196    * @param releaseLastUpdated
197    *          the releaseLastUpdated to set
198    */
199   public void setRLastUpdated(String releaseLastUpdated)
200   {
201     this.rLastUpdated = releaseLastUpdated;
202   }
203
204   /**
205    * @return the sequence
206    */
207   public EmblSequence getSequence()
208   {
209     return sequence;
210   }
211
212   /**
213    * @param sequence
214    *          the sequence to set
215    */
216   public void setSequence(EmblSequence sequence)
217   {
218     this.sequence = sequence;
219   }
220
221   /**
222    * @return the taxDivision
223    */
224   public String getTaxDivision()
225   {
226     return taxDivision;
227   }
228
229   /**
230    * @param taxDivision
231    *          the taxDivision to set
232    */
233   public void setTaxDivision(String taxDivision)
234   {
235     this.taxDivision = taxDivision;
236   }
237
238   /**
239    * @return the version
240    */
241   public String getVersion()
242   {
243     return version;
244   }
245
246   /**
247    * @param version
248    *          the version to set
249    */
250   public void setVersion(String version)
251   {
252     this.version = version;
253   }
254
255   /*
256    * EMBL Feature support is limited. The text below is included for the benefit
257    * of any developer working on improving EMBL feature import in Jalview.
258    * Extract from EMBL feature specification see
259    * http://www.embl-ebi.ac.uk/embl/Documentation
260    * /FT_definitions/feature_table.html 3.5 Location 3.5.1 Purpose
261    * 
262    * The location indicates the region of the presented sequence which
263    * corresponds to a feature.
264    * 
265    * 3.5.2 Format and conventions The location contains at least one sequence
266    * location descriptor and may contain one or more operators with one or more
267    * sequence location descriptors. Base numbers refer to the numbering in the
268    * entry. This numbering designates the first base (5' end) of the presented
269    * sequence as base 1. Base locations beyond the range of the presented
270    * sequence may not be used in location descriptors, the only exception being
271    * location in a remote entry (see 3.5.2.1, e).
272    * 
273    * Location operators and descriptors are discussed in more detail below.
274    * 
275    * 3.5.2.1 Location descriptors
276    * 
277    * The location descriptor can be one of the following: (a) a single base
278    * number (b) a site between two indicated adjoining bases (c) a single base
279    * chosen from within a specified range of bases (not allowed for new entries)
280    * (d) the base numbers delimiting a sequence span (e) a remote entry
281    * identifier followed by a local location descriptor (i.e., a-d)
282    * 
283    * A site between two adjoining nucleotides, such as endonucleolytic cleavage
284    * site, is indicated by listing the two points separated by a carat (^). The
285    * permitted formats for this descriptor are n^n+1 (for example 55^56), or,
286    * for circular molecules, n^1, where "n" is the full length of the molecule,
287    * ie 1000^1 for circular molecule with length 1000.
288    * 
289    * A single base chosen from a range of bases is indicated by the first base
290    * number and the last base number of the range separated by a single period
291    * (e.g., '12.21' indicates a single base taken from between the indicated
292    * points). From October 2006 the usage of this descriptor is restricted : it
293    * is illegal to use "a single base from a range" (c) either on its own or in
294    * combination with the "sequence span" (d) descriptor for newly created
295    * entries. The existing entries where such descriptors exist are going to be
296    * retrofitted.
297    * 
298    * Sequence spans are indicated by the starting base number and the ending
299    * base number separated by two periods (e.g., '34..456'). The '<' and '>'
300    * symbols may be used with the starting and ending base numbers to indicate
301    * that an end point is beyond the specified base number. The starting and
302    * ending base positions can be represented as distinct base numbers
303    * ('34..456') or a site between two indicated adjoining bases.
304    * 
305    * A location in a remote entry (not the entry to which the feature table
306    * belongs) can be specified by giving the accession-number and sequence
307    * version of the remote entry, followed by a colon ":", followed by a
308    * location descriptor which applies to that entry's sequence (i.e.
309    * J12345.1:1..15, see also examples below)
310    * 
311    * 3.5.2.2 Operators
312    * 
313    * The location operator is a prefix that specifies what must be done to the
314    * indicated sequence to find or construct the location corresponding to the
315    * feature. A list of operators is given below with their definitions and most
316    * common format.
317    * 
318    * complement(location) Find the complement of the presented sequence in the
319    * span specified by " location" (i.e., read the complement of the presented
320    * strand in its 5'-to-3' direction)
321    * 
322    * join(location,location, ... location) The indicated elements should be
323    * joined (placed end-to-end) to form one contiguous sequence
324    * 
325    * order(location,location, ... location) The elements can be found in the
326    * specified order (5' to 3' direction), but nothing is implied about the
327    * reasonableness about joining them
328    * 
329    * Note : location operator "complement" can be used in combination with
330    * either " join" or "order" within the same location; combinations of "join"
331    * and "order" within the same location (nested operators) are illegal.
332    * 
333    * 
334    * 
335    * 3.5.3 Location examples
336    * 
337    * The following is a list of common location descriptors with their meanings:
338    * 
339    * Location Description
340    * 
341    * 467 Points to a single base in the presented sequence
342    * 
343    * 340..565 Points to a continuous range of bases bounded by and including the
344    * starting and ending bases
345    * 
346    * <345..500 Indicates that the exact lower boundary point of a feature is
347    * unknown. The location begins at some base previous to the first base
348    * specified (which need not be contained in the presented sequence) and
349    * continues to and includes the ending base
350    * 
351    * <1..888 The feature starts before the first sequenced base and continues to
352    * and includes base 888
353    * 
354    * 1..>888 The feature starts at the first sequenced base and continues beyond
355    * base 888
356    * 
357    * 102.110 Indicates that the exact location is unknown but that it is one of
358    * the bases between bases 102 and 110, inclusive
359    * 
360    * 123^124 Points to a site between bases 123 and 124
361    * 
362    * join(12..78,134..202) Regions 12 to 78 and 134 to 202 should be joined to
363    * form one contiguous sequence
364    * 
365    * 
366    * complement(34..126) Start at the base complementary to 126 and finish at
367    * the base complementary to base 34 (the feature is on the strand
368    * complementary to the presented strand)
369    * 
370    * 
371    * complement(join(2691..4571,4918..5163)) Joins regions 2691 to 4571 and 4918
372    * to 5163, then complements the joined segments (the feature is on the strand
373    * complementary to the presented strand)
374    * 
375    * join(complement(4918..5163),complement(2691..4571)) Complements regions
376    * 4918 to 5163 and 2691 to 4571, then joins the complemented segments (the
377    * feature is on the strand complementary to the presented strand)
378    * 
379    * J00194.1:100..202 Points to bases 100 to 202, inclusive, in the entry (in
380    * this database) with primary accession number 'J00194'
381    * 
382    * join(1..100,J00194.1:100..202) Joins region 1..100 of the existing entry
383    * with the region 100..202 of remote entry J00194
384    */
385   /**
386    * Recover annotated sequences from EMBL file
387    * 
388    * @param noNa
389    *          don't return nucleic acid sequences
390    * @param sourceDb
391    *          TODO
392    * @param noProtein
393    *          don't return any translated protein sequences marked in features
394    * @return dataset sequences with DBRefs and features - DNA always comes first
395    */
396   public jalview.datamodel.SequenceI[] getSequences(boolean noNa,
397           boolean noPeptide, String sourceDb)
398   { // TODO: ensure emblEntry.getSequences behaves correctly for returning all
399     // cases of noNa and noPeptide
400     Vector seqs = new Vector();
401     Sequence dna = null;
402     if (!noNa)
403     {
404       // In theory we still need to create this if noNa is set to avoid a null
405       // pointer exception
406       dna = new Sequence(sourceDb + "|" + accession, sequence.getSequence());
407       dna.setDescription(desc);
408       DBRefEntry retrievedref = new DBRefEntry(sourceDb, version, accession);
409       dna.addDBRef(retrievedref);
410       // add map to indicate the sequence is a valid coordinate frame for the
411       // dbref
412       retrievedref.setMap(new Mapping(null, new int[]
413       { 1, dna.getLength() }, new int[]
414       { 1, dna.getLength() }, 1, 1));
415       // TODO: transform EMBL Database refs to canonical form
416       if (dbRefs != null)
417       {
418         for (Iterator i = dbRefs.iterator(); i.hasNext(); dna
419                 .addDBRef((DBRefEntry) i.next()))
420         {
421           ;
422         }
423       }
424     }
425     try
426     {
427       for (Iterator i = features.iterator(); i.hasNext();)
428       {
429         EmblFeature feature = (EmblFeature) i.next();
430         if (!noNa)
431         {
432           if (feature.dbRefs != null && feature.dbRefs.size() > 0)
433           {
434             for (Iterator dbr = feature.dbRefs.iterator(); dbr.hasNext(); dna
435                     .addDBRef((DBRefEntry) dbr.next()))
436             {
437               ;
438             }
439           }
440         }
441         if (FeatureProperties.isCodingFeature(sourceDb, feature.getName()))
442         {
443           parseCodingFeature(feature, sourceDb, seqs, dna, noPeptide);
444         }
445         else
446         {
447           // General feature type.
448           if (!noNa)
449           {
450             if (feature.dbRefs != null && feature.dbRefs.size() > 0)
451             {
452               for (Iterator dbr = feature.dbRefs.iterator(); dbr.hasNext(); dna
453                       .addDBRef((DBRefEntry) dbr.next()))
454               {
455                 ;
456               }
457             }
458           }
459         }
460       }
461     } catch (Exception e)
462     {
463       System.err.println("EMBL Record Features parsing error!");
464       System.err
465               .println("Please report the following to help@jalview.org :");
466       System.err.println("EMBL Record " + accession);
467       System.err.println("Resulted in exception: " + e.getMessage());
468       e.printStackTrace(System.err);
469     }
470     if (!noNa && dna != null)
471     {
472       seqs.add(dna);
473     }
474     SequenceI[] sqs = new SequenceI[seqs.size()];
475     for (int i = 0, j = seqs.size(); i < j; i++)
476     {
477       sqs[i] = (SequenceI) seqs.elementAt(i);
478       seqs.set(i, null);
479     }
480     return sqs;
481   }
482
483   /**
484    * attempt to extract coding region and product from a feature and properly
485    * decorate it with annotations.
486    * 
487    * @param feature
488    *          coding feature
489    * @param sourceDb
490    *          source database for the EMBLXML
491    * @param seqs
492    *          place where sequences go
493    * @param dna
494    *          parent dna sequence for this record
495    * @param noPeptide
496    *          flag for generation of Peptide sequence objects
497    */
498   private void parseCodingFeature(EmblFeature feature, String sourceDb,
499           Vector seqs, Sequence dna, boolean noPeptide)
500   {
501     boolean isEmblCdna = sourceDb.equals(DBRefSource.EMBLCDS);
502     // extract coding region(s)
503     jalview.datamodel.Mapping map = null;
504     int[] exon = null;
505     if (feature.locations != null && feature.locations.size() > 0)
506     {
507       for (Enumeration locs = feature.locations.elements(); locs
508               .hasMoreElements();)
509       {
510         EmblFeatureLocations loc = (EmblFeatureLocations) locs
511                 .nextElement();
512         int[] se = loc.getElementRanges(accession);
513         if (exon == null)
514         {
515           exon = se;
516         }
517         else
518         {
519           int[] t = new int[exon.length + se.length];
520           System.arraycopy(exon, 0, t, 0, exon.length);
521           System.arraycopy(se, 0, t, exon.length, se.length);
522           exon = t;
523         }
524       }
525     }
526     String prseq = null;
527     String prname = new String();
528     String prid = null;
529     Hashtable vals = new Hashtable();
530     int prstart = 1;
531     // get qualifiers
532     if (feature.getQualifiers() != null
533             && feature.getQualifiers().size() > 0)
534     {
535       for (Iterator quals = feature.getQualifiers().iterator(); quals
536               .hasNext();)
537       {
538         Qualifier q = (Qualifier) quals.next();
539         if (q.getName().equals("translation"))
540         {
541           StringBuffer prsq = new StringBuffer(q.getValues()[0]);
542           int p = prsq.indexOf(" ");
543           while (p > -1)
544           {
545             prsq.deleteCharAt(p);
546             p = prsq.indexOf(" ", p);
547           }
548           prseq = prsq.toString();
549           prsq = null;
550
551         }
552         else if (q.getName().equals("protein_id"))
553         {
554           prid = q.getValues()[0];
555         }
556         else if (q.getName().equals("codon_start"))
557         {
558           prstart = Integer.parseInt(q.getValues()[0]);
559         }
560         else if (q.getName().equals("product"))
561         {
562           prname = q.getValues()[0];
563         }
564         else
565         {
566           // throw anything else into the additional properties hash
567           String[] s = q.getValues();
568           StringBuffer sb = new StringBuffer();
569           if (s != null)
570           {
571             for (int i = 0; i < s.length; i++)
572             {
573               sb.append(s[i]);
574               sb.append("\n");
575             }
576           }
577           vals.put(q.getName(), sb.toString());
578         }
579       }
580     }
581     Sequence product = null;
582     DBRefEntry protEMBLCDS = null;
583     exon = adjustForPrStart(prstart, exon);
584     boolean noProteinDbref=true;
585     
586     if (prseq != null && prname != null && prid != null)
587     {
588       // extract proteins.
589       product = new Sequence(prid, prseq, 1, prseq.length());
590       product.setDescription(((prname.length() == 0) ? "Protein Product from "
591               + sourceDb
592               : prname));
593       if (!noPeptide)
594       {
595         // Protein is also added to vector of sequences returned
596         seqs.add(product);
597       }
598       // we have everything - create the mapping and perhaps the protein
599       // sequence
600       if (exon == null || exon.length == 0)
601       {
602         System.err
603                 .println("Implementation Notice: EMBLCDS records not properly supported yet - Making up the CDNA region of this sequence... may be incorrect ("
604                         + sourceDb + ":" + getAccession() + ")");
605         if (prseq.length() * 3 == (1 - prstart + dna.getSequence().length))
606         {
607           System.err
608                   .println("Not allowing for additional stop codon at end of cDNA fragment... !");
609           // this might occur for CDS sequences where no features are
610           // marked.
611           exon = new int[]
612           { dna.getStart() + (prstart - 1), dna.getEnd() };
613           map = new jalview.datamodel.Mapping(product, exon, new int[]
614           { 1, prseq.length() }, 3, 1);
615         }
616         if ((prseq.length() + 1) * 3 == (1 - prstart + dna.getSequence().length))
617         {
618           System.err
619                   .println("Allowing for additional stop codon at end of cDNA fragment... will probably cause an error in VAMSAs!");
620           exon = new int[]
621           { dna.getStart() + (prstart - 1), dna.getEnd() - 3 };
622           map = new jalview.datamodel.Mapping(product, exon, new int[]
623           { 1, prseq.length() }, 3, 1);
624         }
625       }
626       else
627       {
628         // Trim the exon mapping if necessary - the given product may only be a
629         // fragment of a larger protein. (EMBL:AY043181 is an example)
630
631         if (isEmblCdna)
632         {
633           // TODO: Add a DbRef back to the parent EMBL sequence with the exon
634           // map
635           // if given a dataset reference, search dataset for parent EMBL
636           // sequence if it exists and set its map
637           // make a new feature annotating the coding contig
638         }
639         else
640         {
641           // final product length trunctation check
642
643           map = new jalview.datamodel.Mapping(product,
644                   adjustForProteinLength(prseq.length(), exon), new int[]
645                   { 1, prseq.length() }, 3, 1);
646           // reconstruct the EMBLCDS entry
647           // TODO: this is only necessary when there codon annotation is
648           // complete (I think JBPNote)
649           DBRefEntry pcdnaref = new DBRefEntry();
650           pcdnaref.setAccessionId(prid);
651           pcdnaref.setSource(DBRefSource.EMBLCDS);
652           pcdnaref.setVersion(getVersion()); // same as parent EMBL version.
653           jalview.util.MapList mp = new jalview.util.MapList(new int[]
654           { 1, prseq.length() }, new int[]
655           { 1 + (prstart - 1), (prstart - 1) + 3 * prseq.length() }, 1, 3);
656           // { 1 + (prstart - 1) * 3,
657           // 1 + (prstart - 1) * 3 + prseq.length() * 3 - 1 }, new int[]
658           // { 1prstart, prstart + prseq.length() - 1 }, 3, 1);
659           pcdnaref.setMap(new Mapping(mp));
660           if (product != null)
661           {
662             product.addDBRef(pcdnaref);
663             protEMBLCDS = new DBRefEntry(pcdnaref);
664             protEMBLCDS.setSource(DBRefSource.EMBLCDSProduct);
665             product.addDBRef(protEMBLCDS);
666             
667           }     
668           
669         }
670       }
671       // add cds feature to dna seq - this may include the stop codon
672       for (int xint = 0; exon != null && xint < exon.length; xint += 2)
673       {
674         SequenceFeature sf = new SequenceFeature();
675         sf.setBegin(exon[xint]);
676         sf.setEnd(exon[xint + 1]);
677         sf.setType(feature.getName());
678         sf.setFeatureGroup(sourceDb);
679         sf.setDescription("Exon " + (1 + xint / 2)
680                 + " for protein '" + prname + "' EMBLCDS:" + prid);
681         sf.setValue(FeatureProperties.EXONPOS, new Integer(1 + xint));
682         sf.setValue(FeatureProperties.EXONPRODUCT, prname);
683         if (vals != null && vals.size() > 0)
684         {
685           Enumeration kv = vals.keys();
686           while (kv.hasMoreElements())
687           {
688             Object key = kv.nextElement();
689             if (key != null)
690             {
691               sf.setValue(key.toString(), vals.get(key));
692             }
693           }
694         }
695         dna.addSequenceFeature(sf);
696       }
697     }
698     // add dbRefs to sequence
699     if (feature.dbRefs != null && feature.dbRefs.size() > 0)
700     {
701       for (Iterator dbr = feature.dbRefs.iterator(); dbr.hasNext();)
702       {
703         DBRefEntry ref = (DBRefEntry) dbr.next();
704         ref.setSource(jalview.util.DBRefUtils.getCanonicalName(ref
705                 .getSource()));
706         // Hard code the kind of protein product accessions that EMBL cite
707         if (ref.getSource().equals(jalview.datamodel.DBRefSource.UNIPROT))
708         {
709           ref.setMap(map);
710           if (map != null && map.getTo() != null)
711           {
712             map.getTo().addDBRef(
713                     new DBRefEntry(ref.getSource(), ref.getVersion(), ref
714                             .getAccessionId())); // don't copy map over.
715             if (map.getTo().getName().indexOf(prid) == 0)
716             {
717               map.getTo().setName(
718                       jalview.datamodel.DBRefSource.UNIPROT + "|"
719                               + ref.getAccessionId());
720             }
721           }
722           noProteinDbref = false;
723         }
724         if (product != null)
725         {
726           DBRefEntry pref = new DBRefEntry(ref.getSource(),
727                   ref.getVersion(), ref.getAccessionId());
728           pref.setMap(null); // reference is direct
729           product.addDBRef(pref);
730           // Add converse mapping reference
731           if (map != null)
732           {
733             Mapping pmap = new Mapping(dna, map.getMap().getInverse());
734             pref = new DBRefEntry(sourceDb, getVersion(),
735                     this.getAccession());
736             pref.setMap(pmap);
737             if (map.getTo() != null)
738             {
739               map.getTo().addDBRef(pref);
740             }
741           }
742         }
743         dna.addDBRef(ref);
744       }
745       if (noProteinDbref && product != null)
746       {
747         // add protein coding reference to dna sequence so xref matches
748         if (protEMBLCDS == null)
749         {
750           protEMBLCDS = new DBRefEntry();
751           protEMBLCDS.setAccessionId(prid);
752           protEMBLCDS.setSource(DBRefSource.EMBLCDSProduct);
753           protEMBLCDS.setVersion(getVersion());
754           protEMBLCDS
755                   .setMap(new Mapping(product, map.getMap().getInverse()));
756         }
757         product.addDBRef(protEMBLCDS);
758           
759         // Add converse mapping reference
760         if (map != null)
761         {
762           Mapping pmap = new Mapping(product, protEMBLCDS.getMap().getMap()
763                   .getInverse());
764           DBRefEntry ncMap = new DBRefEntry(protEMBLCDS);
765           ncMap.setMap(pmap);
766           if (map.getTo() != null)
767           {
768             dna.addDBRef(ncMap);
769           }
770         }
771       }
772     }
773   }
774
775   private int[] adjustForPrStart(int prstart, int[] exon)
776   {
777
778     int origxon[], sxpos = -1;
779     int sxstart, sxstop; // unnecessary variables used for debugging
780     // first adjust range for codon start attribute
781     if (prstart > 1)
782     {
783       origxon = new int[exon.length];
784       System.arraycopy(exon, 0, origxon, 0, exon.length);
785       int cdspos = 0;
786       for (int x = 0; x < exon.length && sxpos == -1; x += 2)
787       {
788         cdspos += exon[x + 1] - exon[x] + 1;
789         if (prstart <= cdspos)
790         {
791           sxpos = x;
792           sxstart = exon[x];
793           sxstop = exon[x + 1];
794           // and adjust start boundary of first exon.
795           exon[x] = exon[x + 1] - cdspos + prstart;
796           break;
797         }
798       }
799
800       if (sxpos > 0)
801       {
802         int[] nxon = new int[exon.length - sxpos];
803         System.arraycopy(exon, sxpos, nxon, 0, exon.length - sxpos);
804         exon = nxon;
805       }
806     }
807     return exon;
808   }
809
810   /**
811    * truncate the last exon interval to the prlength'th codon
812    * 
813    * @param prlength
814    * @param exon
815    * @return new exon
816    */
817   private int[] adjustForProteinLength(int prlength, int[] exon)
818   {
819
820     int origxon[], sxpos = -1, endxon = 0, cdslength = prlength * 3;
821     int sxstart, sxstop; // unnecessary variables used for debugging
822     // first adjust range for codon start attribute
823     if (prlength >= 1 && exon != null)
824     {
825       origxon = new int[exon.length];
826       System.arraycopy(exon, 0, origxon, 0, exon.length);
827       int cdspos = 0;
828       for (int x = 0; x < exon.length && sxpos == -1; x += 2)
829       {
830         cdspos += exon[x + 1] - exon[x] + 1;
831         if (cdslength <= cdspos)
832         {
833           // advanced beyond last codon.
834           sxpos = x;
835           sxstart = exon[x];
836           sxstop = exon[x + 1];
837           if (cdslength != cdspos)
838           {
839             System.err
840                     .println("Truncating final exon interval on region by "
841                             + (cdspos - cdslength));
842           }
843           // locate the new end boundary of final exon as endxon
844           endxon = exon[x + 1] - cdspos + cdslength;
845           break;
846         }
847       }
848
849       if (sxpos != -1)
850       {
851         // and trim the exon interval set if necessary
852         int[] nxon = new int[sxpos + 2];
853         System.arraycopy(exon, 0, nxon, 0, sxpos + 2);
854         nxon[sxpos + 1] = endxon; // update the end boundary for the new exon
855                                   // set
856         exon = nxon;
857       }
858     }
859     return exon;
860   }
861 }