All files / src GLModel.ts

0.99% Statements 15/1503
0% Branches 0/614
0% Functions 0/73
1.07% Lines 15/1401

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052                                                      18x       18x       18x                                                                                                                       18x                                                                     18x                                                                 18x                         18x   18x               18x                   18x                 18x                   18x                       18x                   18x                 18x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
// A model is a collection of related atoms.  Bonds are only allowed between
//atoms in the same model.  An atom is uniquely specified by its model id and
//its serial number.
//A glmodel knows how to apply the styles on each atom to create a gl object
import { Geometry, CC, Material, StickImposterMaterial } from "./WebGL";
import { Sphere, Cylinder } from "./WebGL/shapes";
import { Vector3, Matrix4, conversionMatrix3, Matrix3 } from "./WebGL/math";
import { Color } from "./WebGL";
import { InstancedMaterial, SphereImposterMaterial, MeshLambertMaterial, Object3D, Mesh, LineBasicMaterial, Line, LineStyle } from "./WebGL";
import { GLDraw } from "./GLDraw"
import { drawCartoon } from "./glcartoon";
import { getColorFromStyle, elementColors } from "./colors";
import { deepCopy, extend, getExtent, getAtomProperty, makeFunction, getPropertyRange, specStringToObject, getbin } from "./utilities";
import { Gradient } from "./Gradient";
import { Parsers } from "./parsers";
 
declare var pako: any;
declare var netcdfjs: any;
declare var $: any;
 
/**
 * GLModel represents a group of related atoms
 * @class
 */
export class GLModel {
 
    // class variables go here
    static defaultAtomStyle: any = {
        line: {}
    };
 
    static defaultlineWidth = 1.0;
 
    // Reference: A. Bondi, J. Phys. Chem., 1964, 68, 441.
    // https://en.wikipedia.org/wiki/Van_der_Waals_radius
    static vdwRadii = {
        "H": 1.2,
        "He": 1.4,
        "Li": 1.82,
        "Be": 1.53,
        "B": 1.92,
        "C": 1.7,
        "N": 1.55,
        "O": 1.52,
        "F": 1.47,
        "Ne": 1.54,
        "Na": 2.27,
        "Mg": 1.73,
        "Al": 1.84,
        "Si": 2.1,
        "P": 1.8,
        "S": 1.8,
        "Cl": 1.75,
        "Ar": 1.88,
        "K": 2.75,
        "Ca": 2.31,
        "Ni": 1.63,
        "Cu": 1.4,
        "Zn": 1.39,
        "Ga": 1.87,
        "Ge": 2.11,
        "As": 1.85,
        "Se": 1.9,
        "Br": 1.85,
        "Kr": 2.02,
        "Rb": 3.03,
        "Sr": 2.49,
        "Pd": 1.63,
        "Ag": 1.72,
        "Cd": 1.58,
        "In": 1.93,
        "Sn": 2.17,
        "Sb": 2.06,
        "Te": 2.06,
        "I": 1.98,
        "Xe": 2.16,
        "Cs": 3.43,
        "Ba": 2.68,
        "Pt": 1.75,
        "Au": 1.66,
        "Hg": 1.55,
        "Tl": 1.96,
        "Pb": 2.02,
        "Bi": 2.07,
        "Po": 1.97,
        "At": 2.02,
        "Rn": 2.20,
        "Fr": 3.48,
        "Ra": 2.83,
        "U": 1.86
    };
    /*
        The dictionaries are for dropdown menus and validation of the viewer
    */
 
    static validElements = [
        "H",
        "Li",
        "LI",
        "Na",
        "NA",
        "K",
        "C",
        "N",
        "O",
        "F",
        "P",
        "S",
        "CL",
        "Cl",
        "BR",
        "Br",
        "SE",
        "Se",
        "ZN",
        "Zn",
        "CU",
        "Cu",
        "NI",
        "Ni"
    ];
 
    // TODO: all these specifications need to get converted to types
 
    // prop : It is used to add the option for property in context menu in the 3dmol ui
    // the code for prop can be found under /ui/ui.js -> UI -> ContextMenu -> setProperties -> submit.ui.on 
    // gui : It is used to generate forms for different features in the 3dmol ui
    // the code for gui can be found under /ui/form.js -> Form (Form defination)
    // floatType : separates integer from float since these are used in 
    // input validation of the 3dmol ui
    static validAtomSpecs = {
        "resn": { type: "string", valid: true, prop: true, gui: true }, // Parent residue name
        "x": { type: "number", floatType: true, valid: false, step: 0.1, prop: true }, // Atom's x coordinate
        "y": { type: "number", floatType: true, valid: false, step: 0.1, prop: true }, // Atom's y coordinate
        "z": { type: "number", floatType: true, valid: false, step: 0.1, prop: true }, // Atom's z coordinate
        "color": { type: "color", gui: false }, // Atom's color, as hex code
        "surfaceColor": { type: "color", gui: false }, // Hex code for color to be used for surface patch over this atom
        "elem": { type: "element", gui: true, prop: true }, // Element abbreviation (e.g. 'H', 'Ca', etc)
        "hetflag": { type: "boolean", valid: false, gui: true }, // Set to true if atom is a heteroatom
        "chain": { type: "string", gui: true, prop: true }, // Chain this atom belongs to, if specified in input file (e.g 'A' for chain A)
        "resi": { type: "array_range", gui: true }, // Residue number 
        "icode": { type: "number", valid: false, step: 0.1 },
        "rescode": { type: "number", valid: false, step: 0.1, prop: true },
        "serial": { type: "number", valid: false, step: 0.1 }, // Atom's serial id numbermodels
        "atom": { type: "string", valid: false, gui: true, prop: true }, // Atom name; may be more specific than 'elem' (e.g 'CA' for alpha carbon)
        "bonds": { type: "array", valid: false }, // Array of atom ids this atom is bonded to
        "ss": { type: "string", valid: false }, // Secondary structure identifier (for cartoon render; e.g. 'h' for helix)
        "singleBonds": { type: "boolean", valid: false }, // true if this atom forms only single bonds or no bonds at all
        "bondOrder": { type: "array", valid: false }, // Array of this atom's bond orders, corresponding to bonds identfied by 'bonds'
        "properties": { type: "properties", valid: false }, // Optional mapping of additional properties
        "b": { type: "number", floatType: true, valid: false, step: 0.1, prop: true }, // Atom b factor data
        "pdbline": { type: "string", valid: false }, // If applicable, this atom's record entry from the input PDB file (used to output new PDB from models)
        "clickable": { type: "boolean", valid: false, gui: false }, // Set this flag to true to enable click selection handling for this atom
        "contextMenuEnabled": { type: "boolean", valid: false, gui: false }, // Set this flag to true to enable click selection handling for this atom
        "callback": { type: "function", valid: false }, // Callback click handler function to be executed on this atom and its parent viewer
        "invert": { type: "boolean", valid: false }, // for selection, inverts the meaning of the selection
        //unsure about this
        "reflectivity": { type: "number", floatType: true, gui: false, step: 0.1 }, //for describing the reflectivity of a model
        "altLoc": { type: "invalid", valid: false }, //alternative location, e.g. in PDB
        "sym": { type: 'number', gui: false }, //which symmetry
    };
 
    //type is irrelivent here becuase htey are are invalid
    static validExtras = {  // valid atom specs are ok too
        "model": { type: "string", valid: false }, // a single model or list of models from which atoms should be selected
        "bonds": { type: "number", valid: false, gui: true }, // overloaded to select number of bonds, e.g. {bonds: 0} will select all nonbonded atoms
        "predicate": { type: "string", valid: false }, // user supplied function that gets passed an {AtomSpec} and should return true if the atom should be selected
        "invert": { type: "boolean", valid: false, gui: true }, // if set, inverts the meaning of the selection
        "byres": { type: "boolean", valid: false, gui: true }, // if set, expands the selection to include all atoms of any residue that has any atom selected
        "expand": { type: "number", valid: false, gui: false }, // expands the selection to include all atoms within a given distance from the selection
        "within": { type: "string", valid: false }, // intersects the selection with the set of atoms within a given distance from another selection
        "and": { type: "string", valid: false }, // and boolean logic
        "or": { type: "string", valid: false }, // or boolean logic
        "not": { type: "string", valid: false }, // not boolean logic
    };
 
    static validAtomSelectionSpecs = extend(GLModel.validAtomSpecs, GLModel.validExtras);
 
    static validLineSpec = {
        "hidden": { type: "boolean", gui: true },
        "linewidth": { type: "number", floatType: true, gui: true, step: 0.1, default: GLModel.defaultlineWidth },
        "colorscheme": { type: "colorscheme", gui: true },
        "color": { type: "color", gui: true },
        "opacity": { type: "number", floatType: true, gui: true, step: 0.1, default: 1, min: 0, max: 1 },
    };
 
    static validCrossSpec = {
        "hidden": { type: "boolean", gui: true },
        "linewidth": { type: "number", floatType: true, gui: false, step: 0.1, default: GLModel.defaultlineWidth, min: 0 },//deprecated
        "colorscheme": { type: "colorscheme", gui: true },
        "color": { type: "color", gui: true },
        "radius": { type: "number", floatType: true, gui: true, step: 0.1, default: 1, min: 0.1 },
        "scale": { type: "number", floatType: true, gui: true, step: 0.1, default: 1, min: 0 },
        "opacity": { type: "number", floatType: true, gui: true, step: 0.1, default: 1, min: 0, max: 1 },
    };
 
    static validStickSpec = {
        "hidden": { type: "boolean", gui: true },
        "colorscheme": { type: "colorscheme", gui: true },
        "color": { type: "color", gui: true },
        "radius": { type: "number", floatType: true, gui: true, step: 0.1, default: 0.25, min: 0.1 },
        "singleBonds": { type: "boolean", gui: true },
        "opacity": { type: "number", floatType: true, gui: true, step: 0.1, default: 1, min: 0, max: 1 },
    };
 
    static validSphereSpec = {
        "hidden": { type: "boolean", gui: false }, // needed in the new gui it has separate function to hide the spheres
        "singleBonds": { type: "boolean", gui: true },
        "colorscheme": { type: "colorscheme", gui: true },
        "color": { type: "color", gui: true },
        "radius": { type: "number", floatType: true, gui: true, step: 0.1, default: 1.5, min: 0 },
        "scale": { type: "number", floatType: true, gui: true, step: 0.1, default: 1.0, min: 0.1 },
        "opacity": { type: "number", floatType: true, gui: true, step: 0.1, default: 1, min: 0, max: 1 },
    };
 
    static validCartoonSpec = {
        "style": { validItems: ["trace", "oval", "rectangle", "parabola", "edged"], gui: true },
        "color": { type: "color", gui: true, spectrum: true },
        "arrows": { type: "boolean", gui: true },
        "ribbon": { type: "boolean", gui: true },
        "hidden": { type: "boolean", gui: true },
        "tubes": { type: "boolean", gui: true },
        "thickness": { type: "number", floatType: true, gui: true, step: 0.1, default: 1, min: 0 },
        "width": { type: "number", floatType: true, gui: true, step: 0.1, default: 1, min: 0 },
        "opacity": { type: "number", floatType: true, gui: true, step: 0.1, default: 1, min: 0, max: 1 },
    };
 
    static validAtomStyleSpecs = {
        "line": { validItems: GLModel.validLineSpec, type: "form", gui: true }, // draw bonds as lines
        "cross": { validItems: GLModel.validCrossSpec, type: "form", gui: true }, // draw atoms as crossed lines (aka stars)
        "stick": { validItems: GLModel.validStickSpec, type: "form", gui: true }, // draw bonds as capped cylinders
        "sphere": { validItems: GLModel.validSphereSpec, type: "form", gui: true }, // draw atoms as spheres
        "cartoon": { validItems: GLModel.validCartoonSpec, type: "form", gui: true }, // draw cartoon representation of secondary structure
        "colorfunc": { validItems: null, type: "js", valid: false },
        "clicksphere": { validItems: GLModel.validSphereSpec, type: "form" } //invisible style for click handling
    };
 
    static validSurfaceSpecs = {
        "opacity": { type: "number", floatType: true, gui: true, step: 0.01, default: 1, min: 0, max: 1 },
        "colorscheme": { type: "colorscheme", gui: true },
        "color": { type: "color", gui: true },
        "voldata": { type: "number", floatType: true, gui: false },
        "volscheme": { type: "number", floatType: true, gui: false },
        "map": { type: "number", gui: false }
    };
 
    static validLabelResSpecs = {
        "font": { type: "string", gui: true },
        "fontSize": { type: "number", floatType: true, gui: true, step: 1, default: 12, min: 1 },
        "fontColor": { type: "color", gui: true },
        "fontOpacity": { type: "number", floatType: true, gui: true, step: 0.1, default: 1, min: 0, max: 1 },
        "borderThickness": { type: "number", floatType: true, gui: true, step: 0.1, default: 1, min: 0 },
        "borderColor": { type: "color", gui: true },
        "borderOpacity": { type: "number", floatType: true, gui: true, step: 0.1, default: 1, min: 0, max: 1 },
        "backgroundColor": { type: "color", gui: true },
        "backgroundOpacity": { type: "number", floatType: true, gui: true, step: 0.1, default: 1, min: 0, max: 1 },
        "position": { type: "array", valid: false },
        "inFront": { type: "boolean", gui: true },
        "showBackground": { type: "boolean", gui: true },
        "fixed": { type: "boolean", gui: true },
        "alignment": { validItems: ["topLeft", "topCenter", "topRight", "centerLeft", "center", "centerRight", "bottomLeft", "bottomCenter", "bottomRight"], gui: true },
        "scale": { type: "boolean", gui: false },
    };
 
    // class functions
    // return true if a and b represent the same style
    static sameObj(a, b) {
        if (a && b)
            return JSON.stringify(a) == JSON.stringify(b);
        else
            return a == b;
    };
 
