This file is indexed.

/usr/share/pyshared/pyx/normpath.py is in python-pyx 0.11.1-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
# -*- encoding: utf-8 -*-
#
#
# Copyright (C) 2002-2011 Jörg Lehmann <joergl@users.sourceforge.net>
# Copyright (C) 2003-2006 Michael Schindler <m-schindler@users.sourceforge.net>
# Copyright (C) 2002-2011 André Wobst <wobsta@users.sourceforge.net>
#
# This file is part of PyX (http://pyx.sourceforge.net/).
#
# PyX is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# PyX is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyX; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA

import math
import mathutils, path, trafo, unit
import bbox as bboxmodule


# use new style classes when possible
__metaclass__ = type

class _marker: pass

################################################################################

# specific exception for normpath-related problems
class NormpathException(Exception): pass

# invalid result marker
class _invalid:

    """invalid result marker class

    The following norm(sub)path(item) methods:
      - trafo
      - rotation
      - tangent_pt
      - tangent
      - curvature_pt
      - curvradius_pt
    return list of result values, which might contain the invalid instance
    defined below to signal points, where the result is undefined due to
    properties of the norm(sub)path(item). Accessing invalid leads to an
    NormpathException, but you can test the result values by "is invalid".
    """

    def invalid1(self):
        raise NormpathException("invalid result (the requested value is undefined due to path properties)")
    __str__ = __repr__ = __neg__ = invalid1

    def invalid2(self, other):
        self.invalid1()
    __cmp__ = __add__ = __iadd__ = __sub__ = __isub__ = __mul__ = __imul__ = __div__ = __truediv__ = __idiv__ = invalid2

invalid = _invalid()

################################################################################

# global epsilon (default precision of normsubpaths)
_epsilon = 1e-5
# minimal relative speed (abort condition for tangent information)
_minrelspeed = 1e-5

def set(epsilon=None, minrelspeed=None):
    global _epsilon
    global _minrelspeed
    if epsilon is not None:
        _epsilon = epsilon
    if minrelspeed is not None:
        _minrelspeed = minrelspeed


################################################################################
# normsubpathitems
################################################################################

class normsubpathitem:

    """element of a normalized sub path

    Various operations on normsubpathitems might be subject of
    approximitions. Those methods get the finite precision epsilon,
    which is the accuracy needed expressed as a length in pts.

    normsubpathitems should never be modified inplace, since references
    might be shared between several normsubpaths.
    """

    def arclen_pt(self, epsilon):
        """return arc length in pts"""
        pass

    def _arclentoparam_pt(self, lengths_pt, epsilon):
        """return a tuple of params and the total length arc length in pts"""
        pass

    def arclentoparam_pt(self, lengths_pt, epsilon):
        """return a tuple of params"""
        pass

    def at_pt(self, params):
        """return coordinates at params in pts"""
        pass

    def atbegin_pt(self):
        """return coordinates of first point in pts"""
        pass

    def atend_pt(self):
        """return coordinates of last point in pts"""
        pass

    def bbox(self):
        """return bounding box of normsubpathitem"""
        pass

    def cbox(self):
        """return control box of normsubpathitem

        The control box also fully encloses the normsubpathitem but in the case of a Bezier
        curve it is not the minimal box doing so. On the other hand, it is much faster
        to calculate.
        """
        pass

    def curvature_pt(self, params):
        """return the curvature at params in 1/pts

        The result contains the invalid instance at positions, where the
        curvature is undefined."""
        pass

    def curveradius_pt(self, params):
        """return the curvature radius at params in pts

        The curvature radius is the inverse of the curvature. Where the
        curvature is undefined, the invalid instance is returned. Note that
        this radius can be negative or positive, depending on the sign of the
        curvature."""
        pass

    def intersect(self, other, epsilon):
        """intersect self with other normsubpathitem"""
        pass

    def modifiedbegin_pt(self, x_pt, y_pt):
        """return a normsubpathitem with a modified beginning point"""
        pass

    def modifiedend_pt(self, x_pt, y_pt):
        """return a normsubpathitem with a modified end point"""
        pass

    def _paramtoarclen_pt(self, param, epsilon):
        """return a tuple of arc lengths and the total arc length in pts"""
        pass

    def pathitem(self):
        """return pathitem corresponding to normsubpathitem"""

    def reversed(self):
        """return reversed normsubpathitem"""
        pass

    def rotation(self, params):
        """return rotation trafos (i.e. trafos without translations) at params"""
        pass

    def segments(self, params):
        """return segments of the normsubpathitem

        The returned list of normsubpathitems for the segments between
        the params. params needs to contain at least two values.
        """
        pass

    def trafo(self, params):
        """return transformations at params"""

    def transformed(self, trafo):
        """return transformed normsubpathitem according to trafo"""
        pass

    def outputPS(self, file, writer):
        """write PS code corresponding to normsubpathitem to file"""
        pass

    def outputPDF(self, file, writer):
        """write PDF code corresponding to normsubpathitem to file"""
        pass


class normline_pt(normsubpathitem):

    """Straight line from (x0_pt, y0_pt) to (x1_pt, y1_pt) (coordinates in pts)"""

    __slots__ = "x0_pt", "y0_pt", "x1_pt", "y1_pt"

    def __init__(self, x0_pt, y0_pt, x1_pt, y1_pt):
        self.x0_pt = x0_pt
        self.y0_pt = y0_pt
        self.x1_pt = x1_pt
        self.y1_pt = y1_pt

    def __str__(self):
        return "normline_pt(%g, %g, %g, %g)" % (self.x0_pt, self.y0_pt, self.x1_pt, self.y1_pt)

    def _arclentoparam_pt(self, lengths_pt, epsilon):
        # do self.arclen_pt inplace for performance reasons
        l_pt = math.hypot(self.x0_pt-self.x1_pt, self.y0_pt-self.y1_pt)
        return [length_pt/l_pt for length_pt in lengths_pt], l_pt

    def arclentoparam_pt(self, lengths_pt, epsilon):
        """return a tuple of params"""
        return self._arclentoparam_pt(lengths_pt, epsilon)[0]

    def arclen_pt(self,  epsilon):
        return math.hypot(self.x0_pt-self.x1_pt, self.y0_pt-self.y1_pt)

    def at_pt(self, params):
        return [(self.x0_pt+(self.x1_pt-self.x0_pt)*t, self.y0_pt+(self.y1_pt-self.y0_pt)*t)
                for t in params]

    def atbegin_pt(self):
        return self.x0_pt, self.y0_pt

    def atend_pt(self):
        return self.x1_pt, self.y1_pt

    def bbox(self):
        return bboxmodule.bbox_pt(min(self.x0_pt, self.x1_pt), min(self.y0_pt, self.y1_pt),
                                  max(self.x0_pt, self.x1_pt), max(self.y0_pt, self.y1_pt))

    cbox = bbox

    def curvature_pt(self, params):
        return [0] * len(params)

    def curveradius_pt(self, params):
        return [invalid] * len(params)

    def intersect(self, other, epsilon):
        if isinstance(other, normline_pt):
            a_deltax_pt = self.x1_pt - self.x0_pt
            a_deltay_pt = self.y1_pt - self.y0_pt

            b_deltax_pt = other.x1_pt - other.x0_pt
            b_deltay_pt = other.y1_pt - other.y0_pt
            try:
                det = 1.0 / (b_deltax_pt * a_deltay_pt - b_deltay_pt * a_deltax_pt)
            except ArithmeticError:
                return []

            ba_deltax0_pt = other.x0_pt - self.x0_pt
            ba_deltay0_pt = other.y0_pt - self.y0_pt

            a_t = (b_deltax_pt * ba_deltay0_pt - b_deltay_pt * ba_deltax0_pt) * det
            b_t = (a_deltax_pt * ba_deltay0_pt - a_deltay_pt * ba_deltax0_pt) * det

            # check for intersections out of bound
            # TODO: we might allow for a small out of bound errors.
            if not (0<=a_t<=1 and 0<=b_t<=1):
                return []

            # return parameters of intersection
            return [(a_t, b_t)]
        else:
            return [(s_t, o_t) for o_t, s_t in other.intersect(self, epsilon)]

    def modifiedbegin_pt(self, x_pt, y_pt):
        return normline_pt(x_pt, y_pt, self.x1_pt, self.y1_pt)

    def modifiedend_pt(self, x_pt, y_pt):
        return normline_pt(self.x0_pt, self.y0_pt, x_pt, y_pt)

    def _paramtoarclen_pt(self, params, epsilon):
        totalarclen_pt = self.arclen_pt(epsilon)
        arclens_pt = [totalarclen_pt * param for param in params + [1]]
        return arclens_pt[:-1], arclens_pt[-1]

    def pathitem(self):
        return path.lineto_pt(self.x1_pt, self.y1_pt)

    def reversed(self):
        return normline_pt(self.x1_pt, self.y1_pt, self.x0_pt, self.y0_pt)

    def rotation(self, params):
        return [trafo.rotate(math.degrees(math.atan2(self.y1_pt-self.y0_pt, self.x1_pt-self.x0_pt)))]*len(params)

    def segments(self, params):
        if len(params) < 2:
            raise ValueError("at least two parameters needed in segments")
        result = []
        xl_pt = yl_pt = None
        for t in params:
            xr_pt = self.x0_pt + (self.x1_pt-self.x0_pt)*t
            yr_pt = self.y0_pt + (self.y1_pt-self.y0_pt)*t
            if xl_pt is not None:
                result.append(normline_pt(xl_pt, yl_pt, xr_pt, yr_pt))
            xl_pt = xr_pt
            yl_pt = yr_pt
        return result

    def trafo(self, params):
        rotate = trafo.rotate(math.degrees(math.atan2(self.y1_pt-self.y0_pt, self.x1_pt-self.x0_pt)))
        return [trafo.translate_pt(*at_pt) * rotate
                for param, at_pt in zip(params, self.at_pt(params))]

    def transformed(self, trafo):
        return normline_pt(*(trafo.apply_pt(self.x0_pt, self.y0_pt) + trafo.apply_pt(self.x1_pt, self.y1_pt)))

    def outputPS(self, file, writer):
        file.write("%g %g lineto\n" % (self.x1_pt, self.y1_pt))

    def outputPDF(self, file, writer):
        file.write("%f %f l\n" % (self.x1_pt, self.y1_pt))


