File: JalviewJmolBinding.java

package info (click to toggle)
jalview 2.7.dfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 10,152 kB
  • sloc: java: 162,883; xml: 1,131; haskell: 43; makefile: 20; sh: 18
file content (1561 lines) | stat: -rw-r--r-- 46,476 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
/*
 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
 * Copyright (C) 2011 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
 * 
 * This file is part of Jalview.
 * 
 * Jalview is free software: you can redistribute it and/or
 * modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 * 
 * Jalview is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty 
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
 * PURPOSE.  See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
 */
package jalview.ext.jmol;

import jalview.api.AlignmentViewPanel;
import jalview.api.FeatureRenderer;
import jalview.api.SequenceRenderer;
import jalview.api.SequenceStructureBinding;
import jalview.api.StructureSelectionManagerProvider;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.ColumnSelection;
import jalview.datamodel.PDBEntry;
import jalview.datamodel.SequenceI;
import jalview.io.AppletFormatAdapter;
import jalview.schemes.ColourSchemeI;
import jalview.schemes.ResidueProperties;
import jalview.structure.StructureListener;
import jalview.structure.StructureMapping;
import jalview.structure.StructureSelectionManager;

import java.awt.Color;
import java.awt.Container;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.io.File;
import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
import java.util.Vector;

import org.jmol.adapter.smarter.SmarterJmolAdapter;
import org.jmol.api.JmolAppConsoleInterface;
import org.jmol.api.JmolSelectionListener;
import org.jmol.api.JmolStatusListener;
import org.jmol.api.JmolViewer;
import org.jmol.constant.EnumCallback;
import org.jmol.popup.JmolPopup;

public abstract class JalviewJmolBinding implements StructureListener,
        JmolStatusListener, SequenceStructureBinding,
        JmolSelectionListener, ComponentListener, StructureSelectionManagerProvider