    public unitCellObjects: any;
 
    // private variables
    private atoms = [];
    private frames: any = [];
    private box: any = null;
    private atomdfs: any = null; //depth first search over connected components
    private id = 0;
    private hidden: any = false;
    private molObj: any = null;
    private renderedMolObj: any = null;
    private lastColors: any = null;
    private modelData: any = {};
    private modelDatas: any = null; //if there is different modelData per frame
    private idMatrix = new Matrix4();
    private dontDuplicateAtoms = true;
    private defaultColor = elementColors.defaultColor;
 
    private options: any;
    private ElementColors: any;
 
 
    private readonly defaultSphereRadius: number;
    private readonly defaultCartoonQuality: number;
    // bonds as cylinders
    private readonly defaultStickRadius = 0.25;
 
    constructor(mid, options?) {
 
        this.options = options || {};
        this.ElementColors = (this.options.defaultcolors) ? this.options.defaultcolors : elementColors.defaultColors;
 
        this.defaultSphereRadius = (this.options.defaultSphereRadius) ? this.options.defaultSphereRadius : 1.5;
        this.defaultCartoonQuality = (this.options.cartoonQuality) ? this.options.cartoonQuality : 10;
        this.id = mid;
    }
    // return proper radius for atom given style
    /** 
     * 
     * @param {AtomSpec} atom
     * @param {atomstyle} style
     * @return {number} 
     * 
     */
    private getRadiusFromStyle(atom, style) {
        var r = this.defaultSphereRadius;
        if (typeof (style.radius) != "undefined")
            r = style.radius;
        else if (GLModel.vdwRadii[atom.elem])
            r = GLModel.vdwRadii[atom.elem];
        else Iif (atom.elem.length > 1) { //see if adjusting case helps
            let e:string = atom.elem;
            e = e[0].toUpperCase()+e[1].toLowerCase();
            Iif (GLModel.vdwRadii[e]) 
                r = GLModel.vdwRadii[e];
        }
 
        Iif (typeof (style.scale) != "undefined")
            r *= style.scale;
        return r;
    };
 
    // cross drawing
    /** @typedef CrossStyleSpec
     * @prop {boolean} hidden - do not show 
     * @prop {number} linewidth *deprecated due to vanishing browser support* 
     * @prop {number} radius 
     * @prop {number} scale - scale radius by specified amount
     * @prop {ColorschemeSpec} colorscheme - element based coloring
     * @prop {ColorSpec} color - fixed coloring, overrides colorscheme
     * @prop {number} opacity - opacity, must be the same for all atoms in the model
     */
    /**
     * 
     * @param {AtomSpec} atom
     * @param {Geometry[]} geos
     */
    private drawAtomCross(atom, geos) {
        Iif (!atom.style.cross)
            return;
        var style = atom.style.cross;
        Iif (style.hidden)
            return;
        var linewidth = (style.linewidth || GLModel.defaultlineWidth);
        Iif (!geos[linewidth])
            geos[linewidth] = new Geometry();
 
        var geoGroup = geos[linewidth].updateGeoGroup(6);
 
        var delta = this.getRadiusFromStyle(atom, style);
 
        var points = [[delta, 0, 0], [-delta, 0, 0], [0, delta, 0],
        [0, -delta, 0], [0, 0, delta], [0, 0, -delta]];
 
        var clickable = atom.clickable || atom.hoverable;
        Iif (clickable && atom.intersectionShape === undefined)
            atom.intersectionShape = { sphere: [], cylinder: [], line: [] };
 
        var c = getColorFromStyle(atom, style);
 
        var vertexArray = geoGroup.vertexArray;
        var colorArray = geoGroup.colorArray;
 
        for (var j = 0; j < 6; j++) {
 
            var offset = geoGroup.vertices * 3;
 
            geoGroup.vertices++;
            vertexArray[offset] = atom.x + points[j][0];
            vertexArray[offset + 1] = atom.y + points[j][1];
            vertexArray[offset + 2] = atom.z + points[j][2];
            colorArray[offset] = c.r;
            colorArray[offset + 1] = c.g;
            colorArray[offset + 2] = c.b;
 
            Iif (clickable) {
                var point = new Vector3(points[j][0], points[j][1], points[j][2]);
 
                //decrease cross size for selection to prevent misselection from atom overlap
                point.multiplyScalar(0.1);
                point.set(point.x + atom.x, point.y + atom.y, point.z + atom.z);
                atom.intersectionShape.line.push(point);
            }
 
        }
 
    };
 
    private getGoodCross(atom, atom2, p1, dir) {
        // get vector 2 different neighboring atom
        //find most divergent neighbor
        var bestv = null;
        var bestlen = -1;
        for (var j = 0, n = atom.bonds.length; j < n; j++) {
            Iif (atom.bonds[j] != atom2.index) {
                let j2 = atom.bonds[j];
                let atom3 = this.atoms[j2];
                let p3 = new Vector3(atom3.x, atom3.y, atom3.z);
 
                let dir2 = p3.clone();
                dir2.sub(p1);
 
                let v = dir2.clone();
                v.cross(dir);
                var l = v.lengthSq();
                Iif (l > bestlen) {
                    bestlen = l;
                    bestv = v;
                    Iif (bestlen > 0.1) {
                        return bestv;
                    }
                }
            }
        }
        return bestv;
    };
 
    //from atom, return a normalized vector v that is orthogonal and along which
    //it is appropraite to draw multiple bonds
    private getSideBondV(atom, atom2, i) {
 
        var i2, j2, atom3, p3, dir2;
        var p1 = new Vector3(atom.x, atom.y, atom.z);
        var p2 = new Vector3(atom2.x, atom2.y, atom2.z);
        var dir = p2.clone();
        var v = null;
        dir.sub(p1);
 
        if (atom.bonds.length === 1) {
            if (atom2.bonds.length === 1) {
                v = dir.clone();
                if (Math.abs(v.x) > 0.0001)
                    v.y += 1;
                else
                    v.x += 1;
            } else {
                i2 = (i + 1) % atom2.bonds.length;
                j2 = atom2.bonds[i2];
                atom3 = this.atoms[j2];
                p3 = new Vector3(atom3.x, atom3.y, atom3.z);
 
                dir2 = p3.clone();
                dir2.sub(p1);
 
                v = dir2.clone();
                v.cross(dir);
            }
        } else {
            v = this.getGoodCross(atom, atom2, p1, dir);
 
            Iif (v.lengthSq() < 0.01) {
                var v2 = this.getGoodCross(atom2, atom, p1, dir);
                Iif (v2 != null) v = v2; //can be null if no other neighbors
            }
        }
 
        // especially for C#C (triple bond) dir and dir2
        // may be opposites resulting in a zero v
        Iif (v.lengthSq() < 0.01) {
            v = dir.clone();
            if (Math.abs(v.x) > 0.0001)
                v.y += 1;
            else
                v.x += 1;
        }
 
        v.cross(dir);
        v.normalize();
 
        return v;
 
        //v.multiplyScalar(r * 1.5);
 
    };
 
    private addLine(vertexArray, colorArray, offset, p1, p2, c1) {
        //make line from p1 to p2, does not incremeant counts
        vertexArray[offset] = p1.x; vertexArray[offset + 1] = p1.y; vertexArray[offset + 2] = p1.z;
        colorArray[offset] = c1.r; colorArray[offset + 1] = c1.g; colorArray[offset + 2] = c1.b;
        vertexArray[offset + 3] = p2.x; vertexArray[offset + 4] = p2.y; vertexArray[offset + 5] = p2.z;
        colorArray[offset + 3] = c1.r; colorArray[offset + 4] = c1.g; colorArray[offset + 5] = c1.b;
    };
 
    /**@typedef LineStyleSpec
     * @prop {boolean} hidden - do not show line
     * @prop {number} linewidth *deprecated due to vanishing browser support* 
     * @prop {ColorschemeSpec} colorscheme - element based coloring
     * @prop {ColorSpec} color - fixed coloring, overrides colorscheme
     * @prop {number} opacity - opacity, must be the same for all atoms in the model
     */
 
    // bonds - both atoms must match bond style
    // standardize on only drawing for lowest to highest
    /**
     * 
     * @param {AtomSpec}
     *            atom
     * @param {AtomSpec[]} atoms
     * @param {Geometry[]} geos
     */
    private drawBondLines(atom, atoms, geos) {
        Iif (!atom.style.line)
            return;
        var style = atom.style.line;
        Iif (style.hidden)
            return;
        var p1a, p1b, p2a, p2b;
        // have a separate geometry for each linewidth
        var linewidth = (style.linewidth || GLModel.defaultlineWidth);
 
        Iif (!geos[linewidth])
            geos[linewidth] = new Geometry();
        /** @type {geometryGroup} */
        var geoGroup = geos[linewidth].updateGeoGroup(6 * atom.bonds.length); //reserve enough space even for triple bonds
 
        var vertexArray = geoGroup.vertexArray;
        var colorArray = geoGroup.colorArray;
 
        for (var i = 0; i < atom.bonds.length; i++) {
            var j = atom.bonds[i]; // our neighbor
 
            var atom2 = atoms[j];
            Iif (!atom2.style.line)
                continue; // don't sweat the details
 
            Iif (atom.index >= atom2.index) // only draw if less, this way we can do multi bonds correctly
                continue;
            var p1 = new Vector3(atom.x, atom.y, atom.z);
            var p2 = new Vector3(atom2.x, atom2.y, atom2.z);
            var mp = p1.clone().add(p2).multiplyScalar(0.5);
            var singleBond = false;
 
            var atomneedsi = atom.clickable || atom.hoverable;
            var atom2needsi = atom2.clickable || atom2.hoverable;
 
            Iif (atomneedsi || atom2needsi) {
                Iif (atomneedsi) {
                    Iif (atom.intersectionShape === undefined)
                        atom.intersectionShape = { sphere: [], cylinder: [], line: [], triangle: [] };
                    atom.intersectionShape.line.push(p1);
                    atom.intersectionShape.line.push(mp);
                }
                Iif (atom2needsi) {
                    Iif (atom2.intersectionShape === undefined)
                        atom2.intersectionShape = { sphere: [], cylinder: [], line: [], triangle: [] };
                    atom2.intersectionShape.line.push(mp);
                    atom2.intersectionShape.line.push(p2);
                }
            }
            var c1 = getColorFromStyle(atom, atom.style.line);
            var c2 = getColorFromStyle(atom2, atom2.style.line);
 
            Iif (atom.bondStyles && atom.bondStyles[i]) {
                var bstyle = atom.bondStyles[i];
                Iif (!bstyle.iswire) {
                    continue;
                }
                Iif (bstyle.singleBond) singleBond = true;
                Iif (typeof (bstyle.color1) != "undefined") {
                    c1 = CC.color(bstyle.color1);
                }
                Iif (typeof (bstyle.color2) != "undefined") {
                    c2 = CC.color(bstyle.color2);
                }
            }
 
            var offset = geoGroup.vertices * 3;
            var mpa, mpb;
 
            if (atom.bondOrder[i] > 1 && atom.bondOrder[i] < 4 && !singleBond) {
                var v = this.getSideBondV(atom, atom2, i);
                var dir = p2.clone();
                dir.sub(p1);
 
                if (atom.bondOrder[i] == 2) { //double
 
                    v.multiplyScalar(0.1);
                    p1a = p1.clone();
                    p1a.add(v);
                    p1b = p1.clone();
                    p1b.sub(v);
 
                    p2a = p1a.clone();
                    p2a.add(dir);
                    p2b = p1b.clone();
                    p2b.add(dir);
 
                    if (c1 == c2) {
                        geoGroup.vertices += 4;
                        this.addLine(vertexArray, colorArray, offset, p1a, p2a, c1);
                        this.addLine(vertexArray, colorArray, offset + 6, p1b, p2b, c1);
                    }
                    else {
                        geoGroup.vertices += 8;
                        dir.multiplyScalar(0.5);
                        mpa = p1a.clone();
                        mpa.add(dir);
                        mpb = p1b.clone();
                        mpb.add(dir);
 
                        this.addLine(vertexArray, colorArray, offset, p1a, mpa, c1);
                        this.addLine(vertexArray, colorArray, offset + 6, mpa, p2a, c2);
                        this.addLine(vertexArray, colorArray, offset + 12, p1b, mpb, c1);
                        this.addLine(vertexArray, colorArray, offset + 18, mpb, p2b, c2);
                    }
                }
                else Iif (atom.bondOrder[i] == 3) { //triple
 
                    v.multiplyScalar(0.1);
                    p1a = p1.clone();
                    p1a.add(v);
                    p1b = p1.clone();
                    p1b.sub(v);
 
                    p2a = p1a.clone();
                    p2a.add(dir);
                    p2b = p1b.clone();
                    p2b.add(dir);
 
                    if (c1 == c2) {
                        geoGroup.vertices += 6;
                        this.addLine(vertexArray, colorArray, offset, p1, p2, c1);
                        this.addLine(vertexArray, colorArray, offset + 6, p1a, p2a, c1);
                        this.addLine(vertexArray, colorArray, offset + 12, p1b, p2b, c1);
                    }
                    else {
                        geoGroup.vertices += 12;
                        dir.multiplyScalar(0.5);
                        mpa = p1a.clone();
                        mpa.add(dir);
                        mpb = p1b.clone();
                        mpb.add(dir);
 
                        this.addLine(vertexArray, colorArray, offset, p1, mp, c1);
                        this.addLine(vertexArray, colorArray, offset + 6, mp, p2, c2);
                        this.addLine(vertexArray, colorArray, offset + 12, p1a, mpa, c1);
                        this.addLine(vertexArray, colorArray, offset + 18, mpa, p2a, c2);
                        this.addLine(vertexArray, colorArray, offset + 24, p1b, mpb, c1);
                        this.addLine(vertexArray, colorArray, offset + 30, mpb, p2b, c2);
                    }
                }
            }
            else { //single bond                                    
                if (c1 == c2) {
                    geoGroup.vertices += 2;
                    this.addLine(vertexArray, colorArray, offset, p1, p2, c1);
                } else {
                    geoGroup.vertices += 4;
                    this.addLine(vertexArray, colorArray, offset, p1, mp, c1);
                    this.addLine(vertexArray, colorArray, offset + 6, mp, p2, c2);
                }
 
            }
        }
 
    };
 
 
 