class normcurve_pt(normsubpathitem):

    """Bezier curve with control points x0_pt, y0_pt, x1_pt, y1_pt, x2_pt, y2_pt, x3_pt, y3_pt (coordinates in pts)"""

    __slots__ = "x0_pt", "y0_pt", "x1_pt", "y1_pt", "x2_pt", "y2_pt", "x3_pt", "y3_pt"

    def __init__(self, x0_pt, y0_pt, x1_pt, y1_pt, x2_pt, y2_pt, x3_pt, y3_pt):
        self.x0_pt = x0_pt
        self.y0_pt = y0_pt
        self.x1_pt = x1_pt
        self.y1_pt = y1_pt
        self.x2_pt = x2_pt
        self.y2_pt = y2_pt
        self.x3_pt = x3_pt
        self.y3_pt = y3_pt

    def __str__(self):
        return "normcurve_pt(%g, %g, %g, %g, %g, %g, %g, %g)" % (self.x0_pt, self.y0_pt, self.x1_pt, self.y1_pt,
                                                                 self.x2_pt, self.y2_pt, self.x3_pt, self.y3_pt)

    def _midpointsplit(self, epsilon):
        """split curve into two parts

        Helper method to reduce the complexity of a problem by turning
        a normcurve_pt into several normline_pt segments. This method
        returns normcurve_pt instances only, when they are not yet straight
        enough to be replaceable by normcurve_pt instances. Thus a recursive
        midpointsplitting will turn a curve into line segments with the
        given precision epsilon.
        """

        # first, we have to calculate the  midpoints between adjacent
        # control points
        x01_pt = 0.5*(self.x0_pt + self.x1_pt)
        y01_pt = 0.5*(self.y0_pt + self.y1_pt)
        x12_pt = 0.5*(self.x1_pt + self.x2_pt)
        y12_pt = 0.5*(self.y1_pt + self.y2_pt)
        x23_pt = 0.5*(self.x2_pt + self.x3_pt)
        y23_pt = 0.5*(self.y2_pt + self.y3_pt)

        # In the next iterative step, we need the midpoints between 01 and 12
        # and between 12 and 23
        x01_12_pt = 0.5*(x01_pt + x12_pt)
        y01_12_pt = 0.5*(y01_pt + y12_pt)
        x12_23_pt = 0.5*(x12_pt + x23_pt)
        y12_23_pt = 0.5*(y12_pt + y23_pt)

        # Finally the midpoint is given by
        xmidpoint_pt = 0.5*(x01_12_pt + x12_23_pt)
        ymidpoint_pt = 0.5*(y01_12_pt + y12_23_pt)

        # Before returning the normcurves we check whether we can
        # replace them by normlines within an error of epsilon pts.
        # The maximal error value is given by the modulus of the
        # difference between the length of the control polygon
        # (i.e. |P1-P0|+|P2-P1|+|P3-P2|), which consitutes an upper
        # bound for the length, and the length of the straight line
        # between start and end point of the normcurve (i.e. |P3-P1|),
        # which represents a lower bound.
        l0_pt = math.hypot(xmidpoint_pt - self.x0_pt, ymidpoint_pt - self.y0_pt)
        l1_pt = math.hypot(x01_pt - self.x0_pt, y01_pt - self.y0_pt)
        l2_pt = math.hypot(x01_12_pt - x01_pt, y01_12_pt - y01_pt)
        l3_pt = math.hypot(xmidpoint_pt - x01_12_pt, ymidpoint_pt - y01_12_pt)
        if l1_pt+l2_pt+l3_pt-l0_pt < epsilon:
            a = _leftnormline_pt(self.x0_pt, self.y0_pt, xmidpoint_pt, ymidpoint_pt, l1_pt, l2_pt, l3_pt)
        else:
            a = _leftnormcurve_pt(self.x0_pt, self.y0_pt,
                                  x01_pt, y01_pt,
                                  x01_12_pt, y01_12_pt,
                                  xmidpoint_pt, ymidpoint_pt)

        l0_pt = math.hypot(self.x3_pt - xmidpoint_pt, self.y3_pt - ymidpoint_pt)
        l1_pt = math.hypot(x12_23_pt - xmidpoint_pt, y12_23_pt - ymidpoint_pt)
        l2_pt = math.hypot(x23_pt - x12_23_pt, y23_pt - y12_23_pt)
        l3_pt = math.hypot(self.x3_pt - x23_pt, self.y3_pt - y23_pt)
        if l1_pt+l2_pt+l3_pt-l0_pt < epsilon:
            b = _rightnormline_pt(xmidpoint_pt, ymidpoint_pt, self.x3_pt, self.y3_pt, l1_pt, l2_pt, l3_pt)
        else:
            b = _rightnormcurve_pt(xmidpoint_pt, ymidpoint_pt,
                                   x12_23_pt, y12_23_pt,
                                   x23_pt, y23_pt,
                                   self.x3_pt, self.y3_pt)

        return a, b

    def _arclentoparam_pt(self, lengths_pt, epsilon):
        a, b = self._midpointsplit(epsilon)
        params_a, arclen_a_pt = a._arclentoparam_pt(lengths_pt, epsilon)
        params_b, arclen_b_pt = b._arclentoparam_pt([length_pt - arclen_a_pt for length_pt in lengths_pt], epsilon)
        params = []
        for param_a, param_b, length_pt in zip(params_a, params_b, lengths_pt):
            if length_pt > arclen_a_pt:
                params.append(b.subparamtoparam(param_b))
            else:
                params.append(a.subparamtoparam(param_a))
        return params, arclen_a_pt + arclen_b_pt

    def arclentoparam_pt(self, lengths_pt, epsilon):
        """return a tuple of params"""
        return self._arclentoparam_pt(lengths_pt, epsilon)[0]

    def arclen_pt(self, epsilon):
        a, b = self._midpointsplit(epsilon)
        return a.arclen_pt(epsilon) + b.arclen_pt(epsilon)

    def at_pt(self, params):
        return [( (-self.x0_pt+3*self.x1_pt-3*self.x2_pt+self.x3_pt)*t*t*t +
                  (3*self.x0_pt-6*self.x1_pt+3*self.x2_pt          )*t*t +
                  (-3*self.x0_pt+3*self.x1_pt                      )*t +
                  self.x0_pt,
                  (-self.y0_pt+3*self.y1_pt-3*self.y2_pt+self.y3_pt)*t*t*t +
                  (3*self.y0_pt-6*self.y1_pt+3*self.y2_pt          )*t*t +
                  (-3*self.y0_pt+3*self.y1_pt                      )*t +
                  self.y0_pt )
                for t in params]

    def atbegin_pt(self):
        return self.x0_pt, self.y0_pt

    def atend_pt(self):
        return self.x3_pt, self.y3_pt

    def bbox(self):
        xmin_pt, xmax_pt = path._bezierpolyrange(self.x0_pt, self.x1_pt, self.x2_pt, self.x3_pt)
        ymin_pt, ymax_pt = path._bezierpolyrange(self.y0_pt, self.y1_pt, self.y2_pt, self.y3_pt)
        return bboxmodule.bbox_pt(xmin_pt, ymin_pt, xmax_pt, ymax_pt)

    def cbox(self):
        return bboxmodule.bbox_pt(min(self.x0_pt, self.x1_pt, self.x2_pt, self.x3_pt),
                                  min(self.y0_pt, self.y1_pt, self.y2_pt, self.y3_pt),
                                  max(self.x0_pt, self.x1_pt, self.x2_pt, self.x3_pt),
                                  max(self.y0_pt, self.y1_pt, self.y2_pt, self.y3_pt))

    def curvature_pt(self, params):
        result = []
        # see notes in rotation
        approxarclen = (math.hypot(self.x1_pt-self.x0_pt, self.y1_pt-self.y0_pt) +
                        math.hypot(self.x2_pt-self.x1_pt, self.y2_pt-self.y1_pt) +
                        math.hypot(self.x3_pt-self.x2_pt, self.y3_pt-self.y2_pt))
        for param in params:
            xdot = ( 3 * (1-param)*(1-param) * (-self.x0_pt + self.x1_pt) +
                     6 * (1-param)*param * (-self.x1_pt + self.x2_pt) +
                     3 * param*param * (-self.x2_pt + self.x3_pt) )
            ydot = ( 3 * (1-param)*(1-param) * (-self.y0_pt + self.y1_pt) +
                     6 * (1-param)*param * (-self.y1_pt + self.y2_pt) +
                     3 * param*param * (-self.y2_pt + self.y3_pt) )
            xddot = ( 6 * (1-param) * (self.x0_pt - 2*self.x1_pt + self.x2_pt) +
                      6 * param * (self.x1_pt - 2*self.x2_pt + self.x3_pt) )
            yddot = ( 6 * (1-param) * (self.y0_pt - 2*self.y1_pt + self.y2_pt) +
                      6 * param * (self.y1_pt - 2*self.y2_pt + self.y3_pt) )

            hypot = math.hypot(xdot, ydot)
            if hypot/approxarclen > _minrelspeed:
                result.append((xdot*yddot - ydot*xddot) / hypot**3)
            else:
                result.append(invalid)
        return result

    def curveradius_pt(self, params):
        result = []
        # see notes in rotation
        approxarclen = (math.hypot(self.x1_pt-self.x0_pt, self.y1_pt-self.y0_pt) +
                        math.hypot(self.x2_pt-self.x1_pt, self.y2_pt-self.y1_pt) +
                        math.hypot(self.x3_pt-self.x2_pt, self.y3_pt-self.y2_pt))
        for param in params:
            xdot = ( 3 * (1-param)*(1-param) * (-self.x0_pt + self.x1_pt) +
                     6 * (1-param)*param * (-self.x1_pt + self.x2_pt) +
                     3 * param*param * (-self.x2_pt + self.x3_pt) )
            ydot = ( 3 * (1-param)*(1-param) * (-self.y0_pt + self.y1_pt) +
                     6 * (1-param)*param * (-self.y1_pt + self.y2_pt) +
                     3 * param*param * (-self.y2_pt + self.y3_pt) )
            xddot = ( 6 * (1-param) * (self.x0_pt - 2*self.x1_pt + self.x2_pt) +
                      6 * param * (self.x1_pt - 2*self.x2_pt + self.x3_pt) )
            yddot = ( 6 * (1-param) * (self.y0_pt - 2*self.y1_pt + self.y2_pt) +
                      6 * param * (self.y1_pt - 2*self.y2_pt + self.y3_pt) )

            hypot = math.hypot(xdot, ydot)
            if hypot/approxarclen > _minrelspeed:
                result.append(hypot**3 / (xdot*yddot - ydot*xddot))
            else:
                result.append(invalid)
        return result

    def intersect(self, other, epsilon):
        # There can be no intersection point, when the control boxes are not
        # overlapping. Note that we use the control box instead of the bounding
        # box here, because the former can be calculated more efficiently for
        # Bezier curves.
        if not self.cbox().intersects(other.cbox()):
            return []
        a, b = self._midpointsplit(epsilon)
        # To improve the performance in the general case we alternate the
        # splitting process between the two normsubpathitems
        return ( [(a.subparamtoparam(a_t), o_t) for o_t, a_t in other.intersect(a, epsilon)] +
                 [(b.subparamtoparam(b_t), o_t) for o_t, b_t in other.intersect(b, epsilon)] )

    def modifiedbegin_pt(self, x_pt, y_pt):
        return normcurve_pt(x_pt, y_pt,
                            self.x1_pt, self.y1_pt,
                            self.x2_pt, self.y2_pt,
                            self.x3_pt, self.y3_pt)

    def modifiedend_pt(self, x_pt, y_pt):
        return normcurve_pt(self.x0_pt, self.y0_pt,
                            self.x1_pt, self.y1_pt,
                            self.x2_pt, self.y2_pt,
                            x_pt, y_pt)

    def _paramtoarclen_pt(self, params, epsilon):
        arclens_pt = [segment.arclen_pt(epsilon) for segment in self.segments([0] + list(params) + [1])]
        for i in range(1, len(arclens_pt)):
            arclens_pt[i] += arclens_pt[i-1]
        return arclens_pt[:-1], arclens_pt[-1]

    def pathitem(self):
        return path.curveto_pt(self.x1_pt, self.y1_pt, self.x2_pt, self.y2_pt, self.x3_pt, self.y3_pt)

    def reversed(self):
        return normcurve_pt(self.x3_pt, self.y3_pt, self.x2_pt, self.y2_pt, self.x1_pt, self.y1_pt, self.x0_pt, self.y0_pt)

    def rotation(self, params):
        result = []
        # We need to take care of the case of tdx_pt and tdy_pt close to zero.
        # We should not compare those values to epsilon (which is a length) directly.
        # Furthermore we want this "speed" in general and it's abort condition in
        # particular to be invariant on the actual size of the normcurve. Hence we
        # first calculate a crude approximation for the arclen.
        approxarclen = (math.hypot(self.x1_pt-self.x0_pt, self.y1_pt-self.y0_pt) +
                        math.hypot(self.x2_pt-self.x1_pt, self.y2_pt-self.y1_pt) +
                        math.hypot(self.x3_pt-self.x2_pt, self.y3_pt-self.y2_pt))
        for param in params:
            tdx_pt = (3*(  -self.x0_pt+3*self.x1_pt-3*self.x2_pt+self.x3_pt)*param*param +
                      2*( 3*self.x0_pt-6*self.x1_pt+3*self.x2_pt           )*param +
                        (-3*self.x0_pt+3*self.x1_pt                        ))
            tdy_pt = (3*(  -self.y0_pt+3*self.y1_pt-3*self.y2_pt+self.y3_pt)*param*param +
                      2*( 3*self.y0_pt-6*self.y1_pt+3*self.y2_pt           )*param +
                        (-3*self.y0_pt+3*self.y1_pt                        ))
            # We scale the speed such the "relative speed" of a line is 1 independend of
            # the length of the line. For curves we want this "relative speed" to be higher than
            # _minrelspeed:
            if math.hypot(tdx_pt, tdy_pt)/approxarclen > _minrelspeed:
                result.append(trafo.rotate(math.degrees(math.atan2(tdy_pt, tdx_pt))))
            else:
                # Note that we can't use the rule of l'Hopital here, since it would
                # not provide us with a sign for the tangent. Hence we wouldn't
                # notice whether the sign changes (which is a typical case at cusps).
                result.append(invalid)
        return result

    def segments(self, params):
        if len(params) < 2:
            raise ValueError("at least two parameters needed in segments")

        # first, we calculate the coefficients corresponding to our
        # original bezier curve. These represent a useful starting
        # point for the following change of the polynomial parameter
        a0x_pt = self.x0_pt
        a0y_pt = self.y0_pt
        a1x_pt = 3*(-self.x0_pt+self.x1_pt)
        a1y_pt = 3*(-self.y0_pt+self.y1_pt)
        a2x_pt = 3*(self.x0_pt-2*self.x1_pt+self.x2_pt)
        a2y_pt = 3*(self.y0_pt-2*self.y1_pt+self.y2_pt)
        a3x_pt = -self.x0_pt+3*(self.x1_pt-self.x2_pt)+self.x3_pt
        a3y_pt = -self.y0_pt+3*(self.y1_pt-self.y2_pt)+self.y3_pt

        result = []

        for i in range(len(params)-1):
            t1 = params[i]
            dt = params[i+1]-t1

            # [t1,t2] part
            #
            # the new coefficients of the [t1,t1+dt] part of the bezier curve
            # are then given by expanding
            #  a0 + a1*(t1+dt*u) + a2*(t1+dt*u)**2 +
            #  a3*(t1+dt*u)**3 in u, yielding
            #
            #   a0 + a1*t1 + a2*t1**2 + a3*t1**3        +
            #   ( a1 + 2*a2 + 3*a3*t1**2 )*dt    * u    +
            #   ( a2 + 3*a3*t1 )*dt**2           * u**2 +
            #   a3*dt**3                         * u**3
            #
            # from this values we obtain the new control points by inversion
            #
            # TODO: we could do this more efficiently by reusing for
            # (x0_pt, y0_pt) the control point (x3_pt, y3_pt) from the previous
            # Bezier curve

            x0_pt = a0x_pt + a1x_pt*t1 + a2x_pt*t1*t1 + a3x_pt*t1*t1*t1
            y0_pt = a0y_pt + a1y_pt*t1 + a2y_pt*t1*t1 + a3y_pt*t1*t1*t1
            x1_pt = (a1x_pt+2*a2x_pt*t1+3*a3x_pt*t1*t1)*dt/3.0 + x0_pt
            y1_pt = (a1y_pt+2*a2y_pt*t1+3*a3y_pt*t1*t1)*dt/3.0 + y0_pt
            x2_pt = (a2x_pt+3*a3x_pt*t1)*dt*dt/3.0 - x0_pt + 2*x1_pt
            y2_pt = (a2y_pt+3*a3y_pt*t1)*dt*dt/3.0 - y0_pt + 2*y1_pt
            x3_pt = a3x_pt*dt*dt*dt + x0_pt - 3*x1_pt + 3*x2_pt
            y3_pt = a3y_pt*dt*dt*dt + y0_pt - 3*y1_pt + 3*y2_pt

            result.append(normcurve_pt(x0_pt, y0_pt, x1_pt, y1_pt, x2_pt, y2_pt, x3_pt, y3_pt))

        return result

    def trafo(self, params):
        result = []
        for rotation, at_pt in zip(self.rotation(params), self.at_pt(params)):
            if rotation is invalid:
                result.append(rotation)
            else:
                result.append(trafo.translate_pt(*at_pt) * rotation)
        return result

    def transformed(self, trafo):
        x0_pt, y0_pt = trafo.apply_pt(self.x0_pt, self.y0_pt)
        x1_pt, y1_pt = trafo.apply_pt(self.x1_pt, self.y1_pt)
        x2_pt, y2_pt = trafo.apply_pt(self.x2_pt, self.y2_pt)
        x3_pt, y3_pt = trafo.apply_pt(self.x3_pt, self.y3_pt)
        return normcurve_pt(x0_pt, y0_pt, x1_pt, y1_pt, x2_pt, y2_pt, x3_pt, y3_pt)

    def outputPS(self, file, writer):
        file.write("%g %g %g %g %g %g curveto\n" % (self.x1_pt, self.y1_pt, self.x2_pt, self.y2_pt, self.x3_pt, self.y3_pt))

    def outputPDF(self, file, writer):
        file.write("%f %f %f %f %f %f c\n" % (self.x1_pt, self.y1_pt, self.x2_pt, self.y2_pt, self.x3_pt, self.y3_pt))

    def x_pt(self, t):
        return (((  self.x3_pt-3*self.x2_pt+3*self.x1_pt-self.x0_pt)*t +
                  3*self.x0_pt-6*self.x1_pt+3*self.x2_pt)*t +
                  3*self.x1_pt-3*self.x0_pt)*t + self.x0_pt

    def xdot_pt(self, t):
        return ((3*self.x3_pt-9*self.x2_pt+9*self.x1_pt-3*self.x0_pt)*t +
                 6*self.x0_pt-12*self.x1_pt+6*self.x2_pt)*t + 3*self.x1_pt - 3*self.x0_pt

    def xddot_pt(self, t):
        return (6*self.x3_pt-18*self.x2_pt+18*self.x1_pt-6*self.x0_pt)*t + 6*self.x0_pt - 12*self.x1_pt + 6*self.x2_pt

    def xdddot_pt(self, t):
        return 6*self.x3_pt-18*self.x2_pt+18*self.x1_pt-6*self.x0_pt

    def y_pt(self, t):
        return (((  self.y3_pt-3*self.y2_pt+3*self.y1_pt-self.y0_pt)*t +
                  3*self.y0_pt-6*self.y1_pt+3*self.y2_pt)*t +
                  3*self.y1_pt-3*self.y0_pt)*t + self.y0_pt

    def ydot_pt(self, t):
        return ((3*self.y3_pt-9*self.y2_pt+9*self.y1_pt-3*self.y0_pt)*t +
                 6*self.y0_pt-12*self.y1_pt+6*self.y2_pt)*t + 3*self.y1_pt - 3*self.y0_pt

    def yddot_pt(self, t):
        return (6*self.y3_pt-18*self.y2_pt+18*self.y1_pt-6*self.y0_pt)*t + 6*self.y0_pt - 12*self.y1_pt + 6*self.y2_pt

    def ydddot_pt(self, t):
        return 6*self.y3_pt-18*self.y2_pt+18*self.y1_pt-6*self.y0_pt