{
  /**
   * set if Jmol state is being restored from some source - instructs binding
   * not to apply default display style when structure set is updated for first
   * time.
   */
  private boolean loadingFromArchive = false;

  /**
   * state flag used to check if the Jmol viewer's paint method can be called
   */
  private boolean finishedInit = false;

  public boolean isFinishedInit()
  {
    return finishedInit;
  }

  public void setFinishedInit(boolean finishedInit)
  {
    this.finishedInit = finishedInit;
  }

  boolean allChainsSelected = false;

  /**
   * when true, try to search the associated datamodel for sequences that are
   * associated with any unknown structures in the Jmol view.
   */
  private boolean associateNewStructs = false;

  Vector atomsPicked = new Vector();

  public Vector chainNames;

  Hashtable chainFile;

  /**
   * array of target chains for seuqences - tied to pdbentry and sequence[]
   */
  protected String[][] chains;

  boolean colourBySequence = true;

  StringBuffer eval = new StringBuffer();

  public String fileLoadingError;

  /**
   * the default or current model displayed if the model cannot be identified
   * from the selection message
   */
  int frameNo = 0;

  protected JmolPopup jmolpopup;

  String lastCommand;

  String lastMessage;

  boolean loadedInline;

  /**
   * current set of model filenames loaded in the Jmol instance
   */
  String[] modelFileNames = null;

  public PDBEntry[] pdbentry;

  /**
   * datasource protocol for access to PDBEntrylatest
   */
  String protocol = null;

  StringBuffer resetLastRes = new StringBuffer();

  /**
   * sequences mapped to each pdbentry
   */
  public SequenceI[][] sequence;

  public StructureSelectionManager ssm;

  public JmolViewer viewer;

  public JalviewJmolBinding(StructureSelectionManager ssm, PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
          String[][] chains, String protocol)
  {
    this.ssm = ssm;
    this.sequence = sequenceIs;
    this.chains = chains;
    this.pdbentry = pdbentry;
    this.protocol = protocol;
    if (chains == null)
    {
      this.chains = new String[pdbentry.length][];
    }
    /*
     * viewer = JmolViewer.allocateViewer(renderPanel, new SmarterJmolAdapter(),
     * "jalviewJmol", ap.av.applet .getDocumentBase(),
     * ap.av.applet.getCodeBase(), "", this);
     * 
     * jmolpopup = JmolPopup.newJmolPopup(viewer, true, "Jmol", true);
     */
  }

  public JalviewJmolBinding(StructureSelectionManager ssm, JmolViewer viewer2)
  {
    this.ssm = ssm;
    viewer = viewer2;
    viewer.setJmolStatusListener(this);
    viewer.addSelectionListener(this);
  }

  /**
   * construct a title string for the viewer window based on the data jalview
   * knows about
   * 
   * @return
   */
  public String getViewerTitle()
  {
    if (sequence == null || pdbentry == null || sequence.length < 1
            || pdbentry.length < 1 || sequence[0].length < 1)
    {
      return ("Jalview Jmol Window");
    }
    // TODO: give a more informative title when multiple structures are
    // displayed.
    StringBuffer title = new StringBuffer(sequence[0][0].getName() + ":"
            + pdbentry[0].getId());

    if (pdbentry[0].getProperty() != null)
    {
      if (pdbentry[0].getProperty().get("method") != null)
      {
        title.append(" Method: ");
        title.append(pdbentry[0].getProperty().get("method"));
      }
      if (pdbentry[0].getProperty().get("chains") != null)
      {
        title.append(" Chain:");
        title.append(pdbentry[0].getProperty().get("chains"));
      }
    }
    return title.toString();
  }

  /**
   * prepare the view for a given set of models/chains. chainList contains
   * strings of the form 'pdbfilename:Chaincode'
   * 
   * @param chainList
   *          list of chains to make visible
   */
  public void centerViewer(Vector chainList)
  {
    StringBuffer cmd = new StringBuffer();
    String lbl;
    int mlength, p;
    for (int i = 0, iSize = chainList.size(); i < iSize; i++)
    {
      mlength = 0;
      lbl = (String) chainList.elementAt(i);
      do
      {
        p = mlength;
        mlength = lbl.indexOf(":", p);
      } while (p < mlength && mlength < (lbl.length() - 2));
      // TODO: lookup each pdb id and recover proper model number for it.
      cmd.append(":" + lbl.substring(mlength + 1) + " /"
              + (1 + getModelNum((String) chainFile.get(lbl))) + " or ");
    }
    if (cmd.length() > 0)
      cmd.setLength(cmd.length() - 4);
    evalStateCommand("select *;restrict " + cmd + ";cartoon;center " + cmd);
  }

  public void closeViewer()
  {
    viewer.setModeMouse(org.jmol.viewer.JmolConstants.MOUSE_NONE);
    // remove listeners for all structures in viewer
    ssm.removeStructureViewerListener(this, this.getPdbFile());
    // and shut down jmol
    viewer.evalStringQuiet("zap");
    viewer.setJmolStatusListener(null);
    lastCommand = null;
    viewer = null;
    releaseUIResources();
  }

  /**
   * called by JalviewJmolbinding after closeViewer is called - release any
   * resources and references so they can be garbage collected.
   */
  protected abstract void releaseUIResources();

  public void colourByChain()
  {
    colourBySequence = false;
    // TODO: colour by chain should colour each chain distinctly across all
    // visible models
    // TODO: http://issues.jalview.org/browse/JAL-628
    evalStateCommand("select *;color chain");
  }

  public void colourByCharge()
  {
    colourBySequence = false;
    evalStateCommand("select *;color white;select ASP,GLU;color red;"
            + "select LYS,ARG;color blue;select CYS;color yellow");
  }

  /**
   * superpose the structures associated with sequences in the alignment
   * according to their corresponding positions.
   */
  public void superposeStructures(AlignmentI alignment)
  {
    superposeStructures(alignment, -1, null);
  }

  /**
   * superpose the structures associated with sequences in the alignment
   * according to their corresponding positions. ded)
   * 
   * @param refStructure
   *          - select which pdb file to use as reference (default is -1 - the
   *          first structure in the alignment)
   */
  public void superposeStructures(AlignmentI alignment, int refStructure)
  {
    superposeStructures(alignment, refStructure, null);
  }

  /**
   * superpose the structures associated with sequences in the alignment
   * according to their corresponding positions. ded)
   * 
   * @param refStructure
   *          - select which pdb file to use as reference (default is -1 - the
   *          first structure in the alignment)
   * @param hiddenCols
   *          TODO
   */
  public void superposeStructures(AlignmentI alignment, int refStructure,
          ColumnSelection hiddenCols)
  {
    superposeStructures(new AlignmentI[]
    { alignment }, new int[]
    { refStructure }, new ColumnSelection[]
    { hiddenCols });
  }

  public void superposeStructures(AlignmentI[] _alignment,
          int[] _refStructure, ColumnSelection[] _hiddenCols)
  {
    String[] files = getPdbFile();
    StringBuffer selectioncom = new StringBuffer();
    assert (_alignment.length == _refStructure.length && _alignment.length != _hiddenCols.length);
    // union of all aligned positions are collected together.
    for (int a = 0; a < _alignment.length; a++)
    {
      int refStructure = _refStructure[a];
      AlignmentI alignment = _alignment[a];
      ColumnSelection hiddenCols = _hiddenCols[a];
      if (a > 0
              && selectioncom.length() > 0
              && !selectioncom.substring(selectioncom.length() - 1).equals(
                      "|"))
      {
        selectioncom.append("|");
      }
      // process this alignment
      if (refStructure >= files.length)
      {
        System.err.println("Invalid reference structure value "
                + refStructure);
        refStructure = -1;
      }
      if (refStructure < -1)
      {
        refStructure = -1;
      }
      StringBuffer command = new StringBuffer();

      boolean matched[] = new boolean[alignment.getWidth()];
      for (int m = 0; m < matched.length; m++)
      {

        matched[m] = (hiddenCols != null) ? hiddenCols.isVisible(m) : true;
      }

      int commonrpositions[][] = new int[files.length][alignment.getWidth()];
      String isel[] = new String[files.length];
      // reference structure - all others are superposed in it
      String[] targetC = new String[files.length];
      String[] chainNames = new String[files.length];
      for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
      {
        StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);

        if (mapping == null || mapping.length < 1)
          continue;

        int lastPos = -1;
        for (int s = 0; s < sequence[pdbfnum].length; s++)
        {
          for (int sp, m = 0; m < mapping.length; m++)
          {
            if (mapping[m].getSequence() == sequence[pdbfnum][s]
                    && (sp = alignment.findIndex(sequence[pdbfnum][s])) > -1)
            {
              if (refStructure == -1)
              {
                refStructure = pdbfnum;
              }
              SequenceI asp = alignment.getSequenceAt(sp);
              for (int r = 0; r < matched.length; r++)
              {
                if (!matched[r])
                {
                  continue;
                }
                matched[r] = false; // assume this is not a good site
                if (r >= asp.getLength())
                {
                  continue;
                }

                if (jalview.util.Comparison.isGap(asp.getCharAt(r)))
                {
                  // no mapping to gaps in sequence
                  continue;
                }
                int t = asp.findPosition(r); // sequence position
                int apos = mapping[m].getAtomNum(t);
                int pos = mapping[m].getPDBResNum(t);

                if (pos < 1 || pos == lastPos)
                {
                  // can't align unmapped sequence
                  continue;
                }
                matched[r] = true; // this is a good ite
                lastPos = pos;
                // just record this residue position
                commonrpositions[pdbfnum][r] = pos;
              }
              // create model selection suffix
              isel[pdbfnum] = "/" + (pdbfnum + 1) + ".1";
              if (mapping[m].getChain() == null
                      || mapping[m].getChain().trim().length() == 0)
              {
                targetC[pdbfnum] = "";
              }
              else
              {
                targetC[pdbfnum] = ":" + mapping[m].getChain();
              }
              chainNames[pdbfnum] = mapping[m].getPdbId()
                      + targetC[pdbfnum];
              // move on to next pdb file
              s = sequence[pdbfnum].length;
              break;
            }
          }
        }
      }
      String[] selcom = new String[files.length];
      int nmatched = 0;
      // generate select statements to select regions to superimpose structures
      {
        for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
        {
          String chainCd = targetC[pdbfnum];
          int lpos = -1;
          boolean run = false;
          StringBuffer molsel = new StringBuffer();
          molsel.append("{");
          for (int r = 0; r < matched.length; r++)
          {
            if (matched[r])
            {
              if (pdbfnum == 0)
              {
                nmatched++;
              }
              if (lpos != commonrpositions[pdbfnum][r] - 1)
              {
                // discontinuity
                if (lpos != -1)
                {
                  molsel.append(lpos);
                  molsel.append(chainCd);
                  // molsel.append("} {");
                  molsel.append("|");
                }
              }
              else
              {
                // continuous run - and lpos >-1
                if (!run)
                {
                  // at the beginning, so add dash
                  molsel.append(lpos);
                  molsel.append("-");
                }
                run = true;
              }
              lpos = commonrpositions[pdbfnum][r];
              // molsel.append(lpos);
            }
          }
          // add final selection phrase
          if (lpos != -1)
          {
            molsel.append(lpos);
            molsel.append(chainCd);
            molsel.append("}");
          }
          selcom[pdbfnum] = molsel.toString();
          selectioncom.append("((");
          selectioncom.append(selcom[pdbfnum].substring(1,
                  selcom[pdbfnum].length() - 1));
          selectioncom.append(" )& ");
          selectioncom.append(pdbfnum + 1);
          selectioncom.append(".1)");
          if (pdbfnum < files.length - 1)
          {
            selectioncom.append("|");
          }
        }
      }
      // TODO: consider bailing if nmatched less than 4 because superposition
      // not
      // well defined.
      // TODO: refactor superposable position search (above) from jmol selection
      // construction (below)
      for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
      {
        if (pdbfnum == refStructure)
        {
          continue;
        }
        command.append("echo ");
        command.append("\"Superposing (");
        command.append(chainNames[pdbfnum]);
        command.append(") against reference (");
        command.append(chainNames[refStructure]);
        command.append(")\";\ncompare ");
        command.append("{");
        command.append(1 + pdbfnum);
        command.append(".1} {");
        command.append(1 + refStructure);
        command.append(".1} SUBSET {*.CA | *.P} ATOMS ");

        // form the matched pair strings
        String sep = "";
        for (int s = 0; s < 2; s++)
        {
          command.append(selcom[(s == 0 ? pdbfnum : refStructure)]);
        }
        command.append(" ROTATE TRANSLATE;\n");
      }
      System.out.println("Select regions:\n" + selectioncom.toString());
      evalStateCommand("select *; cartoons off; backbone; select ("
              + selectioncom.toString() + "); cartoons; ");
      // selcom.append("; ribbons; ");
      System.out.println("Superimpose command(s):\n" + command.toString());

      evalStateCommand(command.toString());
    }
    if (selectioncom.length() > 0)
    {// finally, mark all regions that were superposed.
      if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
      {
        selectioncom.setLength(selectioncom.length() - 1);
      }
      System.out.println("Select regions:\n" + selectioncom.toString());
      evalStateCommand("select *; cartoons off; backbone; select ("
              + selectioncom.toString() + "); cartoons; ");
      // evalStateCommand("select *; backbone; select "+selcom.toString()+"; cartoons; center "+selcom.toString());
    }
  }

  public void evalStateCommand(String command)
  {
    jmolHistory(false);
    if (lastCommand == null || !lastCommand.equals(command))
    {
      viewer.evalStringQuiet(command + "\n");
    }
    jmolHistory(true);
    lastCommand = command;
  }

  /**
   * colour any structures associated with sequences in the given alignment
   * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
   * if colourBySequence is enabled.
   */
  public void colourBySequence(boolean showFeatures,
          jalview.api.AlignmentViewPanel alignmentv)
  {
    if (!colourBySequence)
      return;
    if (ssm == null)
    {
      return;
    }
    String[] files = getPdbFile();

    SequenceRenderer sr = getSequenceRenderer(alignmentv);

    FeatureRenderer fr = null;
    if (showFeatures)
    {
      fr = getFeatureRenderer(alignmentv);
    }
    AlignmentI alignment = alignmentv.getAlignment();

    for (jalview.structure.StructureMappingcommandSet cpdbbyseq: JmolCommands.getColourBySequenceCommand(ssm, files, sequence, sr, fr, alignment))
      for (String cbyseq : cpdbbyseq.commands) {
      evalStateCommand(cbyseq);
    }
  }
  
  public boolean isColourBySequence()
  {
    return colourBySequence;
  }

  public void setColourBySequence(boolean colourBySequence)
  {
    this.colourBySequence = colourBySequence;
  }

  public void createImage(String file, String type, int quality)
  {
    System.out.println("JMOL CREATE IMAGE");
  }

  public String createImage(String fileName, String type,
          Object textOrBytes, int quality)
  {
    System.out.println("JMOL CREATE IMAGE");
    return null;
  }

  public String eval(String strEval)
  {
    // System.out.println(strEval);
    // "# 'eval' is implemented only for the applet.";
    return null;
  }

  // End StructureListener
  // //////////////////////////

  public float[][] functionXY(String functionName, int x, int y)
  {
    return null;
  }

  public float[][][] functionXYZ(String functionName, int nx, int ny, int nz)
  {
    // TODO Auto-generated method stub
    return null;
  }

  public Color getColour(int atomIndex, int pdbResNum, String chain,
          String pdbfile)
  {
    if (getModelNum(pdbfile) < 0)
      return null;
    // TODO: verify atomIndex is selecting correct model.
    return new Color(viewer.getAtomArgb(atomIndex));
  }

  /**
   * returns the current featureRenderer that should be used to colour the
   * structures
   * 
   * @param alignment
   * 
   * @return
   */
  public abstract FeatureRenderer getFeatureRenderer(
          AlignmentViewPanel alignment);

  /**
   * instruct the Jalview binding to update the pdbentries vector if necessary
   * prior to matching the jmol view's contents to the list of structure files
   * Jalview knows about.
   */
  public abstract void refreshPdbEntries();

  private int getModelNum(String modelFileName)
  {
    String[] mfn = getPdbFile();
    if (mfn == null)
    {
      return -1;
    }
    for (int i = 0; i < mfn.length; i++)
    {
      if (mfn[i].equalsIgnoreCase(modelFileName))
        return i;
    }
    return -1;
  }

  /**
   * map between index of model filename returned from getPdbFile and the first
   * index of models from this file in the viewer. Note - this is not trimmed -
   * use getPdbFile to get number of unique models.
   */
  private int _modelFileNameMap[];

  // ////////////////////////////////
  // /StructureListener
  public synchronized String[] getPdbFile()
  {
    if (viewer == null)
    {
      return new String[0];
    }
    if (modelFileNames == null)
    {

      String mset[] = new String[viewer.getModelCount()];
      _modelFileNameMap = new int[mset.length];
      int j = 1;
      mset[0] = viewer.getModelFileName(0);
      for (int i = 1; i < mset.length; i++)
      {
        mset[j] = viewer.getModelFileName(i);
        _modelFileNameMap[j] = i; // record the model index for the filename
        // skip any additional models in the same file (NMR structures)
        if ((mset[j] == null ? mset[j] != mset[j - 1]
                : (mset[j - 1] == null || !mset[j].equals(mset[j - 1]))))
        {
          j++;
        }
      }
      modelFileNames = new String[j];
      System.arraycopy(mset, 0, modelFileNames, 0, j);
    }
    return modelFileNames;
  }

  /**
   * map from string to applet
   */
  public Map getRegistryInfo()
  {
    // TODO Auto-generated method stub
    return null;
  }

  /**
   * returns the current sequenceRenderer that should be used to colour the
   * structures
   * 
   * @param alignment
   * 
   * @return
   */
  public abstract SequenceRenderer getSequenceRenderer(
          AlignmentViewPanel alignment);

  // ///////////////////////////////
  // JmolStatusListener

  public void handlePopupMenu(int x, int y)
  {
    jmolpopup.show(x, y);
  }

  // jmol/ssm only
  public void highlightAtom(int atomIndex, int pdbResNum, String chain,
          String pdbfile)
  {
    if (modelFileNames == null)
    {
      return;
    }

    // look up file model number for this pdbfile
    int mdlNum = 0;
    String fn;
    // may need to adjust for URLencoding here - we don't worry about that yet.
    while (mdlNum < modelFileNames.length
            && !pdbfile.equals(modelFileNames[mdlNum]))
    {
      // System.out.println("nomatch:"+pdbfile+"\nmodelfn:"+fn);
      mdlNum++;
    }
    if (mdlNum == modelFileNames.length)
    {
      return;
    }

    jmolHistory(false);
    // if (!pdbfile.equals(pdbentry.getFile()))
    // return;
    if (resetLastRes.length() > 0)
    {
      viewer.evalStringQuiet(resetLastRes.toString());
    }

    eval.setLength(0);
    eval.append("select " + pdbResNum); // +modelNum

    resetLastRes.setLength(0);
    resetLastRes.append("select " + pdbResNum); // +modelNum

    eval.append(":");
    resetLastRes.append(":");
    if (!chain.equals(" "))
    {
      eval.append(chain);
      resetLastRes.append(chain);
    }
    {
      eval.append(" /" + (mdlNum + 1));
      resetLastRes.append("/" + (mdlNum + 1));
    }
    eval.append(";wireframe 100;" + eval.toString() + " and not hetero;");

    resetLastRes.append(";wireframe 0;" + resetLastRes.toString()
            + " and not hetero; spacefill 0;");

    eval.append("spacefill 200;select none");

    viewer.evalStringQuiet(eval.toString());
    jmolHistory(true);

  }

  boolean debug = true;

  private void jmolHistory(boolean enable)
  {
    viewer.evalStringQuiet("History " + ((debug || enable) ? "on" : "off"));
  }

  public void loadInline(String string)
  {
    loadedInline = true;
    // TODO: re JAL-623
    // viewer.loadInline(strModel, isAppend);
    // could do this:
    // construct fake fullPathName and fileName so we can identify the file
    // later.
    // Then, construct pass a reader for the string to Jmol.
    // ((org.jmol.Viewer.Viewer) viewer).loadModelFromFile(fullPathName,
    // fileName, null, reader, false, null, null, 0);
    viewer.openStringInline(string);
  }

  public void mouseOverStructure(int atomIndex, String strInfo)
  {
    int pdbResNum;
    int alocsep = strInfo.indexOf("^");
    int mdlSep = strInfo.indexOf("/");
    int chainSeparator = strInfo.indexOf(":"), chainSeparator1 = -1;

    if (chainSeparator == -1)
    {
      chainSeparator = strInfo.indexOf(".");
      if (mdlSep > -1 && mdlSep < chainSeparator)
      {
        chainSeparator1 = chainSeparator;
        chainSeparator = mdlSep;
      }
    }
    // handle insertion codes
    if (alocsep != -1)
    {
      pdbResNum = Integer.parseInt(strInfo.substring(
              strInfo.indexOf("]") + 1, alocsep));

    }
    else
    {
      pdbResNum = Integer.parseInt(strInfo.substring(
              strInfo.indexOf("]") + 1, chainSeparator));
    }
    String chainId;

    if (strInfo.indexOf(":") > -1)
      chainId = strInfo.substring(strInfo.indexOf(":") + 1,
              strInfo.indexOf("."));
    else
    {
      chainId = " ";
    }

    String pdbfilename = modelFileNames[frameNo]; // default is first or current
    // model
    if (mdlSep > -1)
    {
      if (chainSeparator1 == -1)
      {
        chainSeparator1 = strInfo.indexOf(".", mdlSep);
      }
      String mdlId = (chainSeparator1 > -1) ? strInfo.substring(mdlSep + 1,
              chainSeparator1) : strInfo.substring(mdlSep + 1);
      try
      {
        // recover PDB filename for the model hovered over.
        pdbfilename = viewer
                .getModelFileName(new Integer(mdlId).intValue() - 1);
      } catch (Exception e)
      {
      }
      ;
    }
    if (lastMessage == null || !lastMessage.equals(strInfo))
      ssm.mouseOverStructure(pdbResNum, chainId, pdbfilename);

    lastMessage = strInfo;
  }

  public void notifyAtomHovered(int atomIndex, String strInfo, String data)
  {
    if (data != null)
    {
      System.err.println("Ignoring additional hover info: " + data
              + " (other info: '" + strInfo + "' pos " + atomIndex + ")");
    }
    mouseOverStructure(atomIndex, strInfo);
  }

  /*
   * { if (history != null && strStatus != null &&
   * !strStatus.equals("Script completed")) { history.append("\n" + strStatus);
   * } }
   */

  public void notifyAtomPicked(int atomIndex, String strInfo, String strData)
  {
    /**
     * this implements the toggle label behaviour copied from the original
     * structure viewer, MCView
     */
    if (strData != null)
    {
      System.err.println("Ignoring additional pick data string " + strData);
    }
    int chainSeparator = strInfo.indexOf(":");
    int p = 0;
    if (chainSeparator == -1)
      chainSeparator = strInfo.indexOf(".");

    String picked = strInfo.substring(strInfo.indexOf("]") + 1,
            chainSeparator);
    String mdlString = "";
    if ((p = strInfo.indexOf(":")) > -1)
      picked += strInfo.substring(p + 1, strInfo.indexOf("."));

    if ((p = strInfo.indexOf("/")) > -1)
    {
      mdlString += strInfo.substring(p, strInfo.indexOf(" #"));
    }
    picked = "((" + picked + ".CA" + mdlString + ")|(" + picked + ".P"
            + mdlString + "))";
    jmolHistory(false);

    if (!atomsPicked.contains(picked))
    {
      viewer.evalStringQuiet("select " + picked + ";label %n %r:%c");
      atomsPicked.addElement(picked);
    }
    else
    {
      viewer.evalString("select " + picked + ";label off");
      atomsPicked.removeElement(picked);
    }
    jmolHistory(true);
    // TODO: in application this happens
    //
    // if (scriptWindow != null)
    // {
    // scriptWindow.sendConsoleMessage(strInfo);
    // scriptWindow.sendConsoleMessage("\n");
    // }

  }

  @Override
  public void notifyCallback(EnumCallback type, Object[] data)
  {
    try
    {
      switch (type)
      {
      case LOADSTRUCT:
        notifyFileLoaded((String) data[1], (String) data[2],
                (String) data[3], (String) data[4],
                ((Integer) data[5]).intValue());

        break;
      case PICK:
        notifyAtomPicked(((Integer) data[2]).intValue(), (String) data[1],
                (String) data[0]);
        // also highlight in alignment
      case HOVER:
        notifyAtomHovered(((Integer) data[2]).intValue(), (String) data[1],
                (String) data[0]);
        break;
      case SCRIPT:
        notifyScriptTermination((String) data[2],
                ((Integer) data[3]).intValue());
        break;
      case ECHO:
        sendConsoleEcho((String) data[1]);
        break;
      case MESSAGE:
        sendConsoleMessage((data == null) ? ((String) null)
                : (String) data[1]);
        break;
      case ERROR:
        // System.err.println("Ignoring error callback.");
        break;
      case SYNC:
      case RESIZE:
        refreshGUI();
        break;
      case MEASURE:

      case CLICK:
      default:
        System.err.println("Unhandled callback " + type + " "
                + data[1].toString());
        break;
      }
    } catch (Exception e)
    {
      System.err.println("Squashed Jmol callback handler error:");
      e.printStackTrace();
    }
  }

  @Override
  public boolean notifyEnabled(EnumCallback callbackPick)
  {
    switch (callbackPick)
    {
    case ECHO:
    case LOADSTRUCT:
    case MEASURE:
    case MESSAGE:
    case PICK:
    case SCRIPT:
    case HOVER:
    case ERROR:
      return true;
    case RESIZE:
    case SYNC:
    case CLICK:
    case ANIMFRAME:
    case MINIMIZATION:
    }
    return false;
  }

  // incremented every time a load notification is successfully handled -
  // lightweight mechanism for other threads to detect when they can start
  // referrring to new structures.
  private long loadNotifiesHandled = 0;

  public long getLoadNotifiesHandled()
  {
    return loadNotifiesHandled;
  }

  public void notifyFileLoaded(String fullPathName, String fileName2,
          String modelName, String errorMsg, int modelParts)
  {
    if (errorMsg != null)
    {
      fileLoadingError = errorMsg;
      refreshGUI();
      return;
    }
    // TODO: deal sensibly with models loaded inLine:
    // modelName will be null, as will fullPathName.

    // the rest of this routine ignores the arguments, and simply interrogates
    // the Jmol view to find out what structures it contains, and adds them to
    // the structure selection manager.
    fileLoadingError = null;
    String[] oldmodels = modelFileNames;
    modelFileNames = null;
    chainNames = new Vector();
    chainFile = new Hashtable();
    boolean notifyLoaded = false;
    String[] modelfilenames = getPdbFile();
    // first check if we've lost any structures
    if (oldmodels != null && oldmodels.length > 0)
    {
      int oldm = 0;
      for (int i = 0; i < oldmodels.length; i++)
      {
        for (int n = 0; n < modelfilenames.length; n++)
        {
          if (modelfilenames[n] == oldmodels[i])
          {
            oldmodels[i] = null;
            break;
          }
        }
        if (oldmodels[i] != null)
        {
          oldm++;
        }
      }
      if (oldm > 0)
      {
        String[] oldmfn = new String[oldm];
        oldm = 0;
        for (int i = 0; i < oldmodels.length; i++)
        {
          if (oldmodels[i] != null)
          {
            oldmfn[oldm++] = oldmodels[i];
          }
        }
        // deregister the Jmol instance for these structures - we'll add
        // ourselves again at the end for the current structure set.
        ssm.removeStructureViewerListener(this, oldmfn);
      }
    }
    refreshPdbEntries();
    for (int modelnum = 0; modelnum < modelfilenames.length; modelnum++)
    {
      String fileName = modelfilenames[modelnum];
      boolean foundEntry = false;
      MCview.PDBfile pdb = null;
      String pdbfile = null, pdbfhash = null;
      // model was probably loaded inline - so check the pdb file hashcode
      if (loadedInline)
      {
        // calculate essential attributes for the pdb data imported inline.
        // prolly need to resolve modelnumber properly - for now just use our
        // 'best guess'
        pdbfile = viewer.getData("" + (1 + _modelFileNameMap[modelnum])
                + ".0", "PDB");
        pdbfhash = "" + pdbfile.hashCode();
      }
      if (pdbentry != null)
      {
        // search pdbentries and sequences to find correct pdbentry for this
        // model
        for (int pe = 0; pe < pdbentry.length; pe++)
        {
          boolean matches = false;
          if (fileName == null)
          {
            if (false)
            // see JAL-623 - need method of matching pasted data up
            {
              pdb = ssm.setMapping(sequence[pe], chains[pe], pdbfile,
                      AppletFormatAdapter.PASTE);
              pdbentry[modelnum].setFile("INLINE" + pdb.id);
              matches = true;
              foundEntry = true;
            }
          }
          else
          {
            if (matches = pdbentry[pe].getFile().equals(fileName))
            {
              foundEntry = true;
              // TODO: Jmol can in principle retrieve from CLASSLOADER but
              // this
              // needs
              // to be tested. See mantis bug
              // https://mantis.lifesci.dundee.ac.uk/view.php?id=36605
              String protocol = AppletFormatAdapter.URL;
              try
              {
                File fl = new java.io.File(pdbentry[pe].getFile());
                if (fl.exists())
                {
                  protocol = AppletFormatAdapter.FILE;
                }
              } catch (Exception e)
              {
              } catch (Error e)
              {
              }
              ;
              pdb = ssm.setMapping(sequence[pe], chains[pe],
                      pdbentry[pe].getFile(), protocol);

            }
          }
          if (matches)
          {
            // add an entry for every chain in the model
            for (int i = 0; i < pdb.chains.size(); i++)
            {
              String chid = new String(pdb.id + ":"
                      + ((MCview.PDBChain) pdb.chains.elementAt(i)).id);
              chainFile.put(chid, pdbentry[pe].getFile());
              chainNames.addElement(chid);
            }
            notifyLoaded = true;
          }
        }
      }
      if (!foundEntry && associateNewStructs)
      {
        // this is a foreign pdb file that jalview doesn't know about - add
        // it to the dataset and try to find a home - either on a matching
        // sequence or as a new sequence.
        String pdbcontent = viewer.getData("/" + (modelnum + 1) + ".1",
                "PDB");
        // parse pdb file into a chain, etc.
        // locate best match for pdb in associated views and add mapping to
        // ssm
        // if properly registered then
        notifyLoaded = true;

      }
    }
    // FILE LOADED OK
    // so finally, update the jmol bits and pieces
    if (jmolpopup != null)
    {
      // potential for deadlock here:
      // jmolpopup.updateComputedMenus();
    }
    if (!isLoadingFromArchive())
    {
      viewer.evalStringQuiet("model 0; select backbone;restrict;cartoon;wireframe off;spacefill off");
    }
    // register ourselves as a listener and notify the gui that it needs to
    // update itself.
    ssm.addStructureViewerListener(this);
    if (notifyLoaded)
    {
      FeatureRenderer fr = getFeatureRenderer(null);
      if (fr != null)
      {
        fr.featuresAdded();
      }
      refreshGUI();
      loadNotifiesHandled++;
    }
    setLoadingFromArchive(false);
  }

  public void notifyNewPickingModeMeasurement(int iatom, String strMeasure)
  {
    notifyAtomPicked(iatom, strMeasure, null);
  }

  public abstract void notifyScriptTermination(String strStatus,
          int msWalltime);

  /**
   * display a message echoed from the jmol viewer
   * 
   * @param strEcho
   */
  public abstract void sendConsoleEcho(String strEcho); /*
                                                         * { showConsole(true);
                                                         * 
                                                         * history.append("\n" +
                                                         * strEcho); }
                                                         */

  // /End JmolStatusListener
  // /////////////////////////////

  /**
   * @param strStatus
   *          status message - usually the response received after a script
   *          executed
   */
  public abstract void sendConsoleMessage(String strStatus);

  public void setCallbackFunction(String callbackType,
          String callbackFunction)
  {
    System.err.println("Ignoring set-callback request to associate "
            + callbackType + " with function " + callbackFunction);

  }

  public void setJalviewColourScheme(ColourSchemeI cs)
  {
    colourBySequence = false;

    if (cs == null)
      return;

    String res;
    int index;
    Color col;
    jmolHistory(false);
    // TODO: Switch between nucleotide or aa selection expressions
    Enumeration en = ResidueProperties.aa3Hash.keys();
    StringBuffer command = new StringBuffer("select *;color white;");
    while (en.hasMoreElements())
    {
      res = en.nextElement().toString();
      index = ((Integer) ResidueProperties.aa3Hash.get(res)).intValue();
      if (index > 20)
        continue;

      col = cs.findColour(ResidueProperties.aa[index].charAt(0));

      command.append("select " + res + ";color[" + col.getRed() + ","
              + col.getGreen() + "," + col.getBlue() + "];");
    }

    evalStateCommand(command.toString());
    jmolHistory(true);
  }

  public void showHelp()
  {
    showUrl("http://jmol.sourceforge.net/docs/JmolUserGuide/", "jmolHelp");
  }

  /**
   * open the URL somehow
   * 
   * @param target
   */
  public abstract void showUrl(String url, String target);

  /**
   * called when the binding thinks the UI needs to be refreshed after a Jmol
   * state change. this could be because structures were loaded, or because an
   * error has occured.
   */
  public abstract void refreshGUI();

  /**
   * called to show or hide the associated console window container.
   * 
   * @param show
   */
  public abstract void showConsole(boolean show);

  /**
   * @param renderPanel
   * @param jmolfileio
   *          - when true will initialise jmol's file IO system (should be false
   *          in applet context)
   * @param htmlName
   * @param documentBase
   * @param codeBase
   * @param commandOptions
   */
  public void allocateViewer(Container renderPanel, boolean jmolfileio,
          String htmlName, URL documentBase, URL codeBase,
          String commandOptions)
  {
    allocateViewer(renderPanel, jmolfileio, htmlName, documentBase,
            codeBase, commandOptions, null, null);
  }

  /**
   * 
   * @param renderPanel
   * @param jmolfileio
   *          - when true will initialise jmol's file IO system (should be false
   *          in applet context)
   * @param htmlName
   * @param documentBase
   * @param codeBase
   * @param commandOptions
   * @param consolePanel
   *          - panel to contain Jmol console
   * @param buttonsToShow
   *          - buttons to show on the console, in ordr
   */
  public void allocateViewer(Container renderPanel, boolean jmolfileio,
          String htmlName, URL documentBase, URL codeBase,
          String commandOptions, final Container consolePanel,
          String buttonsToShow)
  {
    if (commandOptions==null) {
      commandOptions="";
    }
    viewer = JmolViewer.allocateViewer(renderPanel,
            (jmolfileio ? new SmarterJmolAdapter() : null), htmlName
                    + ((Object) this).toString(), documentBase, codeBase,
            commandOptions, this);

    console = createJmolConsole(viewer, consolePanel, buttonsToShow);
    if (consolePanel != null)
    {
      consolePanel.addComponentListener(this);

    }

  }

  protected abstract JmolAppConsoleInterface createJmolConsole(
          JmolViewer viewer2, Container consolePanel, String buttonsToShow);

  protected org.jmol.api.JmolAppConsoleInterface console = null;

  public void componentResized(ComponentEvent e)
  {

  }

  public void componentMoved(ComponentEvent e)
  {

  }

  public void componentShown(ComponentEvent e)
  {
    showConsole(true);
  }

  public void componentHidden(ComponentEvent e)
  {
    showConsole(false);
  }

  public void setLoadingFromArchive(boolean loadingFromArchive)
  {
    this.loadingFromArchive = loadingFromArchive;
  }

  public boolean isLoadingFromArchive()
  {
    return loadingFromArchive;
  }

  public void setBackgroundColour(java.awt.Color col)
  {
    jmolHistory(false);
    viewer.evalStringQuiet("background [" + col.getRed() + ","
            + col.getGreen() + "," + col.getBlue() + "];");
    jmolHistory(true);
  }

  /**
   * add structures and any known sequence associations
   * 
   * @returns the pdb entries added to the current set.
   */
  public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
          SequenceI[][] seq, String[][] chns)
  {
    int pe = -1;
    Vector v = new Vector();
    Vector rtn = new Vector();
    for (int i = 0; i < pdbentry.length; i++)
    {
      v.addElement(pdbentry[i]);
    }
    for (int i = 0; i < pdbe.length; i++)
    {
      int r = v.indexOf(pdbe[i]);
      if (r == -1 || r >= pdbentry.length)
      {
        rtn.addElement(new int[]
        { v.size(), i });
        v.addElement(pdbe[i]);
      }
      else
      {
        // just make sure the sequence/chain entries are all up to date
        addSequenceAndChain(r, seq[i], chns[i]);
      }
    }
    pdbe = new PDBEntry[v.size()];
    v.copyInto(pdbe);
    pdbentry = pdbe;
    if (rtn.size() > 0)
    {
      // expand the tied seuqence[] and string[] arrays
      SequenceI[][] sqs = new SequenceI[pdbentry.length][];
      String[][] sch = new String[pdbentry.length][];
      System.arraycopy(sequence, 0, sqs, 0, sequence.length);
      System.arraycopy(chains, 0, sch, 0, this.chains.length);
      sequence = sqs;
      chains = sch;
      pdbe = new PDBEntry[rtn.size()];
      for (int r = 0; r < pdbe.length; r++)
      {
        int[] stri = ((int[]) rtn.elementAt(r));
        // record the pdb file as a new addition
        pdbe[r] = pdbentry[stri[0]];
        // and add the new sequence/chain entries
        addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
      }
    }
    else
    {
      pdbe = null;
    }
    return pdbe;
  }

  public void addSequence(int pe, SequenceI[] seq)
  {
    // add sequences to the pe'th pdbentry's seuqence set.
    addSequenceAndChain(pe, seq, null);
  }

  private void addSequenceAndChain(int pe, SequenceI[] seq, String[] tchain)
  {
    if (pe < 0 || pe >= pdbentry.length)
    {
      throw new Error(
              "Implementation error - no corresponding pdbentry (for index "
                      + pe + ") to add sequences mappings to");
    }
    final String nullChain = "TheNullChain";
    Vector s = new Vector();
    Vector c = new Vector();
    if (chains == null)
    {
      chains = new String[pdbentry.length][];
    }
    if (sequence[pe] != null)
    {
      for (int i = 0; i < sequence[pe].length; i++)
      {
        s.addElement(sequence[pe][i]);
        if (chains[pe] != null)
        {
          if (i < chains[pe].length)
          {
            c.addElement(chains[pe][i]);
          }
          else
          {
            c.addElement(nullChain);
          }
        }
        else
        {
          if (tchain != null && tchain.length > 0)
          {
            c.addElement(nullChain);
          }
        }
      }
    }
    for (int i = 0; i < seq.length; i++)
    {
      if (!s.contains(seq[i]))
      {
        s.addElement(seq[i]);
        if (tchain != null && i < tchain.length)
        {
          c.addElement(tchain[i] == null ? nullChain : tchain[i]);
        }
      }
    }
    SequenceI[] tmp = new SequenceI[s.size()];
    s.copyInto(tmp);
    sequence[pe] = tmp;
    if (c.size() > 0)
    {
      String[] tch = new String[c.size()];
      c.copyInto(tch);
      for (int i = 0; i < tch.length; i++)
      {
        if (tch[i] == nullChain)
        {
          tch[i] = null;
        }
      }
      chains[pe] = tch;
    }
    else
    {
      chains[pe] = null;
    }
  }
  /**
   * 
   * @param pdbfile
   * @return text report of alignment between pdbfile and any associated alignment sequences
   */
  public String printMapping(String pdbfile)
  {
    return ssm.printMapping(pdbfile);
  }
  @Override
  public void resizeInnerPanel(String data)
  {
    // Jalview doesn't honour resize panel requests
    
  }
}