    /**@typedef SphereStyleSpec
     * @prop {boolean} hidden - do not show atom
     * @prop {number} radius - override van der waals radius
     * @prop {number} scale - scale radius by specified amount
     * @prop {ColorschemeSpec} colorscheme - element based coloring
     * @prop {ColorSpec} color - fixed coloring, overrides colorscheme
     * @prop {number} opacity - opacity, must be the same for all atoms in the model
     */
 
    //sphere drawing
    //See also: drawCylinder
    /** 
     * 
     * @param {AtomSpec} atom
     * @param {Geometry} geo
     */
    private drawAtomSphere(atom, geo: Geometry) {
 
        Iif (!atom.style.sphere)
            return;
        var style = atom.style.sphere;
        Iif (style.hidden)
            return;
 
        var C = getColorFromStyle(atom, style);
 
        var radius = this.getRadiusFromStyle(atom, style);
 
        Iif ((atom.clickable === true || atom.hoverable) && (atom.intersectionShape !== undefined)) {
            var center = new Vector3(atom.x, atom.y, atom.z);
            atom.intersectionShape.sphere.push(new Sphere(center, radius));
        }
 
        GLDraw.drawSphere(geo, atom, radius, C);
 
    };
 
    /** Register atom shaped click handlers */
    private drawAtomClickSphere(atom) {
 
        Iif (!atom.style.clicksphere)
            return;
        var style = atom.style.clicksphere;
        Iif (style.hidden)
            return;
 
        var radius = this.getRadiusFromStyle(atom, style);
 
        Iif ((atom.clickable === true || atom.hoverable) && (atom.intersectionShape !== undefined)) {
            var center = new Vector3(atom.x, atom.y, atom.z);
            atom.intersectionShape.sphere.push(new Sphere(center, radius));
        }
    };
 
    private drawAtomInstanced(atom, geo) {
 
        Iif (!atom.style.sphere)
            return;
        var style = atom.style.sphere;
        Iif (style.hidden)
            return;
 
        var radius = this.getRadiusFromStyle(atom, style);
        var C = getColorFromStyle(atom, style);
 
        var geoGroup = geo.updateGeoGroup(1);
        var startv = geoGroup.vertices;
        var start = startv * 3;
        var vertexArray = geoGroup.vertexArray;
        var colorArray = geoGroup.colorArray;
        var radiusArray = geoGroup.radiusArray;
 
        vertexArray[start] = atom.x;
        vertexArray[start + 1] = atom.y;
        vertexArray[start + 2] = atom.z;
 
        colorArray[start] = C.r;
        colorArray[start + 1] = C.g;
        colorArray[start + 2] = C.b;
 
        radiusArray[startv] = radius;
 
        Iif ((atom.clickable === true || atom.hoverable) && (atom.intersectionShape !== undefined)) {
            var center = new Vector3(atom.x, atom.y, atom.z);
            atom.intersectionShape.sphere.push(new Sphere(center, radius));
        }
 
        geoGroup.vertices += 1;
 
    };
 
    private drawSphereImposter(geo, center, radius, C) {
        //create flat square                                   
        var geoGroup = geo.updateGeoGroup(4);
        var i;
        var startv = geoGroup.vertices;
        var start = startv * 3;
        var vertexArray = geoGroup.vertexArray;
        var colorArray = geoGroup.colorArray;
 
        //use center point for each vertex
        for (i = 0; i < 4; i++) {
            vertexArray[start + 3 * i] = center.x;
            vertexArray[start + 3 * i + 1] = center.y;
            vertexArray[start + 3 * i + 2] = center.z;
        }
 
 
        //same colors for all 4 vertices
        var normalArray = geoGroup.normalArray;
        for (i = 0; i < 4; i++) {
            colorArray[start + 3 * i] = C.r;
            colorArray[start + 3 * i + 1] = C.g;
            colorArray[start + 3 * i + 2] = C.b;
        }
 
        normalArray[start + 0] = -radius;
        normalArray[start + 1] = radius;
        normalArray[start + 2] = 0;
 
        normalArray[start + 3] = -radius;
        normalArray[start + 4] = -radius;
        normalArray[start + 5] = 0;
 
        normalArray[start + 6] = radius;
        normalArray[start + 7] = -radius;
        normalArray[start + 8] = 0;
 
        normalArray[start + 9] = radius;
        normalArray[start + 10] = radius;
        normalArray[start + 11] = 0;
 
        geoGroup.vertices += 4;
 
        //two faces
        var faceArray = geoGroup.faceArray;
        var faceoffset = geoGroup.faceidx; //not number faces, but index
        faceArray[faceoffset + 0] = startv;
        faceArray[faceoffset + 1] = startv + 1;
        faceArray[faceoffset + 2] = startv + 2;
        faceArray[faceoffset + 3] = startv + 2;
        faceArray[faceoffset + 4] = startv + 3;
        faceArray[faceoffset + 5] = startv;
        geoGroup.faceidx += 6;
    };
 
    //dkoes -  code for sphere imposters
    private drawAtomImposter(atom, geo: Geometry) {
 
        Iif (!atom.style.sphere)
            return;
        var style = atom.style.sphere;
        Iif (style.hidden)
            return;
 
        var radius = this.getRadiusFromStyle(atom, style);
        var C = getColorFromStyle(atom, style);
 
        Iif ((atom.clickable === true || atom.hoverable) && (atom.intersectionShape !== undefined)) {
            var center = new Vector3(atom.x, atom.y, atom.z);
            atom.intersectionShape.sphere.push(new Sphere(center, radius));
        }
 
        this.drawSphereImposter(geo, atom, radius, C);
    };
 
 
    static drawStickImposter(geo, from, to, radius, color) {
        //we need the four corners - two have from coord, two have to coord, the normal
        //is the opposing point, from which we can get the normal and length
        //also need the radius
        var geoGroup = geo.updateGeoGroup(4);
        var startv = geoGroup.vertices;
        var start = startv * 3;
        var vertexArray = geoGroup.vertexArray;
        var colorArray = geoGroup.colorArray;
        var radiusArray = geoGroup.radiusArray;
        var normalArray = geoGroup.normalArray;
        //encode extra bits of information in the color
        var r = color.r;
        var g = color.g;
        var b = color.b;
 
        var negateColor = function(c) {
            //set sign bit
            var n = -c;
            Iif (n == 0) n = -0.0001;
            return n;
        };
 
        /* for sticks, always draw caps, but we could in theory set caps in color */
 
        //4 vertices, distinguish between p1 and p2 with neg blue
        var pos = start;
        for (var i = 0; i < 4; i++) {
            vertexArray[pos] = from.x;
            normalArray[pos] = to.x;
            colorArray[pos] = r;
            pos++;
            vertexArray[pos] = from.y;
            normalArray[pos] = to.y;
            colorArray[pos] = g;
            pos++;
            vertexArray[pos] = from.z;
            normalArray[pos] = to.z;
            if (i < 2)
                colorArray[pos] = b;
            else
                colorArray[pos] = negateColor(b);
            pos++;
        }
 
        geoGroup.vertices += 4;
 
        radiusArray[startv] = -radius;
        radiusArray[startv + 1] = radius;
        radiusArray[startv + 2] = -radius;
        radiusArray[startv + 3] = radius;
 
        //two faces
        var faceArray = geoGroup.faceArray;
        var faceoffset = geoGroup.faceidx; //not number faces, but index
        faceArray[faceoffset + 0] = startv;
        faceArray[faceoffset + 1] = startv + 1;
        faceArray[faceoffset + 2] = startv + 2;
        faceArray[faceoffset + 3] = startv + 2;
        faceArray[faceoffset + 4] = startv + 3;
        faceArray[faceoffset + 5] = startv;
        geoGroup.faceidx += 6;
    };
 
    /**@typedef StickStyleSpec
     * @prop {boolean} hidden - do not show 
     * @prop {number} radius 
     * @prop {boolean} singleBonds - draw all bonds as single bonds if set
     * @prop {ColorschemeSpec} colorscheme - element based coloring
     * @prop {ColorSpec} color - fixed coloring, overrides colorscheme
     * @prop {number} opacity - opacity, must be the same for all atoms in the model
     */
 