# curve replacements used by midpointsplit:
# The replacements are normline_pt and normcurve_pt instances with an
# additional subparamtoparam function for proper conversion of the
# parametrization. Note that we only one direction (when a parameter
# gets calculated), since the other way around direction midpointsplit
# is not needed at all

class _leftnormline_pt(normline_pt):

    __slots__ = "x0_pt", "y0_pt", "x1_pt", "y1_pt", "l1_pt", "l2_pt", "l3_pt"

    def __init__(self, x0_pt, y0_pt, x1_pt, y1_pt, l1_pt, l2_pt, l3_pt):
        normline_pt.__init__(self, x0_pt, y0_pt, x1_pt, y1_pt)
        self.l1_pt = l1_pt
        self.l2_pt = l2_pt
        self.l3_pt = l3_pt

    def subparamtoparam(self, param):
        if 0 <= param <= 1:
            params = mathutils.realpolyroots(self.l1_pt-2*self.l2_pt+self.l3_pt,
                                             -3*self.l1_pt+3*self.l2_pt,
                                             3*self.l1_pt,
                                             -param*(self.l1_pt+self.l2_pt+self.l3_pt))
            # we might get several solutions and choose the one closest to 0.5
            # (we want the solution to be in the range 0 <= param <= 1; in case
            # we get several solutions in this range, they all will be close to
            # each other since l1_pt+l2_pt+l3_pt-l0_pt < epsilon)
            params.sort(lambda t1, t2: cmp(abs(t1-0.5), abs(t2-0.5)))
            return 0.5*params[0]
        else:
            # when we are outside the proper parameter range, we skip the non-linear
            # transformation, since it becomes slow and it might even start to be
            # numerically instable
            return 0.5*param