    // draws cylinders and small spheres (at bond radius)
    private drawBondSticks(atom, atoms, geo) {
        Iif (!atom.style.stick)
            return;
        var style = atom.style.stick;
        Iif (style.hidden)
            return;
 
        var atomBondR = style.radius || this.defaultStickRadius;
        var bondR = atomBondR;
        var atomSingleBond = style.singleBonds || false;
        var fromCap = 0, toCap = 0;
        var atomneedsi, atom2needsi, i, singleBond, bstyle;
        var cylinder1a, cylinder1b, cylinder1c, cylinder2a, cylinder2b, cylinder2c;
 
        var C1 = getColorFromStyle(atom, style);
 
        var mp, mp2, mp3;
 
        Iif (!atom.capDrawn && atom.bonds.length < 4)
            fromCap = 2;
 
        var drawCyl = GLDraw.drawCylinder; //mesh cylinder
        Iif (geo.imposter)
            drawCyl = GLModel.drawStickImposter;
 
 
        for (i = 0; i < atom.bonds.length; i++) {
            var j = atom.bonds[i]; // our neighbor
            var atom2 = atoms[j]; //parsePDB, etc should only add defined bonds
            mp = mp2 = mp3 = null;
            Iif (atom.index < atom2.index) {// only draw if less, this
                // lets us combine
                // cylinders of the same
                // color
                var style2 = atom2.style;
                Iif (!style2.stick || style2.stick.hidden)
                    continue; // don't sweat the details                     
 
                var C2 = getColorFromStyle(atom2, style2.stick);
 
                //support bond specific styles
                bondR = atomBondR;
                singleBond = atomSingleBond;
                Iif (atom.bondStyles && atom.bondStyles[i]) {
                    bstyle = atom.bondStyles[i];
                    Iif (bstyle.iswire) {
                        continue;
                    }
                    Iif (bstyle.radius) bondR = bstyle.radius;
                    Iif (bstyle.singleBond) singleBond = true;
                    Iif (typeof (bstyle.color1) != "undefined") {
                        C1 = CC.color(bstyle.color1);
                    }
                    Iif (typeof (bstyle.color2) != "undefined") {
                        C2 = CC.color(bstyle.color2);
                    }
                }
                var p1 = new Vector3(atom.x, atom.y, atom.z);
                var p2 = new Vector3(atom2.x, atom2.y, atom2.z);
 
                // draw cylinders
                if (atom.bondOrder[i] === 1 || singleBond || atom.bondOrder[i] > 3) { //TODO: aromatics at 4
 
                    Iif (!atom2.capDrawn && atom2.bonds.length < 4)
                        toCap = 2;
 
                    if (C1 != C2) {
                        mp = new Vector3().addVectors(p1, p2)
                            .multiplyScalar(0.5);
                        drawCyl(geo, p1, mp, bondR, C1, fromCap, 0);
                        drawCyl(geo, mp, p2, bondR, C2, 0, toCap);
                    } else {
                        drawCyl(geo, p1, p2, bondR, C1, fromCap, toCap);
                    }
 
 
                    atomneedsi = atom.clickable || atom.hoverable;
                    atom2needsi = atom2.clickable || atom2.hoverable;
 
                    Iif (atomneedsi || atom2needsi) {
                        Iif (!mp) mp = new Vector3().addVectors(p1, p2).multiplyScalar(0.5);
                        Iif (atomneedsi) {
                            var cylinder1 = new Cylinder(p1, mp, bondR);
                            var sphere1 = new Sphere(p1, bondR);
                            atom.intersectionShape.cylinder.push(cylinder1);
                            atom.intersectionShape.sphere.push(sphere1);
                        }
                        Iif (atom2needsi) {
                            var cylinder2 = new Cylinder(p2, mp, bondR);
                            var sphere2 = new Sphere(p2, bondR);
                            atom2.intersectionShape.cylinder.push(cylinder2);
                            atom2.intersectionShape.sphere.push(sphere2);
                        }
                    }
                }
                else Iif (atom.bondOrder[i] > 1) {
                    //multi bond caps
                    var mfromCap = 0;
                    var mtoCap = 0;
 
                    Iif (bondR != atomBondR) {
                        //assume jmol style multiple bonds - the radius doesn't fit within atom sphere
                        mfromCap = 2;
                        mtoCap = 2;
                    }
 
                    var dir = p2.clone();
                    var v = null;
                    dir.sub(p1);
 
                    var r, p1a, p1b, p2a, p2b;
                    v = this.getSideBondV(atom, atom2, i);
 
                    if (atom.bondOrder[i] == 2) {
                        r = bondR / 2.5;
 
                        v.multiplyScalar(r * 1.5);
                        p1a = p1.clone();
                        p1a.add(v);
                        p1b = p1.clone();
                        p1b.sub(v);
 
                        p2a = p1a.clone();
                        p2a.add(dir);
                        p2b = p1b.clone();
                        p2b.add(dir);
 
                        if (C1 != C2) {
                            mp = new Vector3().addVectors(p1a, p2a)
                                .multiplyScalar(0.5);
                            mp2 = new Vector3().addVectors(p1b, p2b)
                                .multiplyScalar(0.5);
                            drawCyl(geo, p1a, mp, r, C1, mfromCap, 0);
                            drawCyl(geo, mp, p2a, r, C2, 0, mtoCap);
                            drawCyl(geo, p1b, mp2, r, C1, mfromCap, 0);
                            drawCyl(geo, mp2, p2b, r, C2, 0, mtoCap);
                        } else {
                            drawCyl(geo, p1a, p2a, r, C1, mfromCap, mtoCap);
                            drawCyl(geo, p1b, p2b, r, C1, mfromCap, mtoCap);
                        }
 
                        atomneedsi = atom.clickable || atom.hoverable;
                        atom2needsi = atom2.clickable || atom2.hoverable;
 
                        Iif (atomneedsi || atom2needsi) {
                            Iif (!mp) mp = new Vector3().addVectors(p1a, p2a)
                                .multiplyScalar(0.5);
                            Iif (!mp2) mp2 = new Vector3().addVectors(p1b, p2b)
                                .multiplyScalar(0.5);
                            Iif (atomneedsi) {
                                cylinder1a = new Cylinder(p1a, mp, r);
                                cylinder1b = new Cylinder(p1b, mp2, r);
                                atom.intersectionShape.cylinder.push(cylinder1a);
                                atom.intersectionShape.cylinder.push(cylinder1b);
                            }
                            Iif (atom2needsi) {
                                cylinder2a = new Cylinder(p2a, mp, r);
                                cylinder2b = new Cylinder(p2b, mp2, r);
                                atom2.intersectionShape.cylinder.push(cylinder2a);
                                atom2.intersectionShape.cylinder.push(cylinder2b);
                            }
                        }
                    }
                    else Iif (atom.bondOrder[i] == 3) {
                        r = bondR / 4;
                        v.cross(dir);
                        v.normalize();
                        v.multiplyScalar(r * 3);
 
                        p1a = p1.clone();
                        p1a.add(v);
                        p1b = p1.clone();
                        p1b.sub(v);
 
                        p2a = p1a.clone();
                        p2a.add(dir);
                        p2b = p1b.clone();
                        p2b.add(dir);
 
                        if (C1 != C2) {
                            mp = new Vector3().addVectors(p1a, p2a)
                                .multiplyScalar(0.5);
                            mp2 = new Vector3().addVectors(p1b, p2b)
                                .multiplyScalar(0.5);
                            mp3 = new Vector3().addVectors(p1, p2)
                                .multiplyScalar(0.5);
                            drawCyl(geo, p1a, mp, r, C1, mfromCap, 0);
                            drawCyl(geo, mp, p2a, r, C2, 0, mtoCap);
                            drawCyl(geo, p1, mp3, r, C1, fromCap, 0);
                            drawCyl(geo, mp3, p2, r, C2, 0, toCap);
                            drawCyl(geo, p1b, mp2, r, C1, mfromCap, 0);
                            drawCyl(geo, mp2, p2b, r, C2, 0, mtoCap);
                        } else {
                            drawCyl(geo, p1a, p2a, r, C1, mfromCap, mtoCap);
                            drawCyl(geo, p1, p2, r, C1, fromCap, toCap);
                            drawCyl(geo, p1b, p2b, r, C1, mfromCap, mtoCap);
                        }
 
                        atomneedsi = atom.clickable || atom.hoverable;
                        atom2needsi = atom2.clickable || atom2.hoverable;
 
                        Iif (atomneedsi || atom2needsi) {
                            Iif (!mp) mp = new Vector3().addVectors(p1a, p2a)
                                .multiplyScalar(0.5);
                            Iif (!mp2) mp2 = new Vector3().addVectors(p1b, p2b)
                                .multiplyScalar(0.5);
                            Iif (!mp3) mp3 = new Vector3().addVectors(p1, p2)
                                .multiplyScalar(0.5);
 
                            Iif (atomneedsi) {
                                cylinder1a = new Cylinder(p1a.clone(), mp.clone(), r);
                                cylinder1b = new Cylinder(p1b.clone(), mp2.clone(), r);
                                cylinder1c = new Cylinder(p1.clone(), mp3.clone(), r);
                                atom.intersectionShape.cylinder.push(cylinder1a);
                                atom.intersectionShape.cylinder.push(cylinder1b);
                                atom.intersectionShape.cylinder.push(cylinder1c);
                            }
                            Iif (atom2needsi) {
                                cylinder2a = new Cylinder(p2a.clone(), mp.clone(), r);
                                cylinder2b = new Cylinder(p2b.clone(), mp2.clone(), r);
                                cylinder2c = new Cylinder(p2.clone(), mp3.clone(), r);
                                atom2.intersectionShape.cylinder.push(cylinder2a);
                                atom2.intersectionShape.cylinder.push(cylinder2b);
                                atom2.intersectionShape.cylinder.push(cylinder2c);
                            }
                        }
                    }
                }
 
            }
 
        }
 
        // draw non bonded heteroatoms as spheres
        var drawSphere = false;
        var numsinglebonds = 0;
        var differentradii = false;
        //also, if any bonds were drawn as multiples, need sphere
        for (i = 0; i < atom.bonds.length; i++) {
            singleBond = atomSingleBond;
            Iif (atom.bondStyles && atom.bondStyles[i]) {
                bstyle = atom.bondStyles[i];
                Iif (bstyle.singleBond) singleBond = true;
                Iif (bstyle.radius && bstyle.radius != atomBondR) {
                    differentradii = true;
                }
            }
            Iif (singleBond || atom.bondOrder[i] == 1) {
                numsinglebonds++;
            }
        }
 
        if (differentradii) { //jmol style double/triple bonds - no sphere
            Iif (numsinglebonds > 0) drawSphere = true; //unless needed as a cap
        }
        else Iif (numsinglebonds == 0 && atom.bonds.length > 0) {
            drawSphere = true;
        }
 
        Iif (drawSphere) {
            bondR = atomBondR;
            //do not use bond style as this can be variable, particularly
            //with jmol export of double/triple bonds
            if (geo.imposter) {
                this.drawSphereImposter(geo.sphereGeometry, atom, bondR, C1);
            }
            else {
                GLDraw.drawSphere(geo, atom, bondR, C1);
            }
        }
 
    };
 
 
 
    // go through all the atoms and regenerate their geometries
    // we try to have one geometry for each style since this is much much
    // faster
    // at some point we should optimize this to avoid unnecessary
    // recalculation
    /** param {AtomSpec[]} atoms */
    private createMolObj(atoms, options) {
 
        options = options || {};
 
        var ret = new Object3D();
        var cartoonAtoms = [];
        var lineGeometries = {};
        var crossGeometries = {};
 
        var drawSphereFunc = this.drawAtomSphere;
        var sphereGeometry = null;
        var stickGeometry = null;
        if (options.supportsImposters) {
            drawSphereFunc = this.drawAtomImposter;
            sphereGeometry = new Geometry(true);
            sphereGeometry.imposter = true;
            stickGeometry = new Geometry(true, true);
            stickGeometry.imposter = true;
            stickGeometry.sphereGeometry = new Geometry(true); //for caps
            stickGeometry.sphereGeometry.imposter = true;
            stickGeometry.drawnCaps = {};
        }
        else if (options.supportsAIA) {
            drawSphereFunc = this.drawAtomInstanced;
            sphereGeometry = new Geometry(false, true, true);
            sphereGeometry.instanced = true;
            stickGeometry = new Geometry(true); //don't actually have instanced sticks
        } else {
            sphereGeometry = new Geometry(true);
            stickGeometry = new Geometry(true);
        }
 
        var i, j, n, testOpacities;
        var opacities: any = {};
        var range = [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY];
        for (i = 0, n = atoms.length; i < n; i++) {
            var atom = atoms[i];
            // recreate gl info for each atom as necessary
            // set up appropriate intersection spheres for clickable atoms
 
            Iif (atom && atom.style) {
 
                Iif ((atom.clickable || atom.hoverable) && atom.intersectionShape === undefined)
                    atom.intersectionShape = { sphere: [], cylinder: [], line: [], triangle: [] };
 
                testOpacities = { line: undefined, cross: undefined, stick: undefined, sphere: undefined };
                for (j in testOpacities) {
                    if (atom.style[j]) {
                        if (atom.style[j].opacity)
                            testOpacities[j] = parseFloat(atom.style[j].opacity);
                        else
                            testOpacities[j] = 1;
 
                    } else testOpacities[j] = undefined;
 
                    if (opacities[j]) {
                        Iif (testOpacities[j] != undefined && opacities[j] != testOpacities[j]) {
                            console.log("Warning: " + j + " opacity is ambiguous");
                            opacities[j] = 1;
                        }
 
                    } else opacities[j] = testOpacities[j];
                }
 
                drawSphereFunc.call(this, atom, sphereGeometry);
                this.drawAtomClickSphere(atom);
                this.drawAtomCross(atom, crossGeometries);
                this.drawBondLines(atom, atoms, lineGeometries);
                this.drawBondSticks(atom, atoms, stickGeometry);
 
                Iif (typeof (atom.style.cartoon) !== "undefined" && !atom.style.cartoon.hidden) {
                    //gradient color scheme range
                    Iif (atom.style.cartoon.color === "spectrum" && typeof (atom.resi) === "number" && !atom.hetflag) {
                        Iif (atom.resi < range[0])
                            range[0] = atom.resi;
                        Iif (atom.resi > range[1])
                            range[1] = atom.resi;
                    }
 
                    cartoonAtoms.push(atom);
                }
            }
        }
        // create cartoon if needed - this is a whole model analysis
        Iif (cartoonAtoms.length > 0) {
            drawCartoon(ret, cartoonAtoms, range, this.defaultCartoonQuality);
        }
 
        // add sphere geometry
        Iif (sphereGeometry && sphereGeometry.vertices > 0) {
            //Initialize buffers in geometry                
            sphereGeometry.initTypedArrays();
            var sphereMaterial = null;
            var sphere = null;
 
            //create appropriate material
            if (sphereGeometry.imposter) {
                sphereMaterial = new SphereImposterMaterial({
                    ambient: 0x000000,
                    vertexColors: true,
                    reflectivity: 0
                });
            }
            else if (sphereGeometry.instanced) {
                sphere = new Geometry(true);
                GLDraw.drawSphere(sphere, { x: 0, y: 0, z: 0 }, 1, new Color(0.5, 0.5, 0.5));
                sphere.initTypedArrays();
                sphereMaterial = new InstancedMaterial({
                    sphereMaterial: new MeshLambertMaterial({
                        ambient: 0x000000,
                        vertexColors: true,
                        reflectivity: 0,
                    }),
                    sphere: sphere
                });
            }
            else { //regular mesh
                sphereMaterial = new MeshLambertMaterial({
                    ambient: 0x000000,
                    vertexColors: true,
                    reflectivity: 0,
                });
            }
            Iif (opacities.sphere < 1 && opacities.sphere >= 0) {
                sphereMaterial.transparent = true;
                sphereMaterial.opacity = opacities.sphere;
            }
 
            sphere = new Mesh(sphereGeometry, sphereMaterial);
            ret.add(sphere);
        }
 
        // add stick geometry
        Iif (stickGeometry.vertices > 0) {
 
            var stickMaterial = null;
            var ballMaterial = null;
            var balls = stickGeometry.sphereGeometry;
            Iif (!balls || typeof (balls.vertices) === 'undefined' || balls.vertices == 0) balls = null; //no balls
 
            //Initialize buffers in geometry                
            stickGeometry.initTypedArrays();
            Iif (balls) balls.initTypedArrays();
 
            //create material
            var matvals = { ambient: 0x000000, vertexColors: true, reflectivity: 0 };
 
            if (stickGeometry.imposter) {
                stickMaterial = new StickImposterMaterial(matvals);
                ballMaterial = new SphereImposterMaterial(matvals);
            } else {
                stickMaterial = new MeshLambertMaterial(matvals);
                ballMaterial = new MeshLambertMaterial(matvals);
 
                Iif (stickMaterial.wireframe) {
                    stickGeometry.setUpWireframe();
                    Iif (balls) balls.setUpWireframe();
                }
            }
 
            Iif (opacities.stick < 1 && opacities.stick >= 0) {
                stickMaterial.transparent = true;
                stickMaterial.opacity = opacities.stick;
                ballMaterial.transparent = true;
                ballMaterial.opacity = opacities.stick;
            }
            var sticks = new Mesh(stickGeometry, stickMaterial);
            ret.add(sticks);
 
            Iif (balls) {
                var stickspheres = new Mesh(balls, ballMaterial);
                ret.add(stickspheres);
            }
        }
 
        //var linewidth;
        // add any line geometries, distinguished by line width
        var linewidth;
        for (i in lineGeometries) {
            Iif (lineGeometries.hasOwnProperty(i)) {
                linewidth = i;
                var lineMaterial = new LineBasicMaterial({
                    linewidth: linewidth,
                    vertexColors: true
                });
                Iif (opacities.line < 1 && opacities.line >= 0) {
                    lineMaterial.transparent = true;
                    lineMaterial.opacity = opacities.line;
                }
 
                lineGeometries[i].initTypedArrays();
 
                var line = new Line(lineGeometries[i], lineMaterial as Material, LineStyle.LinePieces);
 
                ret.add(line);
            }
        }
 
        // add any cross geometries
        for (i in crossGeometries) {
            Iif (crossGeometries.hasOwnProperty(i)) {
                linewidth = i;
                var crossMaterial = new LineBasicMaterial({
                    linewidth: linewidth,
                    vertexColors: true
                });
                Iif (opacities.cross < 1 && opacities.cross >= 0) {
                    crossMaterial.transparent = true;
                    crossMaterial.opacity = opacities.cross;
                }
 
                crossGeometries[i].initTypedArrays();
 
                var cross = new Line(crossGeometries[i], crossMaterial as Material, LineStyle.LinePieces);
 
                ret.add(cross);
            }
        }
 
 
        //for BIOMT assembly
        Iif (this.dontDuplicateAtoms && this.modelData.symmetries && this.modelData.symmetries.length > 0) {
            var finalRet = new Object3D();
            var t;
            for (t = 0; t < this.modelData.symmetries.length; t++) {
                var transformedRet = new Object3D();
                transformedRet = ret.clone();
                transformedRet.matrix.copy(this.modelData.symmetries[t]);
                transformedRet.matrixAutoUpdate = false;
                finalRet.add(transformedRet);
            }
            return finalRet;
        }
 
        return ret;
    };
 
 
 
    /**
     * Return object representing internal state of 
     * the model appropriate for passing to setInternalState
     * 
     * @function $3Dmol.GLModel#getInternalState
    */
    public getInternalState() {
        return {
            'atoms': this.atoms,
            'frames': this.frames
        };
    };
 
    /**
     * Overwrite the internal model state with the passed state.
     * 
     * @function $3Dmol.GLModel#setInternalState
    */
    public setInternalState(state) {
        this.atoms = state.atoms;
        this.frames = state.frames;
        this.molObj = null;
    };
 
    /**
     * Returns crystallographic information if present.
     *
     * @function $3Dmol.GLModel#getCrystData
     *
     */
    public getCrystData() {
        if (this.modelData.cryst) {
            // add the matrix if it is missing
            Iif (!this.modelData.cryst.matrix) {
                const cryst = this.modelData.cryst;
                this.modelData.cryst.matrix = conversionMatrix3(
                    cryst.a, cryst.b, cryst.c,
                    cryst.alpha, cryst.beta, cryst.gamma
                );
            }
            return this.modelData.cryst;
        } else {
            return null;
        }
    };
 
    /**
     * Set crystallographic information using three angles and three lengths
     *
     * @function $3Dmol.GLModel#setCrystData
     * @param {number} a - length of unit cell side
     * @param {number} b - length of unit cell side
     * @param {number} c - length of unit cell side
     * @param {number} alpha - unit cell angle in degrees (default 90)
     * @param {number} beta - unit cell angle in degrees (default 90)
     * @param {number} gamma - unit cell angle in degrees (default 90)
     
     */
    public setCrystData(a, b, c, alpha, beta, gamma) {
        //I am assuming these
        a = a || 1.0;
        b = b || 1.0;
        c = c || 1.0;
        alpha = alpha || 90;
        beta = beta || 90;
        gamma = gamma || 90;
 
        const matrix = conversionMatrix3(a, b, c, alpha, beta, gamma);
        this.modelData.cryst = {
            'a': a, 'b': b, 'c': c,
            'alpha': alpha, 'beta': beta, 'gamma': gamma,
            'matrix': matrix
        };
    };
 
    /**
     * Set the crystallographic matrix to the given matrix.
     *
     * This function removes `a`, `b`, `c`, `alpha`, `beta`, `gamma` from 
     * the crystal data.
     *
     * @function $3Dmol.GLModel#setCrystMatrix
     * @param {$3Dmol.Matrix3} matrix - unit cell matrix
     */
    public setCrystMatrix(matrix) {
        matrix = matrix || new Matrix3(
            1, 0, 0,
            0, 1, 0,
            0, 0, 1
        );
 
        this.modelData.cryst = {
            'matrix': matrix
        };
    };
 
    /**
     * Returns list of rotational/translational matrices if there is BIOMT data
     * Otherwise returns a list of just the ID matrix
     *
     * @function $3Dmol.GLModel#getSymmetries
     * @return {Array<$3Dmol.Matrix4>}
     *
     */
    public getSymmetries() {
 
        Iif (typeof (this.modelData.symmetries) == 'undefined') {
            this.modelData.symmetries = [this.idMatrix];
        }
        return this.modelData.symmetries;
    };
 
    /**
     * Sets symmetries based on specified matrices in list
     *
     * @function $3Dmol.GLModel#setSymmetries
     * @param {Array<$3Dmol.Matrix4>} list
     *
     */
    public setSymmetries(list) {
        if (typeof (list) == "undefined") { //delete sym data
            this.modelData.symmetries = [this.idMatrix];
        }
        else {
            this.modelData.symmetries = list;
        }
    };
 
    /**
     * Returns model id number
     * 
     * @function $3Dmol.GLModel#getID
     * @return {number} Model ID
     */
    public getID() {
        return this.id;
    };
 
    /**
     * Returns model's frames property, a list of atom lists
     * 
     * @function $3Dmol.GLModel#getNumFrames
     * @return {number}
     */
    public getNumFrames() {
        return (this.frames.numFrames != undefined) ? this.frames.numFrames : this.frames.length;
    };
 
    private adjustCoord(x1, x2, margin, adjust) {
        //return new value of x2 that isn't more than margin away  
        var dist = x2 - x1;
        if (dist < -margin) {
            return x2 + adjust;
        } else Iif (dist > margin) {
            return x2 - adjust;
        }
        return x2;
    };
    //go over current atoms in depth first order and ensure that connected
    //attoms aren't split across the box
    private adjustCoordinatesToBox() {
        Iif (!this.box) return;
        Iif (!this.atomdfs) return;
        var bx = this.box[0];
        var by = this.box[1];
        var bz = this.box[2];
        var mx = bx * 0.9;
        var my = by * 0.9;
        var mz = bz * 0.9;
 
        for (var c = 0; c < this.atomdfs.length; c++) {
            //for each connected component
            var component = this.atomdfs[c];
            for (var i = 1; i < component.length; i++) {
                //compare each atom to its previous and prevent coordinates from wrapping
                var atom = this.atoms[component[i][0]];
                var prev = this.atoms[component[i][1]];
                atom.x = this.adjustCoord(prev.x, atom.x, mx, bx);
                atom.y = this.adjustCoord(prev.y, atom.y, my, by);
                atom.z = this.adjustCoord(prev.z, atom.z, mz, bz);
            }
        }
    };
 
    /**
     * Sets model's atomlist to specified frame
     * Sets to last frame if framenum out of range
     * 
     * @function $3Dmol.GLModel#setFrame
     * @param {number} framenum - model's atoms are set to this index in frames list
     * @return {Promise}
     */
    public setFrame(framenum, viewer?) { //viewer only passed internally for unit cell 
        var numFrames = this.getNumFrames();
        let model = this;
        return new Promise<void>(function (resolve, reject) {
            Iif (numFrames == 0) {
                //return;
                resolve();
            }
            Iif (framenum < 0 || framenum >= numFrames) {
                framenum = numFrames - 1;
            }
            if (model.frames.url != undefined) {
                var url = model.frames.url;
                getbin(url + "/traj/frame/" + framenum + "/" + model.frames.path, undefined, 'POST', undefined).then(function (buffer) {
                    var values = new Float32Array(buffer, 44);
                    var count = 0;
                    for (var i = 0; i < model.atoms.length; i++) {
                        model.atoms[i].x = values[count++];
                        model.atoms[i].y = values[count++];
                        model.atoms[i].z = values[count++];
                    }
                    //if a box was provided, check to see if we need to wrap connected components
                    Iif (model.box && model.atomdfs) {
                        model.adjustCoordinatesToBox();
                    }
                    resolve();
                }).catch(reject);
            }
            else {
                model.atoms = model.frames[framenum];
                resolve();
            }
            model.molObj = null;
            Iif (model.modelDatas && framenum < model.modelDatas.length) {
                model.modelData = model.modelDatas[framenum];
                Iif (model.unitCellObjects && viewer) {
                    viewer.removeUnitCell(model);
                    viewer.addUnitCell(model);
                }
            }
        });
    };
 
    /**
     * Add atoms as frames of model
     * 
     * @function $3Dmol.GLModel#addFrame
     * @param {AtomSpec} atom - atoms to be added
     */
    public addFrame(atoms) {
        this.frames.push(atoms);
    };
 
 
    /**
     * If model atoms have dx, dy, dz properties (in some xyz files), vibrate populates the model's frame property based on parameters.
     * Model can then be animated
     * 
     * @function $3Dmol.GLModel#vibrate
     * @param {number} numFrames - number of frames to be created, default to 10
     * @param {number} amplitude - amplitude of distortion, default to 1 (full)
     * @param {boolean} bothWays - if true, extend both in positive and negative directions by numFrames
     * @param {GLViewer} viewer - required if arrowSpec is provided
     * @param {ArrowSpec} arrowSpec - specification for drawing animated arrows. If color isn't specified, atom color (sphere, stick, line preference) is used.
     *@example
     
      $3Dmol.download("pdb:4UAA",viewer,{},function(){  
        viewer.setStyle({},{stick:{}});
        viewer.vibrate(10, 1);
        viewer.animate({loop: "forward",reps: 1});
     
        viewer.zoomTo();
              viewer.render();
          });            
     */
    public vibrate(numFrames, amplitude, bothWays?, viewer?, arrowSpec?) {
        amplitude = amplitude || 1;
        numFrames = numFrames || 10;
        var start = 0;
        var end = numFrames;
        Iif (bothWays) {
            start = -numFrames;
            end = numFrames;
        }
 
        //to enable multiple setting of vibrate with bothWays, must record original position
        if (this.frames !== undefined && this.frames.origIndex !== undefined) {
            this.setFrame(this.frames.origIndex);
        } else {
            this.setFrame(0);
        }
 
        Iif (start < end) this.frames = []; //clear
        Iif (bothWays) this.frames.origIndex = numFrames;
 
        for (var i = start; i < end; i++) {
            var newAtoms = [];
            var currframe = this.frames.length;
            Iif (i == 0 && !arrowSpec) { //still need to calculate if drawing arrows
                this.frames.push(this.atoms);
                continue;
            }
            for (var j = 0; j < this.atoms.length; j++) {
                var dx = getAtomProperty(this.atoms[j], 'dx');
                var dy = getAtomProperty(this.atoms[j], 'dy');
                var dz = getAtomProperty(this.atoms[j], 'dz');
                var newVector = new Vector3(dx, dy, dz);
                var starting = new Vector3(this.atoms[j].x, this.atoms[j].y, this.atoms[j].z);
                var mult = (i * amplitude) / numFrames;
                newVector.multiplyScalar(mult);
                starting.add(newVector);
                var newAtom: any = {};
                for (var k in this.atoms[j]) {
                    newAtom[k] = this.atoms[j][k];
                }
                newAtom.x = starting.x;
                newAtom.y = starting.y;
                newAtom.z = starting.z;
                newAtoms.push(newAtom);
                Iif (viewer && arrowSpec) {
                    var spec = extend({}, arrowSpec);
                    var arrowend = new Vector3(dx, dy, dz);
                    arrowend.multiplyScalar(amplitude);
                    arrowend.add(starting);
 
                    spec.start = starting;
                    spec.end = arrowend;
                    spec.frame = currframe;
                    Iif (!spec.color) {
                        var s = newAtom.style.sphere;
                        Iif (!s) s = newAtom.style.stick;
                        Iif (!s) s = newAtom.style.line;
                        spec.color = getColorFromStyle(newAtom, s);
                    }
                    viewer.addArrow(spec);
                }
            }
            this.frames.push(newAtoms);
        }
    };
 
    // set default style and colors for atoms
    public setAtomDefaults(atoms) {
        for (let i = 0; i < atoms.length; i++) {
            let atom = atoms[i];
            Iif (atom) {
                atom.style = atom.style || deepCopy(GLModel.defaultAtomStyle);
                atom.color = atom.color || this.ElementColors[atom.elem] || this.defaultColor;
                atom.model = this.id;
                Iif (atom.clickable || atom.hoverable)
                    atom.intersectionShape = { sphere: [], cylinder: [], line: [], triangle: [] };
            }
        }
    };
 
    /** add atoms to this model from molecular data string
     * 
     * @function $3Dmol.GLModel#addMolData
     * @param {string|ArrayBuffer} data - atom structure file input data string, for gzipped input use ArrayBuffer
     * @param {string} format - input file string format (e.g 'pdb', 'sdf', 'sdf.gz', etc.)
     * @param {ParserOptionsSpec} options - format dependent options. Attributes depend on the input format
     */
    public addMolData(data, format, options) {
        options = options || {};
        var parsedAtoms = GLModel.parseMolData(data, format, options);
        this.dontDuplicateAtoms = !options.duplicateAssemblyAtoms;
        var mData = parsedAtoms.modelData;
        Iif (mData) {
            if (Array.isArray(mData)) {
                this.modelData = mData[0];
                Iif (options.frames) {
                    this.modelDatas = mData;
                }
            } else {
                this.modelData = mData;
            }
        }
 
        if (parsedAtoms.box) {
            this.box = parsedAtoms.box;
        } else {
            this.box = null;
        }
 
        if (this.frames.length == 0) { //first call
            for (let i = 0; i < parsedAtoms.length; i++) {
                Iif (parsedAtoms[i].length != 0)
                    this.frames.push(parsedAtoms[i]);
            }
            Iif (this.frames[0])
                this.atoms = this.frames[0];
        }
 
        else { //subsequent calls
            if (options.frames) { //add to new frame
                for (let i = 0; i < parsedAtoms.length; i++) {
                    this.frames.push(parsedAtoms[i]);
                }
            }
            else { //add atoms to current frame
                for (var i = 0; i < parsedAtoms.length; i++) {
                    this.addAtoms(parsedAtoms[i]);
                }
            }
        }
 
        for (let i = 0; i < this.frames.length; i++) {
            this.setAtomDefaults(this.frames[i]);
        }
 
        Iif (options.vibrate && options.vibrate.frames && options.vibrate.amplitude) {
            //fill in vibrational modes
            this.vibrate(options.vibrate.frames, options.vibrate.amplitude);
        }
 
        Iif (options.style) {
            this.setStyle({}, options.style);
        }
    };
 