class _rightnormline_pt(_leftnormline_pt):

    __slots__ = "x0_pt", "y0_pt", "x1_pt", "y1_pt", "l1_pt", "l2_pt", "l3_pt"

    def subparamtoparam(self, param):
        return 0.5+_leftnormline_pt.subparamtoparam(self, param)


class _leftnormcurve_pt(normcurve_pt):

    __slots__ = "x0_pt", "y0_pt", "x1_pt", "y1_pt", "x2_pt", "y2_pt", "x3_pt", "y3_pt"

    def subparamtoparam(self, param):
        return 0.5*param


class _rightnormcurve_pt(normcurve_pt):

    __slots__ = "x0_pt", "y0_pt", "x1_pt", "y1_pt", "x2_pt", "y2_pt", "x3_pt", "y3_pt"

    def subparamtoparam(self, param):
        return 0.5+0.5*param


################################################################################
# normsubpath
################################################################################

class normsubpath:

    """sub path of a normalized path

    A subpath consists of a list of normsubpathitems, i.e., normlines_pt and
    normcurves_pt and can either be closed or not.

    Some invariants, which have to be obeyed:
    - All normsubpathitems have to be longer than epsilon pts.
    - At the end there may be a normline (stored in self.skippedline) whose
      length is shorter than epsilon -- it has to be taken into account
      when adding further normsubpathitems
    - The last point of a normsubpathitem and the first point of the next
      element have to be equal.
    - When the path is closed, the last point of last normsubpathitem has
      to be equal to the first point of the first normsubpathitem.
    - epsilon might be none, disallowing any numerics, but allowing for
      arbitrary short paths. This is used in pdf output, where all paths need
      to be transformed to normpaths.
    """

    __slots__ = "normsubpathitems", "closed", "epsilon", "skippedline"

    def __init__(self, normsubpathitems=[], closed=0, epsilon=_marker):
        """construct a normsubpath"""
        if epsilon is _marker:
            epsilon = _epsilon
        self.epsilon = epsilon
        # If one or more items appended to the normsubpath have been
        # skipped (because their total length was shorter than epsilon),
        # we remember this fact by a line because we have to take it
        # properly into account when appending further normsubpathitems
        self.skippedline = None

        self.normsubpathitems = []
        self.closed = 0

        # a test (might be temporary)
        for anormsubpathitem in normsubpathitems:
            assert isinstance(anormsubpathitem, normsubpathitem), "only list of normsubpathitem instances allowed"

        self.extend(normsubpathitems)

        if closed:
            self.close()

    def __getitem__(self, i):
        """return normsubpathitem i"""
        return self.normsubpathitems[i]

    def __len__(self):
        """return number of normsubpathitems"""
        return len(self.normsubpathitems)

    def __str__(self):
        l = ", ".join(map(str, self.normsubpathitems))
        if self.closed:
            return "normsubpath([%s], closed=1)" % l
        else:
            return "normsubpath([%s])" % l

    def _distributeparams(self, params):
        """return a dictionary mapping normsubpathitemindices to a tuple
        of a paramindices and normsubpathitemparams.

        normsubpathitemindex specifies a normsubpathitem containing
        one or several positions.  paramindex specify the index of the
        param in the original list and normsubpathitemparam is the
        parameter value in the normsubpathitem.
        """

        result = {}
        for i, param in enumerate(params):
            if param > 0:
                index = int(param)
                if index > len(self.normsubpathitems) - 1:
                    index = len(self.normsubpathitems) - 1
            else:
                index = 0
            result.setdefault(index, ([], []))
            result[index][0].append(i)
            result[index][1].append(param - index)
        return result

    def append(self, anormsubpathitem):
        """append normsubpathitem

        Fails on closed normsubpath.
        """
        if self.epsilon is None:
            self.normsubpathitems.append(anormsubpathitem)
        else:
            # consitency tests (might be temporary)
            assert isinstance(anormsubpathitem, normsubpathitem), "only normsubpathitem instances allowed"
            if self.skippedline:
                assert math.hypot(*[x-y for x, y in zip(self.skippedline.atend_pt(), anormsubpathitem.atbegin_pt())]) < self.epsilon, "normsubpathitems do not match"
            elif self.normsubpathitems:
                assert math.hypot(*[x-y for x, y in zip(self.normsubpathitems[-1].atend_pt(), anormsubpathitem.atbegin_pt())]) < self.epsilon, "normsubpathitems do not match"

            if self.closed:
                raise NormpathException("Cannot append to closed normsubpath")

            if self.skippedline:
                xs_pt, ys_pt = self.skippedline.atbegin_pt()
            else:
                xs_pt, ys_pt = anormsubpathitem.atbegin_pt()
            xe_pt, ye_pt = anormsubpathitem.atend_pt()

            if (math.hypot(xe_pt-xs_pt, ye_pt-ys_pt) >= self.epsilon or
                anormsubpathitem.arclen_pt(self.epsilon) >= self.epsilon):
                if self.skippedline:
                    anormsubpathitem = anormsubpathitem.modifiedbegin_pt(xs_pt, ys_pt)
                self.normsubpathitems.append(anormsubpathitem)
                self.skippedline = None
            else:
                self.skippedline = normline_pt(xs_pt, ys_pt, xe_pt, ye_pt)

    def arclen_pt(self):
        """return arc length in pts"""
        return sum([npitem.arclen_pt(self.epsilon) for npitem in self.normsubpathitems])

    def _arclentoparam_pt(self, lengths_pt):
        """return a tuple of params and the total length arc length in pts"""
        # work on a copy which is counted down to negative values
        lengths_pt = lengths_pt[:]
        results = [None] * len(lengths_pt)

        totalarclen = 0
        for normsubpathindex, normsubpathitem in enumerate(self.normsubpathitems):
            params, arclen = normsubpathitem._arclentoparam_pt(lengths_pt, self.epsilon)
            for i in range(len(results)):
                if results[i] is None:
                    lengths_pt[i] -= arclen
                    if lengths_pt[i] < 0 or normsubpathindex == len(self.normsubpathitems) - 1:
                        # overwrite the results until the length has become negative
                        results[i] = normsubpathindex + params[i]
            totalarclen += arclen

        return results, totalarclen

    def arclentoparam_pt(self, lengths_pt):
        """return a tuple of params"""
        return self._arclentoparam_pt(lengths_pt)[0]

    def at_pt(self, params):
        """return coordinates at params in pts"""
        if not self.normsubpathitems and self.skippedline:
            return [self.skippedline.atbegin_pt()]*len(params)
        result = [None] * len(params)
        for normsubpathitemindex, (indices, params) in self._distributeparams(params).items():
            for index, point_pt in zip(indices, self.normsubpathitems[normsubpathitemindex].at_pt(params)):
                result[index] = point_pt
        return result

    def atbegin_pt(self):
        """return coordinates of first point in pts"""
        if not self.normsubpathitems and self.skippedline:
            return self.skippedline.atbegin_pt()
        return self.normsubpathitems[0].atbegin_pt()

    def atend_pt(self):
        """return coordinates of last point in pts"""
        if self.skippedline:
            return self.skippedline.atend_pt()
        return self.normsubpathitems[-1].atend_pt()

    def bbox(self):
        """return bounding box of normsubpath"""
        if self.normsubpathitems:
            abbox = self.normsubpathitems[0].bbox()
            for anormpathitem in self.normsubpathitems[1:]:
                abbox += anormpathitem.bbox()
            return abbox
        else:
            return bboxmodule.empty()

    def close(self):
        """close subnormpath

        Fails on closed normsubpath.
        """
        if self.closed:
            raise NormpathException("Cannot close already closed normsubpath")
        if not self.normsubpathitems:
            if self.skippedline is None:
                raise NormpathException("Cannot close empty normsubpath")
            else:
                raise NormpathException("Normsubpath too short, cannot be closed")

        xs_pt, ys_pt = self.normsubpathitems[-1].atend_pt()
        xe_pt, ye_pt = self.normsubpathitems[0].atbegin_pt()
        self.append(normline_pt(xs_pt, ys_pt, xe_pt, ye_pt))
        self.flushskippedline()
        self.closed = 1

    def copy(self):
        """return copy of normsubpath"""
        # Since normsubpathitems are never modified inplace, we just
        # need to copy the normsubpathitems list. We do not pass the
        # normsubpathitems to the constructor to not repeat the checks
        # for minimal length of each normsubpathitem.
        result = normsubpath(epsilon=self.epsilon)
        result.normsubpathitems = self.normsubpathitems[:]
        result.closed = self.closed

        # We can share the reference to skippedline, since it is a
        # normsubpathitem as well and thus not modified in place either.
        result.skippedline = self.skippedline

        return result

    def curvature_pt(self, params):
        """return the curvature at params in 1/pts

        The result contain the invalid instance at positions, where the
        curvature is undefined."""
        result = [None] * len(params)
        for normsubpathitemindex, (indices, params) in self._distributeparams(params).items():
            for index, curvature_pt in zip(indices, self.normsubpathitems[normsubpathitemindex].curvature_pt(params)):
                result[index] = curvature_pt
        return result

    def curveradius_pt(self, params):
        """return the curvature radius at params in pts

        The curvature radius is the inverse of the curvature. When the
        curvature is 0, the invalid instance is returned. Note that this radius can be negative
        or positive, depending on the sign of the curvature."""
        result = [None] * len(params)
        for normsubpathitemindex, (indices, params) in self._distributeparams(params).items():
            for index, radius_pt in zip(indices, self.normsubpathitems[normsubpathitemindex].curveradius_pt(params)):
                result[index] = radius_pt
        return result

    def extend(self, normsubpathitems):
        """extend path by normsubpathitems

        Fails on closed normsubpath.
        """
        for normsubpathitem in normsubpathitems:
            self.append(normsubpathitem)

    def flushskippedline(self):
        """flush the skippedline, i.e. apply it to the normsubpath

        remove the skippedline by modifying the end point of the existing normsubpath
        """
        while self.skippedline:
            try:
                lastnormsubpathitem = self.normsubpathitems.pop()
            except IndexError:
                raise ValueError("normsubpath too short to flush the skippedline")
            lastnormsubpathitem = lastnormsubpathitem.modifiedend_pt(*self.skippedline.atend_pt())
            self.skippedline = None
            self.append(lastnormsubpathitem)

    def intersect(self, other):
        """intersect self with other normsubpath

        Returns a tuple of lists consisting of the parameter values
        of the intersection points of the corresponding normsubpath.
        """
        intersections_a = []
        intersections_b = []
        epsilon = min(self.epsilon, other.epsilon)
        # Intersect all subpaths of self with the subpaths of other, possibly including
        # one intersection point several times
        for t_a, pitem_a  in enumerate(self.normsubpathitems):
            for t_b, pitem_b in enumerate(other.normsubpathitems):
                for intersection_a, intersection_b in pitem_a.intersect(pitem_b, epsilon):
                    intersections_a.append(intersection_a + t_a)
                    intersections_b.append(intersection_b + t_b)

        # although intersectipns_a are sorted for the different normsubpathitems,
        # within a normsubpathitem, the ordering has to be ensured separately:
        intersections = zip(intersections_a, intersections_b)
        intersections.sort()
        intersections_a = [a for a, b in intersections]
        intersections_b = [b for a, b in intersections]

        # for symmetry reasons we enumerate intersections_a as well, although
        # they are already sorted (note we do not need to sort intersections_a)
        intersections_a = zip(intersections_a, range(len(intersections_a)))
        intersections_b = zip(intersections_b, range(len(intersections_b)))
        intersections_b.sort()

        # now we search for intersections points which are closer together than epsilon
        # This task is handled by the following function
        def closepoints(normsubpath, intersections):
            split = normsubpath.segments([0] + [intersection for intersection, index in intersections] + [len(normsubpath)])
            result = []
            if normsubpath.closed:
                # note that the number of segments of a closed path is off by one
                # compared to an open path
                i = 0
                while i < len(split):
                    splitnormsubpath = split[i]
                    j = i
                    while not splitnormsubpath.normsubpathitems: # i.e. while "is short"
                        ip1, ip2 = intersections[i-1][1], intersections[j][1]
                        if ip1<ip2:
                            result.append((ip1, ip2))
                        else:
                            result.append((ip2, ip1))
                        j += 1
                        if j == len(split):
                            j = 0
                        if j < len(split):
                            splitnormsubpath = splitnormsubpath.joined(split[j])
                        else:
                            break
                    i += 1
            else:
                i = 1
                while i < len(split)-1:
                    splitnormsubpath = split[i]
                    j = i
                    while not splitnormsubpath.normsubpathitems: # i.e. while "is short"
                        ip1, ip2 = intersections[i-1][1], intersections[j][1]
                        if ip1<ip2:
                            result.append((ip1, ip2))
                        else:
                            result.append((ip2, ip1))
                        j += 1
                        if j < len(split)-1:
                            splitnormsubpath = splitnormsubpath.joined(split[j])
                        else:
                            break
                    i += 1
            return result

        closepoints_a = closepoints(self, intersections_a)
        closepoints_b = closepoints(other, intersections_b)

        # map intersection point to lowest point which is equivalent to the
        # point
        equivalentpoints = list(range(len(intersections_a)))

        for closepoint_a in closepoints_a:
            for closepoint_b in closepoints_b:
                if closepoint_a == closepoint_b:
                    for i in range(closepoint_a[1], len(equivalentpoints)):
                        if equivalentpoints[i] == closepoint_a[1]:
                            equivalentpoints[i] = closepoint_a[0]

        # determine the remaining intersection points
        intersectionpoints = {}
        for point in equivalentpoints:
            intersectionpoints[point] = 1

        # build result
        result = []
        intersectionpointskeys = intersectionpoints.keys()
        intersectionpointskeys.sort()
        for point in intersectionpointskeys:
            for intersection_a, index_a in intersections_a:
                if index_a == point:
                    result_a = intersection_a
            for intersection_b, index_b in intersections_b:
                if index_b == point:
                    result_b = intersection_b
            result.append((result_a, result_b))
        # note that the result is sorted in a, since we sorted
        # intersections_a in the very beginning

        return [x for x, y in result], [y for x, y in result]

    def join(self, other):
        """join other normsubpath inplace

        Fails on closed normsubpath. Fails to join closed normsubpath.
        """
        if other.closed:
            raise NormpathException("Cannot join closed normsubpath")

        if self.normsubpathitems:
            # insert connection line
            x0_pt, y0_pt = self.atend_pt()
            x1_pt, y1_pt = other.atbegin_pt()
            self.append(normline_pt(x0_pt, y0_pt, x1_pt, y1_pt))

        # append other normsubpathitems
        self.extend(other.normsubpathitems)
        if other.skippedline:
            self.append(other.skippedline)

    def joined(self, other):
        """return joined self and other

        Fails on closed normsubpath. Fails to join closed normsubpath.
        """
        result = self.copy()
        result.join(other)
        return result

    def _paramtoarclen_pt(self, params):
        """return a tuple of arc lengths and the total arc length in pts"""
        if not self.normsubpathitems:
            return [0] * len(params), 0
        result = [None] * len(params)
        totalarclen_pt = 0
        distributeparams = self._distributeparams(params)
        for normsubpathitemindex in range(len(self.normsubpathitems)):
            if distributeparams.has_key(normsubpathitemindex):
                indices, params = distributeparams[normsubpathitemindex]
                arclens_pt, normsubpathitemarclen_pt = self.normsubpathitems[normsubpathitemindex]._paramtoarclen_pt(params, self.epsilon)
                for index, arclen_pt in zip(indices, arclens_pt):
                    result[index] = totalarclen_pt + arclen_pt
                totalarclen_pt += normsubpathitemarclen_pt
            else:
                totalarclen_pt += self.normsubpathitems[normsubpathitemindex].arclen_pt(self.epsilon)
        return result, totalarclen_pt

    def pathitems(self):
        """return list of pathitems"""
        if not self.normsubpathitems:
            return []

        # remove trailing normline_pt of closed subpaths
        if self.closed and isinstance(self.normsubpathitems[-1], normline_pt):
            normsubpathitems = self.normsubpathitems[:-1]
        else:
            normsubpathitems = self.normsubpathitems

        result = [path.moveto_pt(*self.atbegin_pt())]
        for normsubpathitem in normsubpathitems:
            result.append(normsubpathitem.pathitem())
        if self.closed:
            result.append(path.closepath())
        return result

    def reversed(self):
        """return reversed normsubpath"""
        nnormpathitems = []
        for i in range(len(self.normsubpathitems)):
            nnormpathitems.append(self.normsubpathitems[-(i+1)].reversed())
        return normsubpath(nnormpathitems, self.closed, self.epsilon)

    def rotation(self, params):
        """return rotations at params"""
        result = [None] * len(params)
        for normsubpathitemindex, (indices, params) in self._distributeparams(params).items():
            for index, rotation in zip(indices, self.normsubpathitems[normsubpathitemindex].rotation(params)):
                result[index] = rotation
        return result

    def segments(self, params):
        """return segments of the normsubpath

        The returned list of normsubpaths for the segments between
        the params. params need to contain at least two values.

        For a closed normsubpath the last segment result is joined to
        the first one when params starts with 0 and ends with len(self).
        or params starts with len(self) and ends with 0. Thus a segments
        operation on a closed normsubpath might properly join those the
        first and the last part to take into account the closed nature of
        the normsubpath. However, for intermediate parameters, closepath
        is not taken into account, i.e. when walking backwards you do not
        loop over the closepath forwardly. The special values 0 and
        len(self) for the first and the last parameter should be given as
        integers, i.e. no finite precision is used when checking for
        equality."""

        if len(params) < 2:
            raise ValueError("at least two parameters needed in segments")

        result = [normsubpath(epsilon=self.epsilon)]

        # instead of distribute the parameters, we need to keep their
        # order and collect parameters for the needed segments of
        # normsubpathitem with index collectindex
        collectparams = []
        collectindex = None
        for param in params:
            # calculate index and parameter for corresponding normsubpathitem
            if param > 0:
                index = int(param)
                if index > len(self.normsubpathitems) - 1:
                    index = len(self.normsubpathitems) - 1
                param -= index
            else:
                index = 0
            if index != collectindex:
                if collectindex is not None:
                    # append end point depening on the forthcoming index
                    if index > collectindex:
                        collectparams.append(1)
                    else:
                        collectparams.append(0)
                    # get segments of the normsubpathitem and add them to the result
                    segments = self.normsubpathitems[collectindex].segments(collectparams)
                    result[-1].append(segments[0])
                    result.extend([normsubpath([segment], epsilon=self.epsilon) for segment in segments[1:]])
                    # add normsubpathitems and first segment parameter to close the
                    # gap to the forthcoming index
                    if index > collectindex:
                        for i in range(collectindex+1, index):
                            result[-1].append(self.normsubpathitems[i])
                        collectparams = [0]
                    else:
                        for i in range(collectindex-1, index, -1):
                            result[-1].append(self.normsubpathitems[i].reversed())
                        collectparams = [1]
                collectindex = index
            collectparams.append(param)
        # add remaining collectparams to the result
        segments = self.normsubpathitems[collectindex].segments(collectparams)
        result[-1].append(segments[0])
        result.extend([normsubpath([segment], epsilon=self.epsilon) for segment in segments[1:]])

        if self.closed:
            # join last and first segment together if the normsubpath was
            # originally closed and first and the last parameters are the
            # beginning and end points of the normsubpath
            if ( ( params[0] == 0 and params[-1] == len(self.normsubpathitems) ) or
                 ( params[-1] == 0 and params[0] == len(self.normsubpathitems) ) ):
                result[-1].normsubpathitems.extend(result[0].normsubpathitems)
                result = result[-1:] + result[1:-1]

        return result

    def trafo(self, params):
        """return transformations at params"""
        result = [None] * len(params)
        for normsubpathitemindex, (indices, params) in self._distributeparams(params).items():
            for index, trafo in zip(indices, self.normsubpathitems[normsubpathitemindex].trafo(params)):
                result[index] = trafo
        return result

    def transformed(self, trafo):
        """return transformed path"""
        nnormsubpath = normsubpath(epsilon=self.epsilon)
        for pitem in self.normsubpathitems:
            nnormsubpath.append(pitem.transformed(trafo))
        if self.closed:
            nnormsubpath.close()
        elif self.skippedline is not None:
            nnormsubpath.append(self.skippedline.transformed(trafo))
        return nnormsubpath

    def outputPS(self, file, writer):
        # if the normsubpath is closed, we must not output a normline at
        # the end
        if not self.normsubpathitems:
            return
        if self.closed and isinstance(self.normsubpathitems[-1], normline_pt):
            assert len(self.normsubpathitems) > 1, "a closed normsubpath should contain more than a single normline_pt"
            normsubpathitems = self.normsubpathitems[:-1]
        else:
            normsubpathitems = self.normsubpathitems
        file.write("%g %g moveto\n" % self.atbegin_pt())
        for anormsubpathitem in normsubpathitems:
            anormsubpathitem.outputPS(file, writer)
        if self.closed:
            file.write("closepath\n")

    def outputPDF(self, file, writer):
        # if the normsubpath is closed, we must not output a normline at
        # the end
        if not self.normsubpathitems:
            return
        if self.closed and isinstance(self.normsubpathitems[-1], normline_pt):
            assert len(self.normsubpathitems) > 1, "a closed normsubpath should contain more than a single normline_pt"
            normsubpathitems = self.normsubpathitems[:-1]
        else:
            normsubpathitems = self.normsubpathitems
        file.write("%f %f m\n" % self.atbegin_pt())
        for anormsubpathitem in normsubpathitems:
            anormsubpathitem.outputPDF(file, writer)
        if self.closed:
            file.write("h\n")