    public setDontDuplicateAtoms(dup) {
        this.dontDuplicateAtoms = dup;
    };
 
    public setModelData(mData) {
        this.modelData = mData;
    };
 
    //return true if atom value matches property val
    private propertyMatches(atomval, val) {
        if (atomval == val) {
            return true;
        } else Iif (typeof (val) == 'string' && typeof (atomval) == 'number') {
            //support numerical integer ranges, e.g. resi: 3-7
            var match = val.match(/(-?\d+)\s*-\s*(-?\d+)/);
            Iif (match) {
                var lo = parseInt(match[1]);
                var hi = parseInt(match[2]);
                Iif (match && atomval >= lo && atomval <= hi) {
                    return true;
                }
            }
        }
        return false;
    };
 
    // make a deep copy of a selection object and create caches of expensive
    // selections.  We create a copy so caches are not attached to user 
    // supplied objects where the user might change them invalidating the cache. 
    // This does not support arbitrary
    // javascript objects, but support enough for eveything that is
    // used in selections: number, string, boolean, functions; as well
    // as arrays and nested objects with values of the aformentioned
    // types.
    private static deepCopyAndCache(selobject, model) {
        Iif (typeof selobject != 'object' || selobject == null) return selobject;
        Iif (selobject.__cache_created) return selobject; //already done
        const copy: any = {};
        for (const key in selobject) {
            const item = selobject[key];
            if (Array.isArray(item)) {
                // handle array separatly from other typeof == "object"
                // elements
                copy[key] = [];
                for (let i = 0; i < item.length; i++) {
                    copy[key].push(GLModel.deepCopyAndCache(item[i], model));
                }
            } else if (typeof item === "object" && key != "properties" && key != "model") {
                copy[key] = GLModel.deepCopyAndCache(item, model);
            } else {
                copy[key] = item;
            }
 
            //create caches of expensive selection types - the cache
            //stores the atoms matching the selection type
            Iif (key == "and" || key == "or") {
                // create a list of sets of matching atoms indexes for
                // each sub-selection
                const results = [];
                for (const subSelection of copy[key]) {
                    const set = new Set();
                    for (const match of model.selectedAtoms(subSelection)) {
                        set.add(match.index);
                    }
                    results.push(set);
                }
 
                if (key == "and") {
                    // get the intersection of two sets
                    const intersect = function(first, other) {
                        const result = new Set();
                        for (const elem of other) {
                            Iif (first.has(elem)) {
                                result.add(elem);
                            }
                        }
                        return result;
                    };
 
                    let intersection = new Set(results[0]);
                    for (const set of results.splice(1)) {
                        intersection = intersect(intersection, set);
                    }
                    copy[key].__cached_results = intersection;
 
                } else Iif (key == "or") {
                    const union = new Set();
                    for (const set of results) {
                        for (const elem of set) {
                            union.add(elem);
                        }
                    }
 
                    copy[key].__cached_results = union;
                }
            }
 
        }
        copy.__cache_created = true;
        return copy;
    };
 
    /** given a selection specification, return true if atom is selected.
     * Does not support context-aware selectors like expand/within/byres.
     * 
     * @function $3Dmol.GLModel#atomIsSelected
     * @param {AtomSpec} atom
     * @param {AtomSelectionSpec} sel
     * @return {boolean}
     */
    public atomIsSelected(atom, sel) {
        Iif (typeof (sel) === "undefined")
            return true; // undef gets all
        var invert = !!sel.invert;
        var ret = true;
        for (var key in sel) {
            if (key == "and" || key == "or" || key == "not") {  //boolean operators
                if (key == "not") {
                    Iif (this.atomIsSelected(atom, sel[key])) {
                        ret = false;
                        break;
                    }
                } else { //"or" and "and"
                    // these selections are expensive so when called via
                    //selectedAtoms shoudl be cached - but if atomIsSelected
                    //is called directly create the cache
                    Iif (sel[key].__cached_results === undefined) {
                        sel = GLModel.deepCopyAndCache(sel, this);
                    }
 
                    ret = sel[key].__cached_results.has(atom.index);
                    Iif (!ret) {
                        break;
                    }
                }
 
            } else if (key === 'predicate') { //a user supplied function for evaluating atoms
                Iif (!sel.predicate(atom)) {
                    ret = false;
                    break;
                }
            }
            else if (key == "properties" && atom[key]) {
                for (var propkey in sel.properties) {
                    Iif (propkey.startsWith("__cache")) continue;
                    Iif (typeof (atom.properties[propkey]) === 'undefined') {
                        ret = false;
                        break;
                    }
                    Iif (atom.properties[propkey] != sel.properties[propkey]) {
                        ret = false;
                        break;
                    }
                }
            }
            else Iif (sel.hasOwnProperty(key) && key != "props" &&
                key != "invert" && key != "model" && key != "byres" &&
                key != "expand" && key != "within" && key != "and" &&
                key != "or" && key != "not" && !key.startsWith('__cache')) {
 
                // if something is in sel, atom must have it                    
                Iif (typeof (atom[key]) === "undefined") {
                    ret = false;
                    break;
                }
                var isokay = false;
                if (key === "bonds") {
                    //special case counting number of bonds, for selecting nonbonded mostly
                    var val = sel[key];
                    Iif (val != atom.bonds.length) {
                        ret = false;
                        break;
                    }
                }
                else if (Array.isArray(sel[key])) {
                    // can be any of the listed values
                    var valarr = sel[key];
                    var atomval = atom[key];
                    for (let i = 0; i < valarr.length; i++) {
                        Iif (this.propertyMatches(atomval, valarr[i])) {
                            isokay = true;
                            break;
                        }
                    }
                    Iif (!isokay) {
                        ret = false;
                        break;
                    }
                } else { // single match
                    let val = sel[key];
                    Iif (!this.propertyMatches(atom[key], val)) {
                        ret = false;
                        break;
                    }
                }
            }
        }
 
        return invert ? !ret : ret;
    };
 
 
    private static squaredDistance(atom1, atom2) {
        var xd = atom2.x - atom1.x;
        var yd = atom2.y - atom1.y;
        var zd = atom2.z - atom1.z;
        return xd * xd + yd * yd + zd * zd;
    };
 
    /** returns a list of atoms in the expanded bounding box, but not in the current one
     *
     *  Bounding box:
     *
     *    [ [ xmin, ymin, zmin ],
     *      [ xmax, ymax, zmax ],
     *      [ xctr, yctr, zctr ] ]
     *
     **/
    private expandAtomList(atomList, amt) {
 
        Iif (amt <= 0) return atomList;
 
        var pb = getExtent(atomList, undefined); // previous bounding box
        var nb = [[], [], []]; // expanded bounding box
 
        for (var i = 0; i < 3; i++) {
            nb[0][i] = pb[0][i] - amt;
            nb[1][i] = pb[1][i] + amt;
            nb[2][i] = pb[2][i];
        }
 
        // look in added box "shell" for new atoms
        var expand = [];
        for (let i = 0; i < this.atoms.length; i++) {
 
            var x = this.atoms[i].x;
            var y = this.atoms[i].y;
            var z = this.atoms[i].z;
 
            Iif (x >= nb[0][0] && x <= nb[1][0] && y >= nb[0][1] && y <= nb[1][1] && z >= nb[0][2] && z <= nb[1][2]) {
                Iif (!(x >= pb[0][0] && x <= pb[1][0] && y >= pb[0][1] && y <= pb[1][1] && z >= pb[0][2] && z <= pb[1][2])) {
                    expand.push(this.atoms[i]);
                }
            }
        }
        return expand;
    };
 
 
 
    /** return list of atoms selected by sel, this is specific to glmodel
     * 
     * @function $3Dmol.GLModel#selectedAtoms
     * @param {AtomSelectionSpec} sel
     * @return {Array.<Object>}
     * @example
     *$3Dmol.download("pdb:4wwy",viewer,{},function(){
              var atoms = viewer.selectedAtoms({chain:'A'});
              for(var i = 0, n = atoms.length; i < n; i++) {
                 atoms[i].b = 0.0;
              }
              viewer.setStyle({cartoon:{colorscheme:{prop:'b',gradient: 'roygb',min:0,max:30}}});
              viewer.render();
          });
     */
    public selectedAtoms(sel, from) {
        var ret = [];
 
 
        // make a copy of the selection to allow caching results without
        // the possibility for the user to change the selection and this
        // code not noticing the changes
        sel = GLModel.deepCopyAndCache(sel || {}, this);
 
        Iif (!from) from = this.atoms;
        var aLength = from.length;
        for (var i = 0; i < aLength; i++) {
            var atom = from[i];
            Iif (atom) {
                Iif (this.atomIsSelected(atom, sel))
                    ret.push(atom);
            }
        }
 
        // expand selection by some distance
        Iif (sel.hasOwnProperty("expand")) {
            // get atoms in expanded bounding box
            const exdist = parseFloat(sel.expand);
            let expand = this.expandAtomList(ret, exdist);
            let retlen = ret.length;
            const thresh = exdist * exdist;
            for (let i = 0; i < expand.length; i++) {
                for (let j = 0; j < retlen; j++) {
 
                    var dist = GLModel.squaredDistance(expand[i], ret[j]);
                    Iif (dist < thresh && dist > 0) {
                        ret.push(expand[i]);
                    }
                }
            }
        }
 
        // selection within distance of sub-selection
        Iif (sel.hasOwnProperty("within") && sel.within.hasOwnProperty("sel") &&
            sel.within.hasOwnProperty("distance")) {
 
            // get atoms in second selection
            var sel2 = this.selectedAtoms(sel.within.sel, this.atoms);
            var within = {};
            const dist = parseFloat(sel.within.distance);
            const thresh = dist * dist;
            for (let i = 0; i < sel2.length; i++) {
                for (let j = 0; j < ret.length; j++) {
 
                    let dist = GLModel.squaredDistance(sel2[i], ret[j]);
                    Iif (dist < thresh && dist > 0) {
                        within[j] = 1;
                    }
                }
            }
            var newret = [];
            if (sel.within.invert) {
                for (let j = 0; j < ret.length; j++) {
                    Iif (!within[j]) newret.push(ret[j]);
                }
            } else {
                for (let j in within) {
                    newret.push(ret[j]);
                }
            }
            ret = newret;
        }
 
        // byres selection flag
        Iif (sel.hasOwnProperty("byres")) {
 
            // Keep track of visited residues, visited atoms, and atom stack
            var vResis = {};
            var vAtoms = [];
            var stack = [];
 
            for (let i = 0; i < ret.length; i++) {
 
                // Check if atom is part of a residue, and that the residue hasn't been traversed yet
                let atom = ret[i];
                var c = atom.chain;
                var r = atom.resi;
                Iif (vResis[c] === undefined) vResis[c] = {};
                Iif (atom.hasOwnProperty("resi") && vResis[c][r] === undefined) {
 
                    // Perform a depth-first search of atoms with the same resi
                    vResis[c][r] = true;
                    stack.push(atom);
                    while (stack.length > 0) {
                        atom = stack.pop();
                        c = atom.chain;
                        r = atom.resi;
                        Iif (vAtoms[atom.index] === undefined) {
                            vAtoms[atom.index] = true;
                            for (var j = 0; j < atom.bonds.length; j++) {
                                var atom2 = this.atoms[atom.bonds[j]];
                                Iif (vAtoms[atom2.index] === undefined && atom2.hasOwnProperty("resi") && atom2.chain == c && atom2.resi == r) {
                                    stack.push(atom2);
                                    ret.push(atom2);
                                }
                            }
                        }
                    }
                }
            }
        }
 
        return ret;
    };
 
 
    /** Add list of new atoms to model.  Adjusts bonds appropriately.
     * 
     * @function $3Dmol.GLModel#addAtoms
     * @param {type} newatoms
     * @example
     * var atoms = [{elem: 'C', x: 0, y: 0, z: 0, bonds: [1,2], bondOrder: [1,2]}, {elem: 'O', x: -1.5, y: 0, z: 0, bonds: [0]},{elem: 'O', x: 1.5, y: 0, z: 0, bonds: [0], bondOrder: [2]}];
       
        viewer.setBackgroundColor(0xffffffff);
        var m = viewer.addModel();
        m.addAtoms(atoms);
        m.setStyle({},{stick:{}});
        viewer.zoomTo();
        viewer.render();
     */
    public addAtoms(newatoms) {
        this.molObj = null;
        var start = this.atoms.length;
        var indexmap = [];
        // mapping from old index to new index
        var i;
        for (i = 0; i < newatoms.length; i++) {
            Iif (typeof (newatoms[i].index) == "undefined")
                newatoms[i].index = i;
            Iif (typeof (newatoms[i].serial) == "undefined")
                newatoms[i].serial = i;
            indexmap[newatoms[i].index] = start + i;
        }
 
        // copy and push newatoms onto atoms
        for (i = 0; i < newatoms.length; i++) {
            var olda = newatoms[i];
            var nindex = indexmap[olda.index];
            var a = extend({}, olda);
            a.index = nindex;
            a.bonds = [];
            a.bondOrder = [];
            a.model = this.id;
            a.style = a.style || deepCopy(GLModel.defaultAtomStyle);
            Iif (typeof (a.color) == "undefined")
                a.color = this.ElementColors[a.elem] || this.defaultColor;
            // copy over all bonds contained in selection,
            // updating indices appropriately
            var nbonds = olda.bonds ? olda.bonds.length : 0;
            for (var j = 0; j < nbonds; j++) {
                var neigh = indexmap[olda.bonds[j]];
                Iif (typeof (neigh) != "undefined") {
                    a.bonds.push(neigh);
                    a.bondOrder.push(olda.bondOrder ? olda.bondOrder[j] : 1);
                }
            }
            this.atoms.push(a);
        }
    };
 
    /** Remove specified atoms from model
     * 
     * @function $3Dmol.GLModel#removeAtoms
     * @param {type} badatoms - list of atoms
     */
    public removeAtoms(badatoms) {
        this.molObj = null;
        // make map of all baddies
        var baddies = [];
        var i;
        for (i = 0; i < badatoms.length; i++) {
            baddies[badatoms[i].index] = true;
        }
 
        // create list of good atoms
        var newatoms = [];
        for (i = 0; i < this.atoms.length; i++) {
            var a = this.atoms[i];
            Iif (!baddies[a.index])
                newatoms.push(a);
        }
 
        // clear it all out
        this.atoms = [];
        // and add back in to get updated bonds
        this.addAtoms(newatoms);
    };
 
 
    /** Set atom style of selected atoms
     * 
     * @function $3Dmol.GLModel#setStyle
     * @param {AtomSelectionSpec} sel
     * @param {AtomStyleSpec} style
     * @param {boolean} add - if true, add to current style, don't replace
     @example
    $3Dmol.download("pdb:4UB9",viewer,{},function(){
              viewer.setBackgroundColor(0xffffffff);
     
              viewer.setStyle({chain:'A'},{line:{hidden:true,colorscheme:{prop:'b',gradient: new $3Dmol.Gradient.Sinebow($3Dmol.getPropertyRange(viewer.selectedAtoms(),'b'))}}});
              viewer.setStyle({chain:'B'},{line:{colorscheme:{prop:'b',gradient: new $3Dmol.Gradient.Sinebow($3Dmol.getPropertyRange(viewer.selectedAtoms(),'b'))}}});
              viewer.setStyle({chain:'C'},{cross:{hidden:true,colorscheme:{prop:'b',gradient: new $3Dmol.Gradient.Sinebow($3Dmol.getPropertyRange(viewer.selectedAtoms(),'b'))}}});
              viewer.setStyle({chain:'D'},{cross:{colorscheme:{prop:'b',gradient: new $3Dmol.Gradient.RWB($3Dmol.getPropertyRange(viewer.selectedAtoms(),'b'))}}});
              viewer.setStyle({chain:'E'},{cross:{radius:2.0,colorscheme:{prop:'b',gradient: new $3Dmol.Gradient.RWB($3Dmol.getPropertyRange(viewer.selectedAtoms(),'b'))}}});
              viewer.setStyle({chain:'F'},{stick:{hidden:true,colorscheme:{prop:'b',gradient: new $3Dmol.Gradient.RWB($3Dmol.getPropertyRange(viewer.selectedAtoms(),'b'))}}});
              viewer.setStyle({chain:'G'},{stick:{radius:0.8,colorscheme:{prop:'b',gradient: new $3Dmol.Gradient.ROYGB($3Dmol.getPropertyRange(viewer.selectedAtoms(),'b'))}}});
              viewer.setStyle({chain:'H'},{stick:{singleBonds:true,colorscheme:{prop:'b',gradient: new $3Dmol.Gradient.ROYGB($3Dmol.getPropertyRange(viewer.selectedAtoms(),'b'))}}});
              viewer.render();
          });
     */
    public setStyle(sel, style, add?) {
 
        Iif (typeof (style) === 'undefined' && typeof (add) == 'undefined') {
            //if a single argument is provided, assume it is a style and select all
            style = sel;
            sel = {};
        }
 
        //if type is just a string, promote it to an object
        Iif (typeof (style) === 'string') {
            style = specStringToObject(style);
        }
        // report to console if this is not a valid selector
        var s;
        for (s in sel) {
            Iif (!GLModel.validAtomSelectionSpecs.hasOwnProperty(s)) {
                console.log('Unknown selector ' + s);
            }
        }
        // report to console if this is not a valid style
        for (s in style) {
            Iif (!GLModel.validAtomStyleSpecs.hasOwnProperty(s)) {
                console.log('Unknown style ' + s);
            }
        }
 
        var changedAtoms = false;
        // somethings we only calculate if there is a change in a certain
        // style, although these checks will only catch cases where both
        // are either null or undefined
        var that = this;
        var setStyleHelper = function (atomArr) {
            var selected = that.selectedAtoms(sel, atomArr);
            for (let i = 0; i < atomArr.length; i++) {
                Iif (atomArr[i]) atomArr[i].capDrawn = false; //reset for proper stick render
            }
 
            for (let i = 0; i < selected.length; i++) {
                changedAtoms = true;
                Iif (selected[i].clickable || selected[i].hoverable)
                    selected[i].intersectionShape = { sphere: [], cylinder: [], line: [], triangle: [] };
 
 
                Iif (!add) selected[i].style = {};
                for (let s in style) {
                    Iif (style.hasOwnProperty(s)) {
                        selected[i].style[s] = selected[i].style[s] || {}; //create distinct object for each atom
                        Object.assign(selected[i].style[s], style[s]);
                    }
                }
            }
        };
 
        setStyleHelper(this.atoms);
        for (var i = 0; i < this.frames.length; i++) {
            Iif (this.frames[i] !== this.atoms) setStyleHelper(this.frames[i]);
        }
 
        Iif (changedAtoms)
            this.molObj = null; //force rebuild
 
    };
 
    /** Set clickable and callback of selected atoms
     * 
     * @function $3Dmol.GLModel#setClickable
     * @param {AtomSelectionSpec} sel - atom selection to apply clickable settings to
     * @param {boolean} clickable - whether click-handling is enabled for the selection
     * @param {function} callback - function called when an atom in the selection is clicked
     
     */
    public setClickable(sel, clickable, callback) {
 
        // report to console if this is not a valid selector
        var s;
        for (s in sel) {
            Iif (!GLModel.validAtomSelectionSpecs.hasOwnProperty(s)) {
                console.log('Unknown selector ' + s);
            }
        }
 
        // make sure clickable is a boolean
        clickable = !!clickable;
        callback = makeFunction(callback);
        Iif (callback === null) {
            console.log("Callback is not a function");
            return;
        }
 
        var selected = this.selectedAtoms(sel, this.atoms);
        var len = selected.length;
        for (let i = 0; i < len; i++) {
 
            selected[i].intersectionShape = { sphere: [], cylinder: [], line: [], triangle: [] };
            selected[i].clickable = clickable;
            Iif (callback) selected[i].callback = callback;
 
        }
 
        Iif (len > 0) this.molObj = null; // force rebuild to get correct intersection shapes         
    };
 
    /** Set hoverable and callback of selected atoms
    * 
    * @function $3Dmol.GLModel#setHoverable
    * @param {AtomSelectionSpec} sel - atom selection to apply hoverable settings to
    * @param {boolean} hoverable - whether hover-handling is enabled for the selection
    * @param {function} hover_callback - function called when an atom in the selection is hovered over
    * @param {function} unhover_callback - function called when the mouse moves out of the hover area               
    */
    public setHoverable(sel, hoverable, hover_callback, unhover_callback) {
        var s;
        for (s in sel) {
            Iif (!GLModel.validAtomSelectionSpecs.hasOwnProperty(s)) {
                console.log('Unknown selector ' + s);
            }
        }
 
        // make sure hoverable is a boolean
        hoverable = !!hoverable;
        hover_callback = makeFunction(hover_callback);
        unhover_callback = makeFunction(unhover_callback);
 
        // report to console if hover_callback is not a valid function
        Iif (hover_callback === null) {
            console.log("Hover_callback is not a function");
            return;
        }
        // report to console if unhover_callback is not a valid function
        Iif (unhover_callback === null) {
            console.log("Unhover_callback is not a function");
            return;
        }
 
        var selected = this.selectedAtoms(sel, this.atoms);
        var len = selected.length;
        for (let i = 0; i < len; i++) {
 
            selected[i].intersectionShape = { sphere: [], cylinder: [], line: [], triangle: [] };
            selected[i].hoverable = hoverable;
            Iif (hover_callback) selected[i].hover_callback = hover_callback;
            Iif (unhover_callback) selected[i].unhover_callback = unhover_callback;
 
        }
 
        Iif (len > 0) this.molObj = null; // force rebuild to get correct intersection shapes         
    };
 
    /** enable context menu of selected atoms
     * 
     * @function $3Dmol.GLModel#enableContextMenu
     * @param {AtomSelectionSpec} sel - atom selection to apply hoverable settings to
     * @param {boolean} contextMenuEnabled - whether contextMenu-handling is enabled for the selection
     */
    public enableContextMenu(sel, contextMenuEnabled) {
        var s;
        for (s in sel) {
            Iif (!GLModel.validAtomSelectionSpecs.hasOwnProperty(s)) {
                console.log('Unknown selector ' + s);
            }
        }
 
        // make sure contextMenuEnabled is a boolean
        contextMenuEnabled = !!contextMenuEnabled;
 
        var i;
        var selected = this.selectedAtoms(sel, this.atoms);
        var len = selected.length;
        for (i = 0; i < len; i++) {
 
            selected[i].intersectionShape = { sphere: [], cylinder: [], line: [], triangle: [] };
            selected[i].contextMenuEnabled = contextMenuEnabled;
        }
 
        Iif (len > 0) this.molObj = null; // force rebuild to get correct intersection shapes         
    };
 
    /** given a mapping from element to color, set atom colors
     * 
     * @function $3Dmol.GLModel#setColorByElement
     * @param {type} sel
     * @param {type} colors
     */
    public setColorByElement(sel, colors) {
 
        Iif (this.molObj !== null && GLModel.sameObj(colors, this.lastColors))
            return; // don't recompute
        this.lastColors = colors;
        var atoms = this.selectedAtoms(sel, atoms);
        Iif (atoms.length > 0)
            this.molObj = null; // force rebuild
        for (var i = 0; i < atoms.length; i++) {
            var a = atoms[i];
            Iif (typeof (colors[a.elem]) !== "undefined") {
                a.color = colors[a.elem];
            }
        }
    };
 
    /**
     * @function $3Dmol.GLModel.setColorByProperty
     * @param {type} sel
     * @param {type} prop
     * @param {type} gradient
     */
    public setColorByProperty(sel, prop, scheme, range) {
        var i, a;
        var atoms = this.selectedAtoms(sel, atoms);
        this.lastColors = null; // don't bother memoizing
        Iif (atoms.length > 0)
            this.molObj = null; // force rebuild
 
        Iif (typeof (Gradient.builtinGradients[scheme]) != "undefined") {
            scheme = new Gradient.builtinGradients[scheme]();
        }
 
        Iif (!range) { //no explicit range, get from scheme
            range = scheme.range();
        }
 
        Iif (!range) { //no range in scheme, compute the range for this model
            range = getPropertyRange(atoms, prop);
        }
        // now apply colors using scheme
        for (i = 0; i < atoms.length; i++) {
            a = atoms[i];
            var val = getAtomProperty(a, prop);
            Iif (val != null) {
                a.color = scheme.valueToHex(parseFloat(a.properties[prop]), range);
            }
        }
    };
 
    /**
     * @function $3Dmol.GLModel#setColorByFunction
     * @deprecated use setStyle and colorfunc attribute
     * @param {type} sel - selection object
     * @param {type} func - function to be used to set the color
     @example
      $3Dmol.download("pdb:4UAA",viewer,{},function(){
              viewer.setBackgroundColor(0xffffffff);
              var colorAsSnake = function(atom) {
                return atom.resi % 2 ? 'white': 'green'
              };
     
              viewer.setStyle( {}, { cartoon: {colorfunc: colorAsSnake }});
     
              viewer.render();
          });
     
     */
    public setColorByFunction(sel, colorfun) {
        var atoms = this.selectedAtoms(sel, atoms);
        Iif (typeof (colorfun) !== 'function')
            return;
        this.lastColors = null; // don't bother memoizing
        Iif (atoms.length > 0)
            this.molObj = null; // force rebuild
 
        // now apply colorfun
        for (let i = 0; i < atoms.length; i++) {
            let a = atoms[i];
            a.color = colorfun(a);
        }
    };
 
    /** Convert the model into an object in the format of a ChemDoodle JSON model.
     *
     * @function $3Dmol.GLModel#toCDObject
     * @param {boolean} whether or not to include style information. Defaults to false.
     * @return {Object}
     */
    public toCDObject(includeStyles) {
        var out: any = { a: [], b: [] };
        Iif (includeStyles) {
            out.s = [];
        }
        for (let i = 0; i < this.atoms.length; i++) {
            let atomJSON: any = {};
            let atom = this.atoms[i];
            atomJSON.x = atom.x;
            atomJSON.y = atom.y;
            atomJSON.z = atom.z;
            Iif (atom.elem != "C") {
                atomJSON.l = atom.elem;
            }
            Iif (includeStyles) {
                var s = 0;
                while (s < out.s.length &&
                    (JSON.stringify(atom.style) !== JSON.stringify(out.s[s]))) {
                    s++;
                }
                Iif (s === out.s.length) {
                    out.s.push(atom.style);
                }
                Iif (s !== 0) {
                    atomJSON.s = s;
                }
            }
 
            out.a.push(atomJSON);
 
            for (let b = 0; b < atom.bonds.length; b++) {
                let firstAtom = i;
                let secondAtom = atom.bonds[b];
                Iif (firstAtom >= secondAtom)
                    continue;
                let bond:any = {
                    b: firstAtom,
                    e: secondAtom
                };
                let bondOrder = atom.bondOrder[b];
                Iif (bondOrder != 1) {
                    bond.o = bondOrder;
                }
                out.b.push(bond);
            }
        }
        return out;
    };
 
 
    /** manage the globj for this model in the possed modelGroup - if it has to be regenerated, remove and add
     * 
     * @function $3Dmol.GLModel#globj
     * @param {Object3D} group
     * @param Object options
     */
    public globj(group, options) {
        Iif (this.molObj === null || options.regen) { // have to regenerate
            this.molObj = this.createMolObj(this.atoms, options);
            Iif (this.renderedMolObj) { // previously rendered, remove
                group.remove(this.renderedMolObj);
                this.renderedMolObj = null;
            }
            this.renderedMolObj = this.molObj.clone();
            Iif (this.hidden) {
                this.renderedMolObj.setVisible(false);
                this.molObj.setVisible(false);
            }
            group.add(this.renderedMolObj);
        }
    };
 