################################################################################
# normpath
################################################################################

class normpathparam:

    """parameter of a certain point along a normpath"""

    __slots__ = "normpath", "normsubpathindex", "normsubpathparam"

    def __init__(self, normpath, normsubpathindex, normsubpathparam):
        self.normpath = normpath
        self.normsubpathindex = normsubpathindex
        self.normsubpathparam = normsubpathparam
        float(normsubpathparam)

    def __str__(self):
        return "normpathparam(%s, %s, %s)" % (self.normpath, self.normsubpathindex, self.normsubpathparam)

    def __add__(self, other):
        if isinstance(other, normpathparam):
            assert self.normpath is other.normpath, "normpathparams have to belong to the same normpath"
            return self.normpath.arclentoparam_pt(self.normpath.paramtoarclen_pt(self) +
                                                  other.normpath.paramtoarclen_pt(other))
        else:
            return self.normpath.arclentoparam_pt(self.normpath.paramtoarclen_pt(self) + unit.topt(other))

    __radd__ = __add__

    def __sub__(self, other):
        if isinstance(other, normpathparam):
            assert self.normpath is other.normpath, "normpathparams have to belong to the same normpath"
            return self.normpath.arclentoparam_pt(self.normpath.paramtoarclen_pt(self) -
                                                  other.normpath.paramtoarclen_pt(other))
        else:
            return self.normpath.arclentoparam_pt(self.normpath.paramtoarclen_pt(self) - unit.topt(other))

    def __rsub__(self, other):
        # other has to be a length in this case
        return self.normpath.arclentoparam_pt(-self.normpath.paramtoarclen_pt(self) + unit.topt(other))

    def __mul__(self, factor):
        return self.normpath.arclentoparam_pt(self.normpath.paramtoarclen_pt(self) * factor)

    __rmul__ = __mul__

    def __div__(self, divisor):
        return self.normpath.arclentoparam_pt(self.normpath.paramtoarclen_pt(self) / divisor)

    def __neg__(self):
        return self.normpath.arclentoparam_pt(-self.normpath.paramtoarclen_pt(self))

    def __cmp__(self, other):
        if isinstance(other, normpathparam):
            assert self.normpath is other.normpath, "normpathparams have to belong to the same normpath"
            return cmp((self.normsubpathindex, self.normsubpathparam), (other.normsubpathindex, other.normsubpathparam))
        else:
            return cmp(self.normpath.paramtoarclen_pt(self), unit.topt(other))

    def arclen_pt(self):
        """return arc length in pts corresponding to the normpathparam """
        return self.normpath.paramtoarclen_pt(self)

    def arclen(self):
        """return arc length corresponding to the normpathparam """
        return self.normpath.paramtoarclen(self)