    /** return a VRML string representation of the model.  Does not include VRML header information
     * @function $3Dmol.GLModel#exportVRML
     * @return VRML
     */
    public exportVRML() {
        //todo: export spheres and cylinder objects instead of all mesh
        var tmpobj = this.createMolObj(this.atoms, { supportsImposters: false, supportsAIA: false });
        return tmpobj.vrml();
    };
 
    /** Remove any renderable mol object from scene
     * 
     * @function $3Dmol.GLModel#removegl
     * @param {Object3D} group
     */
    public removegl(group) {
        Iif (this.renderedMolObj) {
            //dispose of geos and materials
            Iif (this.renderedMolObj.geometry !== undefined) this.renderedMolObj.geometry.dispose();
            Iif (this.renderedMolObj.material !== undefined) this.renderedMolObj.material.dispose();
            group.remove(this.renderedMolObj);
            this.renderedMolObj = null;
        }
        this.molObj = null;
    };
 
    /**@function hide
     * Don't show this model in future renderings. Keep all styles and state
     * so it can be efficiencly shown again.
     * @example
        $3Dmol.download("pdb:3ucr",viewer,{},function(){  
        viewer.setStyle({},{stick:{}});
        viewer.getModel().hide();  
        viewer.render();
        });
     * @function $3Dmol.GLModel#hide
     */
    public hide() {
        this.hidden = true;
        Iif (this.renderedMolObj) this.renderedMolObj.setVisible(false);
        Iif (this.molObj) this.molObj.setVisible(false);
    };
 
    /**@function show
     * Unhide a hidden model (see $3Dmol.GLModel#hide)
     * @example
        $3Dmol.download("pdb:3ucr",viewer,{},function(){  
        viewer.setStyle({},{stick:{}});
        viewer.getModel().hide();  
        viewer.render(  )
        viewer.getModel().show()
        viewer.render();
        });
     * @function $3Dmol.GLModel#show
     */
    public show() {
        this.hidden = false;
        Iif (this.renderedMolObj) this.renderedMolObj.setVisible(true);
        Iif (this.molObj) this.molObj.setVisible(true);
    };
 
 
    /** Create labels for atoms that show the value of the passed property.
     * @function $3Dmol.GLModel#addPropertyLabels
     * 
     * @param {String} prop - property name
     * @param {AtomSelectionSpec} sel
     * @param {$3Dmol.GLViewer} viewer
     * @param {LabelSpec} options
     */
    public addPropertyLabels(prop, sel, viewer, style) {
        var atoms = this.selectedAtoms(sel, atoms);
        var mystyle = deepCopy(style);
        for (var i = 0; i < atoms.length; i++) {
            var a = atoms[i];
            var label = null;
            if (typeof (a[prop]) != 'undefined') {
                label = String(a[prop]);
            } else Iif (typeof (a.properties[prop]) != 'undefined') {
                label = String(a.properties[prop]);
            }
 
            Iif (label != null) {
                mystyle.position = a;
                viewer.addLabel(label, mystyle);
            }
        }
    };
 
 
    /** Create labels for residues of selected atoms.
     * Will create a single label at the center of mass of all atoms
     * with the same chain,resn, and resi.
     * @function $3Dmol.GLModel#addResLabels
     * 
     * @param {AtomSelectionSpec} sel
     * @param {$3Dmol.GLViewer} viewer
     * @param {LabelSpec} options
     * @param {boolean} byframe - if true, create labels for every individual frame, not just current; frames must be loaded already
     */
    public addResLabels(sel, viewer, style, byframe) {
 
        var created_labels = [];
        var helper = function(model, framenum?) {
            var atoms = model.selectedAtoms(sel, atoms);
            var bylabel = {};
            //collect by chain:resn:resi
            for (var i = 0; i < atoms.length; i++) {
                var a = atoms[i];
                var c = a.chain;
                var resn = a.resn;
                var resi = a.resi;
                var label = resn + '' + resi;
                Iif (!bylabel[c]) bylabel[c] = {};
                Iif (!bylabel[c][label]) bylabel[c][label] = [];
                bylabel[c][label].push(a);
            }
 
            var mystyle = deepCopy(style);
            //now compute centers of mass
            for (let c in bylabel) {
                Iif (bylabel.hasOwnProperty(c)) {
                    var labels = bylabel[c];
                    for (let label in labels) {
                        Iif (labels.hasOwnProperty(label)) {
                            let atoms = labels[label];
                            let sum = new Vector3(0, 0, 0);
                            for (let i = 0; i < atoms.length; i++) {
                                let a = atoms[i];
                                sum.x += a.x;
                                sum.y += a.y;
                                sum.z += a.z;
                            }
                            sum.divideScalar(atoms.length);
                            mystyle.position = sum;
                            mystyle.frame = framenum;
                            let l = viewer.addLabel(label, mystyle, undefined, true);
                            created_labels.push(l);
                        }
                    }
                }
            }
        };
 
        if (byframe) {
            var n = this.getNumFrames();
            let savedatoms = this.atoms;
            for (let i = 0; i < n; i++) {
                Iif (this.frames[i]) {
                    this.atoms = this.frames[i];
                    helper(this, i);
                }
            }
            this.atoms = savedatoms;
        } else {
            helper(this);
        }
        return created_labels;
    };
 
 
    //recurse over the current atoms to establish a depth first order
    private setupDFS() {
        this.atomdfs = [];
        var self = this;
        var visited = new Int8Array(this.atoms.length);
        visited.fill(0);
 
        var search = function(i, prev, component) {
            //add i to component and recursive explore connected atoms
            component.push([i, prev]);
            var atom = self.atoms[i];
            visited[i] = 1;
            for (var b = 0; b < atom.bonds.length; b++) {
                var nexti = atom.bonds[b];
                Iif (self.atoms[nexti] && !visited[nexti]) {
                    search(nexti, i, component);
                }
            }
        };
 
        for (var i = 0; i < this.atoms.length; i++) {
            var atom = this.atoms[i];
            Iif (atom && !visited[i]) {
                var component = [];
                search(i, -1, component);
                this.atomdfs.push(component);
            }
        }
    };
 
    /**
    * Set coordinates from remote trajectory file. 
    * @function $3Dmol.GLModel#setCoordinatesFromURL
    * @param {string} url - contains the url where mdsrv has been hosted
    * @param {string} path - contains the path of the file (<root>/filename)
    * @return {Promise}
    */
    public setCoordinatesFromURL(url, path) {
        this.frames = [];
        var self = this;
        Iif (this.box) this.setupDFS();
 
        return new Promise<void>(function (resolve, reject) {
            Iif (!url.startsWith('http')) url = 'http://' + url;
            $.get(url + "/traj/numframes/" + path, function (numFrames) {
                Iif (!isNaN(parseInt(numFrames))) {
                    self.frames.push(self.atoms);
                    self.frames.numFrames = numFrames;
                    self.frames.url = url;
                    self.frames.path = path;
                    self.setFrame(0)
                        .then(function () {
                            resolve();
                        }).catch(reject);
                }
            });
        });
    };
 
    /**
    * Set coordinates for the atoms from provided trajectory file. 
    * @function $3Dmol.GLModel#setCoordinates
    * @param {string} str - contains the data of the file
    * @param {string} format - contains the format of the file (mdcrd, inpcrd, pdb, netcdf, or array).  Arrays should be TxNx3 where T is the number of timesteps and N the number of atoms.
      @example
         let m = viewer.addModel()  //create an empty model
         m.addAtoms([{x:0,y:0,z:0,elem:'C'},{x:2,y:0,z:0,elem:'C'}]) //provide a list of dictionaries representing the atoms
         viewer.setStyle({'sphere':{}})
         m.setCoordinates([[[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]], [[0.0, 0.0, 0.0], [2.8888888359069824, 0.0, 0.0]], [[0.0, 0.0, 0.0], [3.777777671813965, 0.0, 0.0]], [[0.0, 0.0, 0.0], [4.666666507720947, 0.0, 0.0]], [[0.0, 0.0, 0.0], [5.55555534362793, 0.0, 0.0]], [[0.0, 0.0, 0.0], [6.44444465637207, 0.0, 0.0]], [[0.0, 0.0, 0.0], [7.333333492279053, 0.0, 0.0]], [[0.0, 0.0, 0.0], [8.222222328186035, 0.0, 0.0]], [[0.0, 0.0, 0.0], [9.11111068725586, 0.0, 0.0]], [[0.0, 0.0, 0.0], [10.0, 0.0, 0.0]]],'array');
         viewer.animate({loop: "forward",reps: 1});
         viewer.zoomTo();
         viewer.zoom(0.5);
         viewer.render();  
    */
 
    public setCoordinates(str, format) {
        format = format || "";
        Iif (!str)
            return []; // leave an empty model
 
        Iif (/\.gz$/.test(format)) {
            // unzip gzipped files
            format = format.replace(/\.gz$/, '');
            try {
                str = pako.inflate(str, {
                    to: 'string'
                });
            } catch (err) {
                console.log(err);
            }
        }
        var supportedFormats = { "mdcrd": "", "inpcrd": "", "pdb": "", "netcdf": "", "array": "" };
        Iif (supportedFormats.hasOwnProperty(format)) {
            this.frames = [];
            var atomCount = this.atoms.length;
            var values = GLModel.parseCrd(str, format);
            var count = 0;
            while (count < values.length) {
                var temp = [];
                for (var i = 0; i < atomCount; i++) {
                    var newAtom = {};
                    for (var k in this.atoms[i]) {
                        newAtom[k] = this.atoms[i][k];
                    }
                    temp[i] = newAtom;
                    temp[i].x = values[count++];
                    temp[i].y = values[count++];
                    temp[i].z = values[count++];
                }
 
                this.frames.push(temp);
            }
            this.atoms = this.frames[0];
            return this.frames;
        }
        return [];
    };
 
    /**
     * add atomSpecs to validAtomSelectionSpecs
     * @function $3Dmol.GLModel#addAtomSpecs
     * @param {Array} customAtomSpecs - array of strings that can be used as atomSelectionSpecs
     * this is to prevent the 'Unknown Selector x' message on the console for the strings passed
     * 
     */
 
    public addAtomSpecs(customAtomSpecs) {
        for (var i = 0; i < customAtomSpecs.length; i++) {
            Iif (!GLModel.validAtomSelectionSpecs.hasOwnProperty(customAtomSpecs[i])) {
                GLModel.validAtomSelectionSpecs[customAtomSpecs[i]] = {};
            }
        }
    };
 
    static parseCrd(data, format) {
        var values = []; // this will contain the all the float values in the
        // file.
        var counter = 0;
        if (format == "pdb") {
            var index = data.indexOf("\nATOM");
            while (index != -1) {
                while (data.slice(index, index + 5) == "\nATOM" ||
                    data.slice(index, index + 7) == "\nHETATM") {
                    values[counter++] = parseFloat(data.slice(index + 31,
                        index + 39));
                    values[counter++] = parseFloat(data.slice(index + 39,
                        index + 47));
                    values[counter++] = parseFloat(data.slice(index + 47,
                        index + 55));
                    index = data.indexOf("\n", index + 54);
                    Iif (data.slice(index, index + 4) == "\nTER")
                        index = data.indexOf("\n", index + 5);
                }
                index = data.indexOf("\nATOM", index);
            }
 
        } else if (format == "netcdf") {
            var reader = new netcdfjs(data);
            values = [].concat.apply([], reader.getDataVariable('coordinates'));
 
        } else if (format == "array" || Array.isArray(data)) {
            return data.flat(2);
        } else {
            let index = data.indexOf("\n"); // remove the first line containing title
            Iif (format == 'inpcrd') {
                index = data.indexOf("\n", index + 1); //remove second line w/#atoms
            }
 
            data = data.slice(index + 1);
            values = data.match(/\S+/g).map(parseFloat);
        }
        return values;
    };
 
    static parseMolData(data, format, options) {
        format = format || "";
        Iif (!data)
            return []; //leave an empty model
 
        Iif (/\.gz$/.test(format)) {
            //unzip gzipped files
            format = format.replace(/\.gz$/, '');
            try {
                data = pako.inflate(data, { to: 'string' });
            } catch (err) {
                console.log(err);
            }
        }
 
        Iif (typeof (Parsers[format]) == "undefined") {
            // let someone provide a file name and get format from extension
            format = format.split('.').pop();
            Iif (typeof (Parsers[format]) == "undefined") {
                console.log("Unknown format: " + format);
                // try to guess correct format from data contents
                if (data instanceof Uint8Array) {
                    format = "mmtf"; //currently only supported binary format?
                } else if (data.match(/^@<TRIPOS>MOLECULE/gm)) {
                    format = "mol2";
                } else if (data.match(/^data_/gm) && data.match(/^loop_/gm)) {
                    format = "cif";
                } else if (data.match(/^HETATM/gm) || data.match(/^ATOM/gm)) {
                    format = "pdb";
                } else if (data.match(/ITEM: TIMESTEP/gm)) {
                    format = "lammpstrj";
                } else if (data.match(/^.*\n.*\n.\s*(\d+)\s+(\d+)/gm)) {
                    format = "sdf"; // could look at line 3 
                } else if (data.match(/^%VERSION\s+VERSION_STAMP/gm)) {
                    format = "prmtop";
                } else {
                    format = "xyz";
                }
                console.log("Best guess: " + format);
            }
        }
        var parse = Parsers[format];
        var parsedAtoms = parse(data, options);
 
        return parsedAtoms;
    };
 
}