def _valueorlistmethod(method):
    """Creates a method which takes a single argument or a list and
    returns a single value or a list out of method, which always
    works on lists."""

    def wrappedmethod(self, valueorlist, *args, **kwargs):
        try:
            for item in valueorlist:
                break
        except:
            return method(self, [valueorlist], *args, **kwargs)[0]
        return method(self, valueorlist, *args, **kwargs)
    return wrappedmethod


class normpath:

    """normalized path

    A normalized path consists of a list of normsubpaths.
    """

    def __init__(self, normsubpaths=None):
        """construct a normpath from a list of normsubpaths"""

        if normsubpaths is None:
            self.normsubpaths = [] # make a fresh list
        else:
            self.normsubpaths = normsubpaths
            for subpath in normsubpaths:
                assert isinstance(subpath, normsubpath), "only list of normsubpath instances allowed"

    def __add__(self, other):
        """create new normpath out of self and other"""
        result = self.copy()
        result += other
        return result

    def __iadd__(self, other):
        """add other inplace"""
        for normsubpath in other.normpath().normsubpaths:
            self.normsubpaths.append(normsubpath.copy())
        return self

    def __getitem__(self, i):
        """return normsubpath i"""
        return self.normsubpaths[i]

    def __len__(self):
        """return the number of normsubpaths"""
        return len(self.normsubpaths)

    def __str__(self):
        return "normpath([%s])" % ", ".join(map(str, self.normsubpaths))

    def _convertparams(self, params, convertmethod):
        """return params with all non-normpathparam arguments converted by convertmethod

        usecases:
        - self._convertparams(params, self.arclentoparam_pt)
        - self._convertparams(params, self.arclentoparam)
        """

        converttoparams = []
        convertparamindices = []
        for i, param in enumerate(params):
            if not isinstance(param, normpathparam):
                converttoparams.append(param)
                convertparamindices.append(i)
        if converttoparams:
            params = params[:]
            for i, param in zip(convertparamindices, convertmethod(converttoparams)):
                params[i] = param
        return params

    def _distributeparams(self, params):
        """return a dictionary mapping subpathindices to a tuple of a paramindices and subpathparams

        subpathindex specifies a subpath containing one or several positions.
        paramindex specify the index of the normpathparam in the original list and
        subpathparam is the parameter value in the subpath.
        """

        result = {}
        for i, param in enumerate(params):
            assert param.normpath is self, "normpathparam has to belong to this path"
            result.setdefault(param.normsubpathindex, ([], []))
            result[param.normsubpathindex][0].append(i)
            result[param.normsubpathindex][1].append(param.normsubpathparam)
        return result

    def append(self, item):
        """append a normpath by a normsubpath or a pathitem"""
        if isinstance(item, normsubpath):
            # the normsubpaths list can be appended by a normsubpath only
            self.normsubpaths.append(item)
        elif isinstance(item, path.pathitem):
            # ... but we are kind and allow for regular path items as well
            # in order to make a normpath to behave more like a regular path
            if self.normsubpaths:
                context = path.context(*(self.normsubpaths[-1].atend_pt() +
                                         self.normsubpaths[-1].atbegin_pt()))
                item.updatenormpath(self, context)
            else:
                self.normsubpaths = item.createnormpath(self).normsubpaths

    def arclen_pt(self):
        """return arc length in pts"""
        return sum([normsubpath.arclen_pt() for normsubpath in self.normsubpaths])

    def arclen(self):
        """return arc length"""
        return self.arclen_pt() * unit.t_pt

    def _arclentoparam_pt(self, lengths_pt):
        """return the params matching the given lengths_pt"""
        # work on a copy which is counted down to negative values
        lengths_pt = lengths_pt[:]
        results = [None] * len(lengths_pt)

        for normsubpathindex, normsubpath in enumerate(self.normsubpaths):
            params, arclen = normsubpath._arclentoparam_pt(lengths_pt)
            done = 1
            for i, result in enumerate(results):
                if results[i] is None:
                    lengths_pt[i] -= arclen
                    if lengths_pt[i] < 0 or normsubpathindex == len(self.normsubpaths) - 1:
                        # overwrite the results until the length has become negative
                        results[i] = normpathparam(self, normsubpathindex, params[i])
                    done = 0
            if done:
                break

        return results

    def arclentoparam_pt(self, lengths_pt):
        """return the param(s) matching the given length(s)_pt in pts"""
        pass
    arclentoparam_pt = _valueorlistmethod(_arclentoparam_pt)

    def arclentoparam(self, lengths):
        """return the param(s) matching the given length(s)"""
        return self._arclentoparam_pt([unit.topt(l) for l in lengths])
    arclentoparam = _valueorlistmethod(arclentoparam)

    def _at_pt(self, params):
        """return coordinates of normpath in pts at params"""
        result = [None] * len(params)
        for normsubpathindex, (indices, params) in self._distributeparams(params).items():
            for index, point_pt in zip(indices, self.normsubpaths[normsubpathindex].at_pt(params)):
                result[index] = point_pt
        return result

    def at_pt(self, params):
        """return coordinates of normpath in pts at param(s) or lengths in pts"""
        return self._at_pt(self._convertparams(params, self.arclentoparam_pt))
    at_pt = _valueorlistmethod(at_pt)

    def at(self, params):
        """return coordinates of normpath at param(s) or arc lengths"""
        return [(x_pt * unit.t_pt, y_pt * unit.t_pt)
                for x_pt, y_pt in self._at_pt(self._convertparams(params, self.arclentoparam))]
    at = _valueorlistmethod(at)

    def atbegin_pt(self):
        """return coordinates of the beginning of first subpath in normpath in pts"""
        if self.normsubpaths:
            return self.normsubpaths[0].atbegin_pt()
        else:
            raise NormpathException("cannot return first point of empty path")

    def atbegin(self):
        """return coordinates of the beginning of first subpath in normpath"""
        x, y = self.atbegin_pt()
        return x * unit.t_pt, y * unit.t_pt

    def atend_pt(self):
        """return coordinates of the end of last subpath in normpath in pts"""
        if self.normsubpaths:
            return self.normsubpaths[-1].atend_pt()
        else:
            raise NormpathException("cannot return last point of empty path")

    def atend(self):
        """return coordinates of the end of last subpath in normpath"""
        x, y = self.atend_pt()
        return x * unit.t_pt, y * unit.t_pt

    def bbox(self):
        """return bbox of normpath"""
        abbox = bboxmodule.empty()
        for normsubpath in self.normsubpaths:
            abbox += normsubpath.bbox()
        return abbox

    def begin(self):
        """return param corresponding of the beginning of the normpath"""
        if self.normsubpaths:
            return normpathparam(self, 0, 0)
        else:
            raise NormpathException("empty path")

    def copy(self):
        """return copy of normpath"""
        result = normpath()
        for normsubpath in self.normsubpaths:
            result.append(normsubpath.copy())
        return result

    def _curvature_pt(self, params):
        """return the curvature in 1/pts at params

        When the curvature is undefined, the invalid instance is returned."""

        result = [None] * len(params)
        for normsubpathindex, (indices, params) in self._distributeparams(params).items():
            for index, curvature_pt in zip(indices, self.normsubpaths[normsubpathindex].curvature_pt(params)):
                result[index] = curvature_pt
        return result

    def curvature_pt(self, params):
        """return the curvature in 1/pt at params

        The curvature radius is the inverse of the curvature. When the
        curvature is undefined, the invalid instance is returned. Note that
        this radius can be negative or positive, depending on the sign of the
        curvature."""

        result = [None] * len(params)
        for normsubpathindex, (indices, params) in self._distributeparams(params).items():
            for index, curv_pt in zip(indices, self.normsubpaths[normsubpathindex].curvature_pt(params)):
                result[index] = curv_pt
        return result
    curvature_pt = _valueorlistmethod(curvature_pt)

    def _curveradius_pt(self, params):
        """return the curvature radius at params in pts

        The curvature radius is the inverse of the curvature. When the
        curvature is 0, None is returned. Note that this radius can be negative
        or positive, depending on the sign of the curvature."""

        result = [None] * len(params)
        for normsubpathindex, (indices, params) in self._distributeparams(params).items():
            for index, radius_pt in zip(indices, self.normsubpaths[normsubpathindex].curveradius_pt(params)):
                result[index] = radius_pt
        return result

    def curveradius_pt(self, params):
        """return the curvature radius in pts at param(s) or arc length(s) in pts

        The curvature radius is the inverse of the curvature. When the
        curvature is 0, None is returned. Note that this radius can be negative
        or positive, depending on the sign of the curvature."""

        return self._curveradius_pt(self._convertparams(params, self.arclentoparam_pt))
    curveradius_pt = _valueorlistmethod(curveradius_pt)

    def curveradius(self, params):
        """return the curvature radius at param(s) or arc length(s)

        The curvature radius is the inverse of the curvature. When the
        curvature is 0, None is returned. Note that this radius can be negative
        or positive, depending on the sign of the curvature."""

        result = []
        for radius_pt in self._curveradius_pt(self._convertparams(params, self.arclentoparam)):
            if radius_pt is not invalid:
                result.append(radius_pt * unit.t_pt)
            else:
                result.append(invalid)
        return result
    curveradius = _valueorlistmethod(curveradius)

    def end(self):
        """return param corresponding of the end of the path"""
        if self.normsubpaths:
            return normpathparam(self, len(self)-1, len(self.normsubpaths[-1]))
        else:
            raise NormpathException("empty path")

    def extend(self, normsubpaths):
        """extend path by normsubpaths or pathitems"""
        for anormsubpath in normsubpaths:
            # use append to properly handle regular path items as well as normsubpaths
            self.append(anormsubpath)

    def intersect(self, other):
        """intersect self with other path

        Returns a tuple of lists consisting of the parameter values
        of the intersection points of the corresponding normpath.
        """
        other = other.normpath()

        # here we build up the result
        intersections = ([], [])

        # Intersect all normsubpaths of self with the normsubpaths of
        # other.
        for ia, normsubpath_a in enumerate(self.normsubpaths):
            for ib, normsubpath_b in enumerate(other.normsubpaths):
                for intersection in zip(*normsubpath_a.intersect(normsubpath_b)):
                    intersections[0].append(normpathparam(self, ia, intersection[0]))
                    intersections[1].append(normpathparam(other, ib, intersection[1]))
        return intersections

    def join(self, other):
        """join other normsubpath inplace

        Both normpaths must contain at least one normsubpath.
        The last normsubpath of self will be joined to the first
        normsubpath of other.
        """
        other = other.normpath()

        if not self.normsubpaths:
            raise NormpathException("cannot join to empty path")
        if not other.normsubpaths:
            raise NormpathException("cannot join empty path")
        self.normsubpaths[-1].join(other.normsubpaths[0])
        self.normsubpaths.extend(other.normsubpaths[1:])

    def joined(self, other):
        """return joined self and other

        Both normpaths must contain at least one normsubpath.
        The last normsubpath of self will be joined to the first
        normsubpath of other.
        """
        result = self.copy()
        result.join(other.normpath())
        return result

    # << operator also designates joining
    __lshift__ = joined

    def normpath(self):
        """return a normpath, i.e. self"""
        return self

    def _paramtoarclen_pt(self, params):
        """return arc lengths in pts matching the given params"""
        result = [None] * len(params)
        totalarclen_pt = 0
        distributeparams = self._distributeparams(params)
        for normsubpathindex in range(max(distributeparams.keys()) + 1):
            if distributeparams.has_key(normsubpathindex):
                indices, params = distributeparams[normsubpathindex]
                arclens_pt, normsubpatharclen_pt = self.normsubpaths[normsubpathindex]._paramtoarclen_pt(params)
                for index, arclen_pt in zip(indices, arclens_pt):
                    result[index] = totalarclen_pt + arclen_pt
                totalarclen_pt += normsubpatharclen_pt
            else:
                totalarclen_pt += self.normsubpaths[normsubpathindex].arclen_pt()
        return result

    def paramtoarclen_pt(self, params):
        """return arc length(s) in pts matching the given param(s)"""
    paramtoarclen_pt = _valueorlistmethod(_paramtoarclen_pt)

    def paramtoarclen(self, params):
        """return arc length(s) matching the given param(s)"""
        return [arclen_pt * unit.t_pt for arclen_pt in self._paramtoarclen_pt(params)]
    paramtoarclen = _valueorlistmethod(paramtoarclen)

    def path(self):
        """return path corresponding to normpath"""
        pathitems = []
        for normsubpath in self.normsubpaths:
            pathitems.extend(normsubpath.pathitems())
        return path.path(*pathitems)

    def reversed(self):
        """return reversed path"""
        nnormpath = normpath()
        for i in range(len(self.normsubpaths)):
            nnormpath.normsubpaths.append(self.normsubpaths[-(i+1)].reversed())
        return nnormpath

    def _rotation(self, params):
        """return rotation at params"""
        result = [None] * len(params)
        for normsubpathindex, (indices, params) in self._distributeparams(params).items():
            for index, rotation in zip(indices, self.normsubpaths[normsubpathindex].rotation(params)):
                result[index] = rotation
        return result

    def rotation_pt(self, params):
        """return rotation at param(s) or arc length(s) in pts"""
        return self._rotation(self._convertparams(params, self.arclentoparam_pt))
    rotation_pt = _valueorlistmethod(rotation_pt)

    def rotation(self, params):
        """return rotation at param(s) or arc length(s)"""
        return self._rotation(self._convertparams(params, self.arclentoparam))
    rotation = _valueorlistmethod(rotation)

    def _split_pt(self, params):
        """split path at params and return list of normpaths"""
        if not params:
            return [self.copy()]

        # instead of distributing the parameters, we need to keep their
        # order and collect parameters for splitting of normsubpathitem
        # with index collectindex
        collectindex = None
        for param in params:
            if param.normsubpathindex != collectindex:
                if collectindex is not None:
                    # append end point depening on the forthcoming index
                    if param.normsubpathindex > collectindex:
                        collectparams.append(len(self.normsubpaths[collectindex]))
                    else:
                        collectparams.append(0)
                    # get segments of the normsubpath and add them to the result
                    segments = self.normsubpaths[collectindex].segments(collectparams)
                    result[-1].append(segments[0])
                    result.extend([normpath([segment]) for segment in segments[1:]])
                    # add normsubpathitems and first segment parameter to close the
                    # gap to the forthcoming index
                    if param.normsubpathindex > collectindex:
                        for i in range(collectindex+1, param.normsubpathindex):
                            result[-1].append(self.normsubpaths[i])
                        collectparams = [0]
                    else:
                        for i in range(collectindex-1, param.normsubpathindex, -1):
                            result[-1].append(self.normsubpaths[i].reversed())
                        collectparams = [len(self.normsubpaths[param.normsubpathindex])]
                else:
                    result = [normpath(self.normsubpaths[:param.normsubpathindex])]
                    collectparams = [0]
                collectindex = param.normsubpathindex
            collectparams.append(param.normsubpathparam)
        # add remaining collectparams to the result
        collectparams.append(len(self.normsubpaths[collectindex]))
        segments = self.normsubpaths[collectindex].segments(collectparams)
        result[-1].append(segments[0])
        result.extend([normpath([segment]) for segment in segments[1:]])
        result[-1].extend(self.normsubpaths[collectindex+1:])
        return result

    def split_pt(self, params):
        """split path at param(s) or arc length(s) in pts and return list of normpaths"""
        try:
            for param in params:
                break
        except:
            params = [params]
        return self._split_pt(self._convertparams(params, self.arclentoparam_pt))

    def split(self, params):
        """split path at param(s) or arc length(s) and return list of normpaths"""
        try:
            for param in params:
                break
        except:
            params = [params]
        return self._split_pt(self._convertparams(params, self.arclentoparam))

    def _tangent(self, params, length_pt):
        """return tangent vector of path at params

        If length_pt in pts is not None, the tangent vector will be scaled to
        the desired length.
        """

        result = [None] * len(params)
        tangenttemplate = path.line_pt(0, 0, length_pt, 0).normpath()
        for normsubpathindex, (indices, params) in self._distributeparams(params).items():
            for index, atrafo in zip(indices, self.normsubpaths[normsubpathindex].trafo(params)):
                if atrafo is invalid:
                    result[index] = invalid
                else:
                    result[index] = tangenttemplate.transformed(atrafo)
        return result

    def tangent_pt(self, params, length_pt):
        """return tangent vector of path at param(s) or arc length(s) in pts

        If length in pts is not None, the tangent vector will be scaled to
        the desired length.
        """
        return self._tangent(self._convertparams(params, self.arclentoparam_pt), length_pt)
    tangent_pt = _valueorlistmethod(tangent_pt)

    def tangent(self, params, length=1):
        """return tangent vector of path at param(s) or arc length(s)

        If length is not None, the tangent vector will be scaled to
        the desired length.
        """
        return self._tangent(self._convertparams(params, self.arclentoparam), unit.topt(length))
    tangent = _valueorlistmethod(tangent)

    def _trafo(self, params):
        """return transformation at params"""
        result = [None] * len(params)
        for normsubpathindex, (indices, params) in self._distributeparams(params).items():
            for index, trafo in zip(indices, self.normsubpaths[normsubpathindex].trafo(params)):
                result[index] = trafo
        return result

    def trafo_pt(self, params):
        """return transformation at param(s) or arc length(s) in pts"""
        return self._trafo(self._convertparams(params, self.arclentoparam_pt))
    trafo_pt = _valueorlistmethod(trafo_pt)

    def trafo(self, params):
        """return transformation at param(s) or arc length(s)"""
        return self._trafo(self._convertparams(params, self.arclentoparam))
    trafo = _valueorlistmethod(trafo)

    def transformed(self, trafo):
        """return transformed normpath"""
        return normpath([normsubpath.transformed(trafo) for normsubpath in self.normsubpaths])

    def outputPS(self, file, writer):
        for normsubpath in self.normsubpaths:
            normsubpath.outputPS(file, writer)

    def outputPDF(self, file, writer):
        for normsubpath in self.normsubpaths:
            normsubpath.outputPDF(file, writer)