This file is indexed.

/usr/include/dune/grid/sgrid.hh is in libdune-grid-dev 2.2.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
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
#ifndef DUNE_SGRID_HH
#define DUNE_SGRID_HH

#include <limits>
#include <vector>
#include <stack>

#include <dune/common/fvector.hh>
#include <dune/common/fmatrix.hh>
#include <dune/common/bigunsignedint.hh>
#include <dune/common/collectivecommunication.hh>
#include <dune/common/reservedvector.hh>
#include <dune/geometry/genericgeometry/topologytypes.hh>
#include <dune/grid/common/capabilities.hh>
#include <dune/grid/common/grid.hh>
#include <dune/grid/sgrid/numbering.hh>
#include <dune/grid/common/indexidset.hh>

/*! \file sgrid.hh
  This file documents the DUNE grid interface. We use the special implementation for 
  simple structured grid to illustrate the different classes and their members.
*/

namespace Dune {

//************************************************************************
/*! define name for floating point type used for coordinates in sgrid.
  You can change the type for coordinates by changing this single typedef.
 */
  typedef double sgrid_ctype; 

  // globally define the persistent index type
  const int sgrid_dim_bits = 24;   // bits for encoding each dimension
  const int sgrid_level_bits = 6;  // bits for encoding level number
  const int sgrid_codim_bits = 4;  // bits for encoding codimension

//************************************************************************
// forward declaration of templates

template<int dim, int dimworld, class GridImp> class SGeometry;
template<int codim, int dim, class GridImp> class SEntity;
template<int codim, class GridImp> class SEntityPointer;
template<int codim, class GridImp> class SEntitySeed;
template<int codim, PartitionIteratorType, class GridImp> class SLevelIterator;
template<int dim, int dimworld, class ctype> class SGrid;
template<class GridImp> class SIntersection;
template<class GridImp> class SIntersectionIterator;
template<class GridImp> class SHierarchicIterator;

namespace FacadeOptions
{
  
  template<int dim, int dimworld, class ctype, int mydim, int cdim>
  struct StoreGeometryReference<mydim, cdim,
                                SGrid<dim,dimworld,ctype>, SGeometry>
  {
    static const bool v = false;
  };
  
  template<int dim, int dimworld, class ctype, int mydim, int cdim>
  struct StoreGeometryReference<mydim, cdim,
                                const SGrid<dim,dimworld,ctype>, SGeometry>
  {
    static const bool v = false;
  };
  
}

//************************************************************************
/*!
  SGeometry realizes the concept of the geometric part of a mesh entity.
  
  The geometric part of a mesh entity is a \f$d\f$-dimensional object in \f$\mathbf{R}^w\f$
  where \f$d\f$ corresponds the template parameter dim and \f$w\f$ corresponds to the
  template parameter dimworld.

  The \f$d\f$-dimensional object is a polyhedron given by a certain number of corners, which
  are vectors in \f$\mathbf{R}^w\f$.

  The member function global provides a map from a topologically equivalent polyhedron ("reference element")
  in \f$\mathbf{R}^d\f$ to the given polyhedron. This map can be inverted by the member function local, where
  an appropriate projection is applied first, when \f$d\neq w\f$.

  In the case of a structured mesh discretizing a generalized cube this map is linear
  and can be described as \f[ g(l) = s + \sum\limits_{i=0}^{d-1} l_ir^i\f] where \f$s\in\mathbf{R}^w\f$
  is a given position vector, the \f$r^i\in\mathbf{R}^w\f$ are given direction vectors and \f$l\in\mathbf{R}^d\f$
  is a local coordinate within the reference polyhedron. The direction vectors are assumed to be orthogonal
  with respect to the standard Eucliden inner product.

  The \f$d\f$-dimensional reference polyhedron is given
  by the points \f$\{ (x_0,\ldots,x_{d-1}) \ | \ x_i\in\{0,1\}\ \}\f$.
  
  In order to invert the map for a point \f$p\f$, we have to find a local coordinate \f$l\f$ such
  that \f$g(l)=p\f$. Of course this is only possible if \f$d=w\f$. In the general case \f$d\leq w\f$
  we determine \f$l\f$ such that
  \f[(s,r^k) + \sum\limits_{i=0}^{d-1} l_i (r^i,r^k) = (p,r^k) \ \ \ \forall k=0,\ldots,d-1. \f]

  The resulting system is diagonal since the direction vectors are required to be orthogonal.
 */
template<int mydim, int cdim, class GridImp> 
class SGeometry
: public GeometryDefaultImplementation<mydim,cdim,GridImp,SGeometry>
{
public:
        //! define type used for coordinates in grid module
        typedef typename GridImp::ctype ctype;

        //! return the element type identifier
        GeometryType type () const
        {
          static const GeometryType cubeType(GeometryType::cube,mydim);
          return cubeType;
        }

        //! here we have always an affine geometry
        bool affine() const { return true ; }

        //! return the number of corners of this element. Corners are numbered 0...n-1
        int corners () const
        {
          return 1<<mydim;
        }

        //! return i'th corner of the geometry
        FieldVector< ctype, cdim > corner ( const int i ) const
        {
          return c[i];
        }

        //! return center of the geometry 
        FieldVector<ctype, cdim > center ( ) const
        {
          return centroid;
        }

        //! maps a local coordinate within reference element to global coordinate in element 
        FieldVector<ctype, cdim> global (const FieldVector<ctype, mydim>& local) const;

        //! maps a global coordinate within the element to a local coordinate in its reference element
        FieldVector<ctype, mydim> local (const FieldVector<ctype, cdim>& global) const;

        /*! Integration over a general element is done by integrating over the reference element
          and using the transformation from the reference element to the global element as follows:
          \f[\int\limits_{\Omega_e} f(x) dx = \int\limits_{\Omega_{ref}} f(g(l)) A(l) dl \f] where
          \f$g\f$ is the local to global mapping and \f$A(l)\f$ is the integration element. 

          For a general map \f$g(l)\f$ involves partial derivatives of the map (surface element of
          the first kind if \f$d=2,w=3\f$, determinant of the Jacobian of the transformation for
          \f$d=w\f$, \f$\|dg/dl\|\f$ for \f$d=1\f$).

          For linear elements, the derivatives of the map with respect to local coordinates
          do not depend on the local coordinates and are the same over the whole element.

          For a structured mesh where all edges are parallel to the coordinate axes, the 
          computation is the length, area or volume of the element is very simple to compute.
 
          Each grid module implements the integration element with optimal efficieny. This
          will directly translate in substantial savings in the computation of finite element
          stiffness matrices.
         */
        ctype integrationElement (const FieldVector<ctype, mydim>& local) const
        {
          return volume();
        }

        /** \brief return volume of geometry */
        ctype volume() const;
        
        const FieldMatrix<ctype, mydim, cdim > &jacobianTransposed ( const FieldVector< ctype, mydim > &local ) const;
        const FieldMatrix<ctype,cdim,mydim>& jacobianInverseTransposed (const FieldVector<ctype, mydim>& local) const;

        //! print internal data
        void print (std::ostream& ss, int indent) const;

        /*! The first dim columns of As contain the dim direction vectors.
          Column dim is the position vector. This format allows a consistent
          treatement of all dimensions, including 0 (the vertex).
         */
        void make (FieldMatrix<ctype,mydim+1,cdim>& __As);

        //! constructor
        SGeometry () : builtinverse(false) {}

private:
        FieldVector<ctype, cdim> s;          //!< position of element
        FieldVector<ctype, cdim> centroid;   //!< centroid of element
        FieldMatrix<ctype,mydim,cdim> A;     //!< direction vectors as matrix
        array<FieldVector<ctype, cdim>, 1<<mydim> c; //!< coordinate vectors of corners
        mutable FieldMatrix<ctype,cdim,mydim> Jinv;       //!< storage for inverse of jacobian
        mutable bool builtinverse;
};

//! specialization for dim=0, this is a vertex
template<int cdim, class GridImp> 
class SGeometry<0,cdim,GridImp>
: public GeometryDefaultImplementation<0,cdim,GridImp,SGeometry>
{
public:
        //! define type used for coordinates in grid module
        typedef typename GridImp::ctype ctype;

        //! return the element type identifier
        GeometryType type () const
        {
          static const GeometryType cubeType(GeometryType::cube,0);
          return cubeType;
        }

        //! here we have always an affine geometry
        bool affine() const { return true ; }

        //! return the number of corners of this element. Corners are numbered 0...n-1
        int corners () const
        {
          return 1;
        }

        //! return i'th corner of the geometry
        FieldVector<ctype, cdim > corner ( const int i ) const
        {
          return s;
        }

        //! return center of the geometry 
        FieldVector<ctype, cdim > center ( ) const
        {
          return s;
        }

        //! print internal data
        void print (std::ostream& ss, int indent) const;

        //! constructor, makes element from position and direction vectors
        void make (FieldMatrix<ctype,1,cdim>& __As);

        //! maps a local coordinate within reference element to global coordinate in element 
        FieldVector<ctype, cdim> global (const FieldVector<ctype, 0>& local) const { return corner(0); }

        //! maps a global coordinate within the element to a local coordinate in its reference element
        FieldVector<ctype, 0> local (const FieldVector<ctype, cdim>& global) const { return FieldVector<ctype,0> (0.0); } 

        /*! Integration over a general element is done by integrating over the reference element
          and using the transformation from the reference element to the global element as follows:
          \f[\int\limits_{\Omega_e} f(x) dx = \int\limits_{\Omega_{ref}} f(g(l)) A(l) dl \f] where
          \f$g\f$ is the local to global mapping and \f$A(l)\f$ is the integration element. 

          For a general map \f$g(l)\f$ involves partial derivatives of the map (surface element of
          the first kind if \f$d=2,w=3\f$, determinant of the Jacobian of the transformation for
          \f$d=w\f$, \f$\|dg/dl\|\f$ for \f$d=1\f$).

          For linear elements, the derivatives of the map with respect to local coordinates
          do not depend on the local coordinates and are the same over the whole element.

          For a structured mesh where all edges are parallel to the coordinate axes, the 
          computation is the length, area or volume of the element is very simple to compute.
 
          Each grid module implements the integration element with optimal efficieny. This
          will directly translate in substantial savings in the computation of finite element
          stiffness matrices.
          For this specialisation the integrationElement is always 1. 
         */

        //! constructor with bool argument makes reference element if true, uninitialized else
        SGeometry () {}

        /** \brief This dummy routine always returns 1.0.
         *
         * This routine exists so that algorithms that integrate over grid
         * boundaries can also be compiled for 1d-grids.
         */
        ctype volume() const 
        {
          return 1;
        }

        /** \brief This dummy routine always returns 1.0.
         *
         * This routine exists so that algorithms that integrate over grid
         * boundaries can also be compiled for 1d-grids.
         */
        ctype integrationElement(const FieldVector<ctype, 0>& local) const {
          return volume();
        }
        
        const FieldMatrix<ctype, 0, cdim > &jacobianTransposed ( const FieldVector<ctype, 0 > &local ) const
        {
          static const FieldMatrix<ctype, 0, cdim > dummy ( ctype( 0 ) );
          return dummy;
        }

        const FieldMatrix<ctype,cdim,0>& jacobianInverseTransposed (const FieldVector<ctype, 0>& local) const
        {
          static const FieldMatrix<ctype,cdim,0> dummy( ctype(0) );
          return dummy;
        }

protected:
        FieldVector<ctype, cdim> s;         //!< position of element
};

template <int mydim, int cdim, class GridImp>
inline std::ostream& operator<< (std::ostream& s, SGeometry<mydim,cdim,GridImp>& e)
{
        e.print(s,0);
        return s;
}

//************************************************************************
/*! SEntityBase contains the part of SEntity that can be defined
  without specialization. This is the base for all SEntity classes with dim>0.
 */

template<int codim, int dim, class GridImp, template<int,int,class> class EntityImp>
class SEntityBase :
  public EntityDefaultImplementation<codim,dim,GridImp,EntityImp>
{
  friend class SEntityPointer<codim,GridImp>;
  friend class SIntersectionIterator<GridImp>;
  enum { dimworld = GridImp::dimensionworld };

  typedef typename GridImp::Traits::template Codim< codim >::GeometryImpl GeometryImpl;

public:
  typedef typename GridImp::ctype ctype;
  typedef typename GridImp::template Codim<codim>::Geometry Geometry;
  typedef typename GridImp::PersistentIndexType PersistentIndexType;

  //! level of this element
  int level () const
  {
    return l;
  }

  //! global index is calculated from the index and grid size  
  int globalIndex() const;
  
  /** \brief Return the entity seed which contains sufficient information 
   *  to generate the entity again and uses as less memory as possible 
   */
  SEntitySeed<codim, GridImp> seed () const {
    return SEntitySeed<codim, GridImp>(l, index);
  }
  
  //! return the element type identifier
  GeometryType type () const
  {
    static const GeometryType cubeType(GeometryType::cube,dim-codim);
    return cubeType;
  }

  //! geometry of this entity
  Geometry geometry () const
  {
      if (!builtgeometry) makegeometry();
      
      // return result
      return Geometry( geo );
  }
  
  PartitionType partitionType () const { return InteriorEntity; }

  //! constructor
  SEntityBase (GridImp* _grid, int _l, int _index) :
    grid(_grid),
    l(_l),
    index(_index),
    z(grid->z(l,index,codim)),
    builtgeometry(false) {}

  //! empty constructor
  SEntityBase () :
    builtgeometry(false) // mark geometry as not built
  {}

  //! copy constructor 
  SEntityBase ( const SEntityBase& other ) : 
    grid(other.grid), 
    l(other.l),
    index(other.index), 
    z(other.z), 
    geo(), // do not copy geometry 
    builtgeometry(false) // mark geometry as not built
  {}
    
  //! Reinitialization
  void make (GridImp* _grid, int _l, int _id);

  //! Reinitialization
  void make (int _l, int _id);

  //! geometry of this entity
  void makegeometry () const;
  
  //! globally unique, persistent index
  PersistentIndexType persistentIndex () const 
  {
    return grid->persistentIndex(l, codim, z);
  }

  //! consecutive, codim-wise, level-wise index
  int compressedIndex () const
  {
    return index;
  }

  //! consecutive, codim-wise, level-wise index
  int compressedLeafIndex () const
  {
    // codim != dim -> there are no copies of entities
    // maxlevel -> ids are fine
    if (codim<dim || l==grid->maxLevel())
      return compressedIndex();
    
    // this is a vertex which is not on the finest level
    // move coordinates up to maxlevel (multiply by 2 for each level
    array<int,dim> coord;
    for (int k=0; k<dim; k++)
      coord[k] = z[k]*(1<<(grid->maxLevel()-l));
    
    // compute number with respect to maxLevel
    return grid->n(grid->maxLevel(),coord);
  }

protected:
  // this is how we implement our elements
  GridImp* grid;         //!< grid containes mapper, geometry, etc.
  int l;                 //!< level where element is on
  int index;             //!< my consecutive index
  array<int,dim> z;      //!< my coordinate, number of even components = codim
  mutable GeometryImpl geo;  //!< geometry, is only built on demand
  mutable bool builtgeometry;   //!< true if geometry has been constructed
};


/**
  A Grid is a container of grid entities. An entity is parametrized by
  the codimension.  An entity of codimension c in dimension d is a d-c
  dimensional object.
 */
template<int codim, int dim, class GridImp> 
class SEntity : public SEntityBase<codim,dim,GridImp,SEntity>
{
  typedef Dune::SEntityBase<codim,dim,GridImp,Dune::SEntity> SEntityBase;
  friend class SEntityPointer<codim,GridImp>;
  friend class SIntersectionIterator<GridImp>;
public:
  //! constructor
  SEntity (GridImp* _grid, int _l, int _id) :
    SEntityBase(_grid,_l,_id) {}
};

/**
  A Grid is a container of grid entities. An entity is parametrized
  by the codimension.  An entity of codimension c in dimension d is a
  d-c dimensional object.

  Entities of codimension 0 ("elements") are defined through template
  specialization. Note that this specialization has an extended
  interface compared to the general case

  Entities of codimension 0 allow to visit all neighbors, where a
  neighbor is an entity of codimension 0 which has a common entity of
  codimension 1 with the entity.  These neighbors are accessed via an
  iterator. This allows the implementation of non-matching meshes. The
  number of neigbors may be different from the number of faces/edges
  of an element!
 */

/**
  A Grid is a container of grid entities. An entity is parametrized by
  the codimension.  An entity of codimension c in dimension d is a d-c
  dimensional object.

  Entities of codimension=0 ("Cells") are defined through template
  specialization. Note that this specialization has an extended
  interface compared to the general case
*/
template<int dim, class GridImp>
class SEntity<0,dim,GridImp> : public SEntityBase<0,dim,GridImp,SEntity>
{
  enum { dimworld = GridImp::dimensionworld };
  typedef Dune::SEntityBase<0,dim,GridImp,Dune::SEntity> SEntityBase;
  using SEntityBase::grid;
  using SEntityBase::l;
  using SEntityBase::index;
  using SEntityBase::z;

  typedef typename GridImp::Traits::template Codim< 0 >::GeometryImpl GeometryImpl;
  typedef typename GridImp::Traits::template Codim< 0 >::LocalGeometryImpl LocalGeometryImpl;

  friend class SEntityPointer<0,GridImp>;
  friend class SIntersectionIterator<GridImp>;

public:
  typedef typename GridImp::ctype ctype;
  typedef typename GridImp::template Codim<0>::Geometry Geometry;
  typedef typename GridImp::template Codim<0>::LocalGeometry LocalGeometry;
  template <int cd>
  struct Codim
  {
    typedef typename GridImp::template Codim<cd>::EntityPointer EntityPointer;
  };
  typedef typename GridImp::template Codim<0>::EntityPointer EntityPointer;
  typedef typename GridImp::LeafIntersectionIterator IntersectionIterator;
  typedef typename GridImp::HierarchicIterator HierarchicIterator;
  typedef typename GridImp::PersistentIndexType PersistentIndexType;

  //! make HierarchicIterator a friend
  friend class SHierarchicIterator<GridImp>;
  
  /**
     Intra-element access to entities of codimension cc > codim.
     Return number of entities with codimension cc.
  */
  template<int cc> int count () const; 

  /**
     Provide access to mesh entity i of given codimension. Entities
     are numbered 0 ... count<cc>()-1
  */ 
  template<int cc> typename Codim<cc>::EntityPointer subEntity (int i) const;

  //! subentity compressed index
  int subCompressedIndex (int codim, int i) const
  {
	if (codim==0) return this->compressedIndex();
    // compute subIndex
    return (this->grid)->n(this->l, this->grid->subz(this->z,i,codim));
  }

  /*! subentity leaf index
    \todo add handling of not-leaf vertices
  */
  int subCompressedLeafIndex (int codim, int i) const
  {
	if (codim==0) return this->compressedLeafIndex();

    assert(this->l == this->grid->maxLevel());
    // compute subIndex
    return (this->grid)->n(this->l, this->grid->subz(this->z,i,codim));
  }

  //! subentity persistent index
  PersistentIndexType subPersistentIndex (int codim, int i) const
  {
	if (codim==0) return this->persistentIndex();
    // compute subId
    return this->grid->persistentIndex(this->l, codim, this->grid->subz(this->z,i,codim));
  }
  
  /**
     Intra-level access to intersections with neighboring elements.  A
     neighbor is an entity of codimension 0 which has an entity of
     codimension 1 in commen with this entity. Access to neighbors is
     provided using iterators. This allows meshes to be
     nonmatching. Returns iterator referencing the first neighbor.
   */
  IntersectionIterator ibegin () const;
  IntersectionIterator ileafbegin () const;
  IntersectionIterator ilevelbegin () const;
  //! Reference to one past the last intersection
  IntersectionIterator iend () const;
  IntersectionIterator ileafend () const;
  IntersectionIterator ilevelend () const;

  /**
     @brief Inter-level access to father element on coarser grid.
     
     Assumes that meshes are nested.
  */
  EntityPointer father () const;

  //! returns true if father entity exists
  bool hasFather () const
  {
    return (this->level()>0);
  }

  //! return true if the entity is leaf 
  bool isLeaf () const
    {
      return ( this->grid->maxLevel() == this->level() );
    }

  /**
     @brief Location of this element relative to the reference element element of the father.

     This is sufficient to interpolate all dofs in conforming case.
     Nonconforming may require access to neighbors of father and
     computations with local coordinates.  On the fly case is somewhat
     inefficient since dofs are visited several times.  If we store
     interpolation matrices, this is tolerable. We assume that
     on-the-fly implementation of numerical algorithms is only done for
     simple discretizations.  Assumes that meshes are nested.
  */
  LocalGeometry geometryInFather () const;

  /**
     @brief Inter-level access to son elements on higher levels<=maxLevel.
     
     This is provided for sparsely stored nested unstructured meshes.
     Returns iterator to first son.
  */
  HierarchicIterator hbegin (int maxLevel) const;

  //! Returns iterator to one past the last son
  HierarchicIterator hend (int maxLevel) const;

  // members specific to SEntity
  //! constructor
  SEntity (GridImp* _grid, int _l, int _index) : 
    SEntityBase(_grid,_l,_index),
    built_father(false)
    {}

  SEntity (const SEntity& other ) :
    SEntityBase(other.grid, other.l, other.index ),
    built_father(false)
    {}

  //! Reinitialization
  void make (GridImp* _grid, int _l, int _id)
    {
      SEntityBase::make(_grid,_l,_id);
      built_father = false;
    }

  //! Reinitialization
  void make (int _l, int _id)
    {
      SEntityBase::make(_l,_id);
      built_father = false;
    }
  
private:

  SEntity();
  
  mutable bool built_father;
  mutable int father_index;
  mutable LocalGeometryImpl in_father_local;
  void make_father() const;
};


//************************************************************************
/*! Mesh entities of codimension 0 ("elements") allow to visit all entities of
  codimension 0 obtained through nested, hierarchic refinement of the entity.
  Iteration over this set of entities is provided by the HIerarchicIterator,
  starting from a given entity.
  This is redundant but important for memory efficient implementations of unstructured
  hierarchically refined meshes.
 */
struct SHierarchicStackElem {
  int l;
  int index;
  SHierarchicStackElem () : l(-1), index(-1) {}
  SHierarchicStackElem (int _l, int _index) {l=_l; index=_index;}
  bool operator== (const SHierarchicStackElem& s) const {return !operator!=(s);}
  bool operator!= (const SHierarchicStackElem& s) const {return l!=s.l || index!=s.index;}
};

template<class GridImp>
class SHierarchicIterator :
  public Dune::SEntityPointer <0,GridImp>
{
  friend class SHierarchicIterator<const GridImp>;
  enum { dim = GridImp::dimension };
  enum { dimworld = GridImp::dimensionworld };
  typedef Dune::SEntityPointer<0,GridImp> SEntityPointer;
  using SEntityPointer::realEntity;
  using SEntityPointer::grid;
  using SEntityPointer::l;
  using SEntityPointer::index;
public:
  typedef typename GridImp::template Codim<0>::Entity Entity;
  typedef typename GridImp::ctype ctype;

  //! increment
  void increment();

  /*! constructor. Here is how it works: If with_sons is true, push start
    element and all its sons on the stack, so the initial element is popped
    last. For an end iterator, push the starting element and no sons. Then
    the iteration will stop when both iterators have the same id AND the
    stack is empty
  */
  SHierarchicIterator (GridImp* _grid,
                       const Dune::SEntity<0,GridImp::dimension,GridImp>& _e,
                       int _maxLevel, bool makeend) :
    SEntityPointer(_grid,_e.level(),_e.compressedIndex())
    {
      // without sons, we are done
      // (the end iterator is equal to the calling iterator)
      if (makeend) return;
      
      // remember element where begin has been called
      orig_l = this->entity().level();
      orig_index = _grid->getRealImplementation(this->entity()).compressedIndex();
      
      // push original element on stack
      SHierarchicStackElem originalElement(orig_l, orig_index);
      stack.push(originalElement);
      
      // compute maxLevel
      maxLevel = std::min(_maxLevel,this->grid->maxLevel());
      
      // ok, push all the sons as well
      push_sons(orig_l,orig_index);
      
      // and pop the first son
      increment();
    }

private:
  int maxLevel;                //!< maximum level of elements to be processed
  int orig_l, orig_index;         //!< element where begin was called (the root of the tree to be processed)

  //!< stack holding elements to be processed
  std::stack<SHierarchicStackElem, Dune::ReservedVector<SHierarchicStackElem,GridImp::MAXL> > stack;
  
  void push_sons (int level, int fatherid); //!< push all sons of this element on the stack
};

//************************************************************************
/*! Mesh entities of codimension 0 ("elements") allow to visit all neighbors, where
  a neighbor is an entity of codimension 0 which has a common entity of codimension 1 with the entity.
  These neighbors are accessed via a IntersectionIterator. This allows the implementation of
  non-matching meshes. The number of neigbors may be different from the number of faces/edges
  of an element!
 */
template<class GridImp>
class SIntersectionIterator
{
  enum { dim=GridImp::dimension };
  enum { dimworld=GridImp::dimensionworld };

  typedef typename GridImp::Traits::template Codim< 1 >::GeometryImpl GeometryImpl;
  typedef typename GridImp::Traits::template Codim< 1 >::LocalGeometryImpl LocalGeometryImpl;

public:
  typedef typename GridImp::template Codim<0>::Entity Entity;
  typedef typename GridImp::template Codim<0>::EntityPointer EntityPointer;
  typedef typename GridImp::template Codim<1>::Geometry Geometry;
  typedef typename GridImp::template Codim<1>::LocalGeometry LocalGeometry;
  typedef Dune::SIntersection<GridImp> IntersectionImp;
  typedef Dune::Intersection<const GridImp, Dune::SIntersection> Intersection;
  //! know your own dimension
  enum { dimension=dim };
  //! know your own dimension of world
  enum { dimensionworld=dimworld };
  //! define type used for coordinates in grid module
  typedef typename GridImp::ctype ctype;

  //! equality
  bool equals(const SIntersectionIterator<GridImp>& i) const;
  //! increment
  void increment();

  //! \brief dereferencing
  const Intersection & dereference() const
  {
    return intersection;
  }

  //! return EntityPointer to the Entity on the inside of this intersection
  //! (that is the Entity where we started this Iterator)
  EntityPointer inside() const;

  //! return EntityPointer to the Entity on the outside of this intersection
  //! (that is the neighboring Entity)
  EntityPointer outside() const;
  
  //! return true if intersection is with boundary.
  bool boundary () const;

  //! return true if intersection is conform.
  bool conforming () const;

  int boundaryId () const {
    if (boundary()) return count + 1;
    return 0;
  }

  int boundarySegmentIndex () const {
    if (boundary())
      return grid->boundarySegmentIndex(self.level(), count, zred);
    return -1;
  }
  
  //! return true if neighbor on this level exists
  bool neighbor () const;

  //! return outer normal
  FieldVector<ctype, GridImp::dimensionworld> outerNormal (const FieldVector<ctype, GridImp::dimension-1>& local) const
    {
      return unitOuterNormal(local);
    }
  //! return unit outer normal
  FieldVector<ctype, GridImp::dimensionworld> unitOuterNormal (const FieldVector<ctype, GridImp::dimension-1>& local) const
    {
      return centerUnitOuterNormal();
    }
  //! return unit outer normal at center of intersection geometry
  FieldVector<ctype, GridImp::dimensionworld> centerUnitOuterNormal () const
    {
      // while we are at it, compute normal direction
      FieldVector<ctype, dimworld> normal(0.0);
      if (count%2)
        normal[count/2] =  1.0; // odd
      else
        normal[count/2] = -1.0; // even
      
      return normal; 
    }
  //! return integration outer normal
  FieldVector<ctype, GridImp::dimensionworld> integrationOuterNormal (const FieldVector<ctype, GridImp::dimension-1>& local) const
    {
        FieldVector<ctype, dimworld> n = unitOuterNormal(local);
        n *= geometry().integrationElement(local);
        return n;
    }

  /*! intersection of codimension 1 of this neighbor with element where iteration started.
    Here returned element is in LOCAL coordinates of the element where iteration started.
  */
  LocalGeometry geometryInInside () const;
  /*! intersection of codimension 1 of this neighbor with element where iteration started. 
    Here returned element is in LOCAL coordinates of neighbor
  */
  LocalGeometry geometryInOutside () const;
  /*! intersection of codimension 1 of this neighbor with element where iteration started. 
    Here returned element is in GLOBAL coordinates of the element where iteration started.
  */
  Geometry geometry () const;

  /** \brief obtain the type of reference element for this intersection */
  GeometryType type () const
  {
    static const GeometryType cubeType(GeometryType::cube,dim-1);
    return cubeType;
  }

  //! local index of codim 1 entity in self where intersection is contained in 
  int indexInInside () const;
  //! local index of codim 1 entity in neighbor where intersection is contained in 
  int indexInOutside () const;

  //! constructor
  SIntersectionIterator (GridImp* _grid, const SEntity<0,dim,GridImp >* _self, int _count) :
    self(*_self), ne(self), grid(_grid),
    partition(_grid->partition(grid->getRealImplementation(ne).l,_self->z)),
    zred(_grid->compress(grid->getRealImplementation(ne).l,_self->z)),
    intersection(IntersectionImp(*this))
  {
    // make neighbor
    make(_count);
  }

  SIntersectionIterator (const SIntersectionIterator & other) :
    self(other.self), ne(other.ne), grid(other.grid),
    partition(other.partition), zred(other.zred),
    count(other.count), valid_count(other.valid_count),
    valid_nb(other.valid_nb), is_on_boundary(other.is_on_boundary),
    built_intersections(false),
    intersection(IntersectionImp(*this))
  {
  }
  
  //! assignment operator
  SIntersectionIterator& operator = (const SIntersectionIterator& other)
    {
      /* We can't assign the grid */
      assert(grid == other.grid);
      
      /* Assign data from other */
      self = other.self;
      ne = other.ne;
      partition = other.partition;
      zred = other.zred;
      count = other.count;
      valid_count = other.valid_count;
      valid_nb = other.valid_nb;
      is_on_boundary = other.is_on_boundary;

      /* mark cached data as invalid */
      built_intersections = false;

      return *this;
    }
  
private:
  void make (int _count) const;           //!< reinitialze iterator with given neighbor
  void makeintersections () const;        //!< compute intersections
  EntityPointer self;                     //!< EntityPointer for myself
  mutable EntityPointer ne;               //!< EntityPointer for neighbor
  const GridImp * grid;                   //!< Pointer to the grid
  int partition;                          //!< partition number of self, needed for coordinate expansion
  array<int,dim> zred;                    //!< reduced coordinates of myself, allows easy computation of neighbors
  mutable int count;                      //!< number of neighbor
  mutable bool valid_count;               //!< true if count is in range
  mutable bool valid_nb;                  //!< true if nb is initialized
  mutable bool is_on_boundary;            //!< true if neighbor is otside the domain
  mutable bool built_intersections;       //!< true if all intersections have been built
  mutable LocalGeometryImpl is_self_local;    //!< intersection in own local coordinates
  mutable GeometryImpl is_global;             //!< intersection in global coordinates, map consistent with is_self_local
  mutable LocalGeometryImpl is_nb_local;      //!< intersection in neighbors local coordinates
  Intersection intersection;
};

template<class GridImp>
class SIntersection
{
  enum { dim=GridImp::dimension };
  enum { dimworld=GridImp::dimensionworld };
public:
  typedef typename GridImp::template Codim<0>::Entity Entity;
  typedef typename GridImp::template Codim<0>::EntityPointer EntityPointer;
  typedef typename GridImp::template Codim<1>::Geometry Geometry;
  typedef typename Geometry::LocalCoordinate LocalCoordinate;
  typedef typename Geometry::GlobalCoordinate GlobalCoordinate;
  typedef typename GridImp::template Codim<1>::LocalGeometry LocalGeometry;
  typedef Dune::Intersection<const GridImp, Dune::SIntersectionIterator> Intersection;
  //! know your own dimension
  enum { dimension=dim };
  //! know your own dimension of world
  enum { dimensionworld=dimworld };
  //! define type used for coordinates in grid module
  typedef typename GridImp::ctype ctype;

  bool boundary () const
  {
    return is.boundary();
  }

  /*! @brief Identifier for boundary segment from macro grid. */
  int boundaryId () const
  {
    return is.boundaryId();
  }

  /*! @brief index of the boundary segment within the macro grid  */
  size_t boundarySegmentIndex () const
  {
    return is.boundarySegmentIndex();
  }

  /*! @brief return true if intersection is shared with another element. */
  bool neighbor () const 
  {
    return is.neighbor();
  }

  /*! @brief return EntityPointer to the Entity on the inside of this intersection. */
  EntityPointer inside() const
  {
    return is.inside();
  }

  /*! @brief return EntityPointer to the Entity on the outside of this intersection. */
  EntityPointer outside() const
  {
    return is.outside();
  }
  
  /*! @brief return true if intersection is conform. */ 
  bool conforming () const 
  {
    return is.conforming();
  }

  /*! @brief geometrical information about this intersection in local coordinates of the inside() entity. */
  LocalGeometry geometryInInside () const
  {
    return is.geometryInInside();
  }

  /*! @brief geometrical information about this intersection in local coordinates of the outside() entity. */
  LocalGeometry geometryInOutside () const
  {
    return is.geometryInOutside();
  }

  /*! @brief geometrical information about the intersection in global coordinates. */
  Geometry geometry () const
  {
    return is.geometry();
  }

  /*! @brief obtain the type of reference element for this intersection */
  GeometryType type () const
  {
    return is.type();
  }

  /*! @brief Local index of codim 1 entity in the inside() entity where intersection is contained in */
  int indexInInside () const
  {
    return is.indexInInside();
  }

  /*! @brief Local index of codim 1 entity in outside() entity where intersection is contained in */
  int indexInOutside () const
  {
    return is.indexInOutside();
  }

  /*! @brief Return an outer normal (length not necessarily 1) */
  GlobalCoordinate outerNormal (const LocalCoordinate& local) const
  {
    return is.outerNormal(local);
  }

  /*! @brief return outer normal scaled with the integration element */
  GlobalCoordinate integrationOuterNormal (const LocalCoordinate& local) const
  {
    return is.integrationOuterNormal(local);
  }

  /*! @brief Return unit outer normal (length == 1)  */
  GlobalCoordinate unitOuterNormal (const LocalCoordinate& local) const
  {
    return is.unitOuterNormal(local);
  }

  /*! @brief Return unit outer normal (length == 1) */
  GlobalCoordinate centerUnitOuterNormal () const
  {
    return is.centerUnitOuterNormal();
  }

  //! constructor
  SIntersection (const SIntersectionIterator<GridImp> & is_) : is(is_) {}
  
private:
#ifndef DOXYGEN // doxygen can't handle this recursive usage
  const SIntersectionIterator<GridImp> & is;
#endif
};

//************************************************************************

/** \brief a stack of pointers with auto destruction if the stack is
    destructed
*/
template <class T>
class AutoPtrStack : public std::stack<T*>
{
public:
    ~AutoPtrStack()
    {
        while(! this->empty())
        {
            T* e = this->top();
            delete e;
            this->pop();
        }
    }
};

/*! Acts as a pointer to an  entities of a given codimension.
 */
template<int codim, class GridImp>
class SEntityPointer
{
  enum { dim = GridImp::dimension };
  friend class SIntersectionIterator<GridImp>;
public:
  typedef SEntityPointer<codim,GridImp> EntityPointerImp;
  typedef typename GridImp::template Codim<codim>::Entity Entity;
  //! codimension of entity pointer 
  enum { codimension = codim };
  
  //! equality
  bool equals(const SEntityPointer<codim,GridImp>& i) const;
  //! dereferencing
  Entity& dereference() const;
  //! ask for level of entity
  int level () const;

  //! constructor
  SEntityPointer (GridImp * _grid, int _l, int _index) :
    grid(_grid), l(_l), index(_index), 
    e(0) 
  {
  }

  //! constructor
  SEntityPointer (const SEntity<codim,dim,GridImp> & _e) :
    grid(_e.grid), l(_e.l), index(_e.index),
    e(0)
  {
  }

  //! constructor
  SEntityPointer (const SEntityPointer<codim,GridImp>& other) :
    grid(other.grid), l(other.l), index(other.index),
    e( 0 )
  {
  }

  //! destructor pointer 
  ~SEntityPointer()
  {
    if( e )
      enStack().push( e );
#ifndef NDEBUG 
    index = -1;
#endif
  }

  //! assignment operator 
  SEntityPointer& operator = (const SEntityPointer& other)
  {
    grid = other.grid;
    l = other.l;
    index = other.index;

    // free current entity
    if( e )
      enStack().push( e );
    e = 0;

    return *this;
  }

protected:
  inline SEntity<codim,dim,GridImp>& realEntity() const
  {
    return grid->getRealImplementation(entity());
  }
  
  inline Entity& entity() const
  {
    if( ! e )
    {
      e = getEntity( grid, l, index );
    }
    return *e;
  }

  typedef AutoPtrStack< Entity > EntityStackType;
  static inline EntityStackType& enStack()
  {
    static EntityStackType eStack;
    return eStack;
  }

  inline Entity* getEntity(GridImp* _grid, int _l, int _id ) const
  {
    // get stack reference 
    EntityStackType& enSt = enStack();

    if( enSt.empty() )
    {
      return (new Entity(SEntity<codim,dim,GridImp>(_grid, _l, _id)));
    }
    else
    {
      Entity* e = enSt.top();
      enSt.pop();
      grid->getRealImplementation(*e).make(_grid, _l,_id);
      return e;
    }
  }

  GridImp* grid;                 //!< my grid
  int l;                         //!< level where element is on
  mutable int index;             //!< my consecutive index
  mutable Entity* e;             //!< virtual entity
};

/*! describes the minimal information necessary to create a fully functional SEntity
 */
template<int codim, class GridImp>
class SEntitySeed
{
  enum { dim = GridImp::dimension };
public:
  enum { codimension = codim };
  
  //! constructor
  SEntitySeed (int l, int index) :
    _l(l), _index(index)
  {}

  int level () const { return this->_l; }
  int index () const { return this->_index; }

private:
  int _l;                         //!< level where element is on
  int _index;                     //!< my consecutive index
};

//************************************************************************


/*! Enables iteration over all entities of a given codimension and level of a grid.
 */
template<int codim, PartitionIteratorType pitype, class GridImp>
class SLevelIterator :
  public Dune::SEntityPointer <codim,GridImp>
{
  friend class SLevelIterator<codim, pitype,const GridImp>;
  enum { dim = GridImp::dimension };
  typedef Dune::SEntityPointer<codim,GridImp> SEntityPointer;
  using SEntityPointer::realEntity;
  using SEntityPointer::l;
  using SEntityPointer::index;
public:
  typedef typename GridImp::template Codim<codim>::Entity Entity;

  //! increment
  void increment();

  //! constructor
  SLevelIterator (GridImp * _grid, int _l, int _id) :
    SEntityPointer(_grid,_l,_id) {}
};


//========================================================================
/*!
  \brief implementation of index set
  
 */
//========================================================================

template<class GridImp>
class SGridLevelIndexSet : public IndexSet<GridImp,SGridLevelIndexSet<GridImp> >
{
  typedef SGridLevelIndexSet< GridImp > This;
  typedef IndexSet< GridImp, This > Base;

  enum { dim = GridImp::dimension };

public:

  //! constructor stores reference to a grid and level
  SGridLevelIndexSet ( const GridImp &g, int l )
  : grid( g ),
    level( l )
  {
    // TODO move list of geometrytypes to grid, can be computed static (singleton)
    // contains a single element type;
	for (int codim=0; codim<=GridImp::dimension; codim++)
	  mytypes[codim].push_back(GeometryType(GeometryType::cube,GridImp::dimension-codim));
  }

  //! get index of an entity
  template<int cd>
  int index (const typename GridImp::Traits::template Codim<cd>::Entity& e) const 
  {
      return grid.getRealImplementation(e).compressedIndex(); 
  }

  template< int cc >
  int subIndex ( const typename GridImp::Traits::template Codim< cc >::Entity &e,
                 int i, unsigned int codim ) const
  {
      if( cc == 0 )
          return grid.getRealImplementation(e).subCompressedIndex(codim, i);
      else
          DUNE_THROW( NotImplemented, "subIndex for higher codimension entity not implemented for SGrid." );
  }

  // return true if the given entity is contained in \f$E\f$.
  template< class EntityType >
  bool contains ( const EntityType &e ) const
  {
    return (e.level() == level);
  }

  //! get number of entities of given type and level (the level is known to the object)
  int size (GeometryType type) const
  {
    return grid.size( level, type );
  }
  
  //! return size of set for a given codim 
  int size (int codim) const
  {
    return grid.size( level, codim );
  }

  //! deliver all geometry types used in this grid
  const std::vector<GeometryType>& geomTypes (int codim) const
  {
	return mytypes[codim];
  }

private:
  const GridImp& grid;
  int level;
  std::vector<GeometryType> mytypes[GridImp::dimension+1];
};

// Leaf Index Set

template<class GridImp>
class SGridLeafIndexSet : public IndexSet<GridImp,SGridLeafIndexSet<GridImp> >
{
  typedef SGridLeafIndexSet< GridImp > This;
  typedef IndexSet< GridImp, This > Base;

  enum { dim = GridImp::dimension };

public:

  //! constructor stores reference to a grid and level
  explicit SGridLeafIndexSet ( const GridImp &g )
  : grid( g )
  {
    // TODO move list of geometrytypes to grid, can be computed static (singleton)
    // contains a single element type;
	for (int codim=0; codim<=dim; codim++)
	  mytypes[codim].push_back(GeometryType(GeometryType::cube,dim-codim));
  }

  //! get index of an entity
  /*
    We use the remove_const to extract the Type from the mutable class,
    because the const class is not instantiated yet.
  */
  template<int cd>
  int index (const typename remove_const<GridImp>::type::Traits::template Codim<cd>::Entity& e) const 
  {
	return grid.getRealImplementation(e).compressedLeafIndex(); 
  }

  template< int cc >
  int subIndex ( const typename GridImp::Traits::template Codim< cc >::Entity &e,
                 int i, unsigned int codim ) const
  {
      if( cc == 0 )
          return grid.getRealImplementation(e).subCompressedIndex(codim, i);
      else
          DUNE_THROW( NotImplemented, "subIndex for higher codimension entity not implemented for SGrid." );
  }

  //! get number of entities of given type
  int size (GeometryType type) const
  {
    return grid.size( grid.maxLevel(), type );
  }

  //! return size of set for a given codim 
  int size (int codim) const
  {
    return grid.size( grid.maxLevel(), codim );
  }

  // return true if the given entity is contained in \f$E\f$.
  template< class EntityType >
  bool contains ( const EntityType &e ) const
  {
    return (e.level() == grid.maxLevel());
  }

  //! deliver all geometry types used in this grid
  const std::vector<GeometryType>& geomTypes (int codim) const
  {
	return mytypes[codim];
  }

private:
  const GridImp& grid;
  std::vector<GeometryType> mytypes[dim+1];
};


//========================================================================
/*!
  \brief persistent, globally unique Ids
  
 */
//========================================================================

template<class GridImp>
class SGridGlobalIdSet :
  public IdSet<GridImp,SGridGlobalIdSet<GridImp>, typename remove_const<GridImp>::type::PersistentIndexType>
  /*
    We used the remove_const to extract the Type from the mutable class,
    because the const class is not instantiated yet.
  */
{
  typedef SGridGlobalIdSet< GridImp > This;

public:
  
  //! import default implementation of subId<cc>
  //! \todo remove after next release
  using IdSet<GridImp,SGridGlobalIdSet<GridImp>, typename remove_const<GridImp>::type::PersistentIndexType>::subId;

  //! define the type used for persisitent indices
  /*
    We use the remove_const to extract the Type from the mutable class,
    because the const class is not instantiated yet.
  */
  typedef typename remove_const<GridImp>::type::PersistentIndexType IdType;

  //! constructor stores reference to a grid
  explicit SGridGlobalIdSet ( const GridImp &g )
  : grid( g )
  {}

  //! get id of an entity
  /*
    We use the remove_const to extract the Type from the mutable class,
    because the const class is not instantiated yet.
  */
  template<int cd>
  IdType id (const typename remove_const<GridImp>::type::Traits::template Codim<cd>::Entity& e) const 
  {
	  return grid.getRealImplementation(e).persistentIndex();
  }

  //! get id of subentity
  /*
    We use the remove_const to extract the Type from the mutable class,
    because the const class is not instantiated yet.
  */
  IdType subId ( const typename remove_const< GridImp >::type::Traits::template Codim< 0 >::Entity &e,
                 int i, unsigned int codim ) const
  {
      return grid.getRealImplementation(e).subPersistentIndex(codim, i);
  }

private:
  const GridImp& grid;
};


template<int dim, int dimworld, class ctype>
struct SGridFamily
{
  typedef GridTraits<dim,dimworld,Dune::SGrid<dim,dimworld,ctype>,
                     SGeometry,SEntity,
                     SEntityPointer,SLevelIterator,
                     SIntersection, // leaf intersection
                     SIntersection, // level intersection
                     SIntersectionIterator, // leaf  intersection iter 
                     SIntersectionIterator, // level intersection iter
                     SHierarchicIterator,
                     SLevelIterator,
					 SGridLevelIndexSet<const SGrid<dim,dimworld,ctype> >,
					 SGridLeafIndexSet<const SGrid<dim,dimworld,ctype> >,
					 SGridGlobalIdSet<const SGrid<dim,dimworld,ctype> >,
					 bigunsignedint<dim*sgrid_dim_bits+sgrid_level_bits+sgrid_codim_bits>,
					 SGridGlobalIdSet<const SGrid<dim,dimworld,ctype> >,
					 bigunsignedint<dim*sgrid_dim_bits+sgrid_level_bits+sgrid_codim_bits>, 
					 CollectiveCommunication<Dune::SGrid<dim,dimworld,ctype> >,
                     DefaultLevelGridViewTraits, DefaultLeafGridViewTraits,
                     SEntitySeed>
  Traits;
};


//************************************************************************
/**
 \brief [<em> provides \ref Dune::Grid </em>]
 \brief A structured mesh in d dimensions consisting of "cubes" (pilot implementation of the %Dune grid interface, for debugging only).
 \ingroup GridImplementations

        This module describes the pilot implementation of the %Dune grid interface.
        It implements the grid interface for simple structured meshes.

        \warning SGrid is slow. It is intended for debugging only.
        
        The following class diagram shows how the classes are related with
        each other:

        \image html sgridclasses.png "Class diagram for classes in the grid interface"
        \image latex sgridclasses.eps "Class diagram for classes in the grid interface" width=\textwidth

        Short description of the classes:

        - SGeometry is a class template providing the geometric part of a grid entity, i.e. a general polyhedron
        with a mapping from a reference polyhedron to the actual polyhedron.

        - SLevelIterator is a class template which allows to iterate over all grid entities of a given
        codimension and level.

        - SEntity is a class template realizing the grid entities. Grid entities are the constituents
        of a grid. Grid entities of codimension 0 and codimension dim are defines through specialization.
        Entities can be used as template parameters to generic algorithms. Each entity must therefore
        provide the nested classes Geometry, LevelIterator, HierarchicIterator and IntersectionIterator.
        Geometry and LevelIterator are derived from the classes SELement and SLevelIterator.
        Note that entities of codimension 0 and dim have an extended interface.

        - SEntity::IntersectionIterator provides access to all entities of codimension 0 sharing an object of codimension 1
        with the given entity of codimension 0. This interface covers nonmatching grids.

        - SEntity::HierarchicIterator provides access to the sons of an entity of codimension 0.

        - SGrid is conceptualized as a container of grid entities of various codimensions. Since grids
        are used as template parameters to generic algorithms they must include the nested classes 
        LevelIterator and Entity which are derived from SLevelIterator and SEntity.

  A Grid is a container of grid entities. Given a dimension dim these entities have a 
  codimension codim with 0 <= codim <= dim. 

  The Grid is assumed to be hierachically refined and nested. It enables iteration over
  entities of a given level and codimension.

  All information is provided to allocate degrees of freedom in appropriate vector
  data structures.

  \note When SGrid is instantiated with dimworld strictly greater than dim, the result is a
  dim-dimensional structured grid which is embedded in the first dim components of 
  dimworld-dimensional Euclidean space.
 */
template<int dim, int dimworld, typename _ctype = sgrid_ctype>
class SGrid : public GridDefaultImplementation <dim,dimworld,_ctype,SGridFamily<dim,dimworld,_ctype> >
{
public:
  typedef SGridFamily<dim,dimworld,_ctype> GridFamily;
  typedef bigunsignedint<dim*sgrid_dim_bits+sgrid_level_bits+sgrid_codim_bits> PersistentIndexType;

  // need for friend declarations in entity
  typedef SGridLevelIndexSet<SGrid<dim,dimworld> > LevelIndexSetType;
  typedef SGridLeafIndexSet<SGrid<dim,dimworld> > LeafIndexSetType;
  typedef SGridGlobalIdSet<SGrid<dim,dimworld> > GlobalIdSetType;
  
  typedef typename SGridFamily<dim,dimworld,_ctype>::Traits Traits;

  //! maximum number of levels allowed
  enum { MAXL=32 };

  //! define type used for coordinates in grid module
  typedef _ctype ctype;

  // constructors

  /*! @brief Make an SGrid from extend and number of cells per direction

  \param[in] N_ number of cells in each direction on coarsest level
  \param[in] H_ extend of the unit cube in each dimension

  Note: The origin of the cube is always at (0,0,...,0), only the extend is given.
  */
  SGrid (const int * const N_, const ctype * const H_);
  
  /*! @brief Make an SGrid from position, extend and number of cells per direction

  \param[in] N_ number of cells in each direction on coarsest level
  \param[in] L_ position of origin of the cube
  \param[in] H_ position of the upper right corner of the cube

  */
  SGrid (const int * const N_, const ctype * const L_, const ctype * const H_);

  /*! @brief Make an SGrid from position, extend and number of cells per direction

  \param[in] N_ number of cells in each direction on coarsest level
  \param[in] L_ position of origin of the cube
  \param[in] H_ position of the upper right corner of the cube

  Note: This constructor uses FieldVectors instead of built-in arrays. This is compatible 
        with the YaspGrid class.
  */
  SGrid (FieldVector<int,dim> N_, FieldVector<ctype,dim> L_, FieldVector<ctype,dim> H_);

  //! @brief empty constructor making grid of unit square discretized with one cell 
  SGrid ();

  //! @brief SGrid destructor 
  ~SGrid ();

  /*! Return maximum level defined in this grid. Levels are numbered
        0 ... maxLevel with 0 the coarsest level.   */
  int maxLevel() const;

  //! Iterator to first entity of given codim on level
  template<int cd, PartitionIteratorType pitype>
  typename Traits::template Codim<cd>::template Partition<pitype>::LevelIterator lbegin (int level) const;

  //! one past the end on this level
  template<int cd, PartitionIteratorType pitype>
  typename Traits::template Codim<cd>::template Partition<pitype>::LevelIterator lend (int level) const;

  //! Iterator to first entity of given codim on level
  template<int cd>
  typename Traits::template Codim<cd>::template Partition<All_Partition>::LevelIterator lbegin (int level) const
    {
      return lbegin<cd,All_Partition>(level);
    }

  //! one past the end on this level
  template<int cd>
  typename Traits::template Codim<cd>::template Partition<All_Partition>::LevelIterator lend (int level) const
    {
      return lend<cd,All_Partition>(level);
    }

  //! return LeafIterator which points to the first entity
  template<int cd, PartitionIteratorType pitype>
  typename Traits::template Codim<cd>::template Partition<pitype>::LeafIterator leafbegin () const;

  //! one past the end on the leaf level
  template<int cd, PartitionIteratorType pitype>
  typename Traits::template Codim<cd>::template Partition<pitype>::LeafIterator leafend () const;

  //! return LeafIterator which points to the first entity
  template<int cd>
  typename Traits::template Codim<cd>::template Partition<All_Partition>::LeafIterator leafbegin () const
    {
      return leafbegin<cd,All_Partition>();
    }

  //! return LeafIterator which points behind the last entity
  template<int cd>
  typename Traits::template Codim<cd>::template Partition<All_Partition>::LeafIterator leafend () const
    {
      return leafend<cd,All_Partition>();
    }

  // \brief obtain EntityPointer from EntitySeed. */
  template <typename Seed>
  typename Traits::template Codim<Seed::codimension>::EntityPointer
  entityPointer(const Seed& seed) const
  {
    enum { codim = Seed::codimension };
    return SEntityPointer<codim,const SGrid<dim,dimworld> >(this,seed.level(),seed.index());
  }

  /*! The communication interface
        @tparam T array class holding data associated with the entities
        @tparam P type used to gather/scatter data in and out of the message buffer
        @tparam codim communicate entites of given codim
        @param t array holding data associated with the entities
        @param iftype one of the predifined interface types, throws error if it is not implemented
        @param dir choose beetween forward and backward communication
        @param level communicate for entities on the given level

        Implements a generic communication function sending an object of type P for each entity
    in the intersection of two processors. P has two methods gather and scatter that implement
    the protocol. Therefore P is called the "protocol class".
   */
  template<class T, template<class> class P, int codim>
  void communicate (T& t, InterfaceType iftype, CommunicationDirection dir, int level)
  {
          // SGrid is sequential and has no periodic boundaries, so do nothing ...
          return;
  }

  //! number of grid entities per level and codim
  int size (int level, int codim) const;

  //! number of leaf entities per codim in this process
  int size (int codim) const
  {
	return size(maxLevel(),codim);
  }

  //! number of entities per level and geometry type in this process
  int size (int level, GeometryType type) const
  {
      return (type.isCube()) ? size(level,dim-type.dim()) : 0;
  }

  //! number of leaf entities per codim and geometry type in this process
  int size (GeometryType type) const
  {
	return size(maxLevel(),type);
  }

  //! \brief returns the number of boundary segments within the macro grid 
  size_t numBoundarySegments () const
  {
    return boundarysize;
  }

  //! number of grid entities of all level for given codim
  int global_size (int codim) const;

  //! return size (= distance in graph) of overlap region
  int overlapSize (int level, int codim)
  {
        return 0;
  }

  //! return size (= distance in graph) of ghost region
  int ghostSize (int level, int codim)
  {
        return 0;
  }

  // these are all members specific to sgrid

  /** \brief Refine mesh globally by one refCount levels */
  void globalRefine (int refCount);

    /** \brief Get number of elements in each coordinate direction */
    const array<int, dim>& dims(int level) const {
        return N[level];
    }

    /** \brief Get lower left corner */
    const FieldVector<ctype, dimworld>& lowerLeft() const {
        return low;
    }

    /** \brief Get upper right corner */
    FieldVector<ctype, dimworld> upperRight() const {
        return H;
    }

  //! map adapt to global refine
  bool adapt ()    
  {
	globalRefine(1);
	return true; 
  }
  
  // The new index sets from DDM 11.07.2005
  const typename Traits::GlobalIdSet& globalIdSet() const
  {
	return *theglobalidset;
  }
  
  const typename Traits::LocalIdSet& localIdSet() const
  {
	return *theglobalidset;
  }

  const typename Traits::LevelIndexSet& levelIndexSet(int level) const
  {
	assert(level>=0 && level<=maxLevel());
	return *(indexsets[level]);
  }

  const typename Traits::LeafIndexSet& leafIndexSet() const
  {
	return *theleafindexset;
  }

  /*!
    @name dummy parallel functions
    @{
  */
  template<class DataHandle>
  void communicate (DataHandle& data, InterfaceType iftype, CommunicationDirection dir, int level) const
  {
  }

  template<class DataHandle>
  void communicate (DataHandle& data, InterfaceType iftype, CommunicationDirection dir) const
  {
  }

  const CollectiveCommunication<SGrid>& comm () const
  {
	return ccobj;
  }

  //! return size (= distance in graph) of overlap region
  int overlapSize (int level, int codim) const
  {
	return 0;
  }

  //! return size (= distance in graph) of overlap region
  int overlapSize (int codim) const
  {
	return 0;
  }

  //! return size (= distance in graph) of ghost region
  int ghostSize (int level, int codim) const
  {
	return 0;
  }

  //! return size (= distance in graph) of ghost region
  int ghostSize (int codim) const
  {
	return 0;
  }

  /*
    @}
   */

private:
  /*
    Make associated classes friends to grant access to the real entity
  */
  friend class Dune::SGridLevelIndexSet<Dune::SGrid<dim,dimworld> >;
  friend class Dune::SGridLeafIndexSet<Dune::SGrid<dim,dimworld> >;
  friend class Dune::SGridGlobalIdSet<Dune::SGrid<dim,dimworld> >;
  friend class Dune::SIntersectionIterator<Dune::SGrid<dim,dimworld> >;
  friend class Dune::SHierarchicIterator<Dune::SGrid<dim,dimworld> >;
  friend class Dune::SEntity<0,dim,Dune::SGrid<dim,dimworld> >;
  
  friend class Dune::SGridLevelIndexSet<const Dune::SGrid<dim,dimworld> >;
  friend class Dune::SGridLeafIndexSet<const Dune::SGrid<dim,dimworld> >;
  friend class Dune::SGridGlobalIdSet<const Dune::SGrid<dim,dimworld> >;
  friend class Dune::SIntersectionIterator<const Dune::SGrid<dim,dimworld> >;
  friend class Dune::SHierarchicIterator<const Dune::SGrid<dim,dimworld> >;
  friend class Dune::SEntity<0,dim,const Dune::SGrid<dim,dimworld> >;

  template<int codim_, int dim_, class GridImp_, template<int,int,class> class EntityImp_>
  friend class Dune::SEntityBase;
  
  template<int codim_, class GridImp_>
  friend class Dune::SEntityPointer;
  
  template<int codim_, int dim_, class GridImp_, template<int,int,class> class EntityImp_>
  friend class Entity;

  //! map expanded coordinates to position
  FieldVector<ctype, dimworld> pos (int level, array<int,dim>& z) const;
 
  //! compute codim from coordinate
  int calc_codim (int level, const array<int,dim>& z) const;

  //! compute number from expanded coordinate
  int n (int level, const array<int,dim>& z) const;

  //! compute coordinates from number and codimension
  array<int,dim> z (int level, int i, int codim) const;
        
  //! compute zentity of subentity of given codim
  array<int,dim> subz (const array<int,dim> & z, int i, int codim) const;
  
  //! compress from expanded coordinates to grid for a single partition number
  array<int,dim> compress (int level, const array<int,dim>& z) const; 

  //! expand with respect to partition number
  array<int,dim> expand (int level, const array<int,dim>& r, int b) const; 

  /*! There are \f$2^d\f$ possibilities of having even/odd coordinates. 
        The binary representation is called partition number.
  */
  int partition (int level, const array<int,dim>& z) const; 

  //! given reduced coordinates of an element, determine if element is in the grid
  bool exists (int level, const array<int,dim>& zred) const;

  // compute boundary segment index for a given zentity and a face
  int boundarySegmentIndex (int l, int face, const array<int,dim> & zentity) const
  {
    array<int,dim-1> zface;
    int dir = face/2;
    int side = face%2;
    // compute z inside the global face
    for (int i=0; i<dir; i++) zface[i] = zentity[i]/(1<<l);
    for (int i=dir+1; i<dim; i++) zface[i-1] = zentity[i]/(1<<l);
    zface = boundarymapper[dir].expand(zface, 0);
    // compute index in the face
    int index = boundarymapper[dir].n(zface);
    // compute offset
    for (int i=0; i<dir; i++)
      index += 2*boundarymapper[i].elements(0);
    index += side*boundarymapper[dir].elements(0);
    return index;
  }
  
  // compute persistent index for a given zentity
  PersistentIndexType persistentIndex (int l, int codim, const array<int,dim> & zentity) const
  {
	  if (codim!=dim)
		{
		  // encode codim, this would actually not be necessary
          // because z is unique in codim
		  PersistentIndexType id(codim);

		  // encode level
		  id = id << sgrid_level_bits;
		  id = id+PersistentIndexType(l);
	
		  // encode coordinates
		  for (int i=dim-1; i>=0; i--)
			{
			  id = id << sgrid_dim_bits;
			  id = id+PersistentIndexType(zentity[i]);
			}
		  
		  return id;
		}
	  else
		{
		  // determine min number of trailing zeroes
		  // consider that z is on the doubled grid !
		  int trailing = 1000;
		  for (int i=0; i<dim; i++)
			{
			  // count trailing zeros
			  int zeros = 0;
			  for (int j=0; j<l; j++)
				if (zentity[i]&(1<<(j+1)))
				  break;
				else
				  zeros++;
			  trailing = std::min(trailing,zeros);
			}

		  // determine the level of this vertex
		  int level = l-trailing;

		  // encode codim
		  PersistentIndexType id(dim);

		  // encode level
		  id = id << sgrid_level_bits;
		  id = id+PersistentIndexType(level);
	
		  // encode coordinates
		  for (int i=dim-1; i>=0; i--)
			{
			  id = id << sgrid_dim_bits;
			  id = id+PersistentIndexType(zentity[i]>>trailing);
			}
	
		  return id;
		}
  }
    
  // disable copy and assign
  SGrid(const SGrid &) {}
  SGrid & operator = (const SGrid &) { return *this; }
  // generate SGrid 
  void makeSGrid (const array<int,dim>& N_, const FieldVector<ctype, dim>& L_, const FieldVector<ctype, dim>& H_);

  /*
    internal data
   */
  CollectiveCommunication<SGrid> ccobj;

  ReservedVector<SGridLevelIndexSet<const SGrid<dim,dimworld> >*, MAXL> indexsets;
  SGridLeafIndexSet<const SGrid<dim,dimworld> > *theleafindexset;
  SGridGlobalIdSet<const SGrid<dim,dimworld> > *theglobalidset;

  int L;                          // number of levels in hierarchic mesh 0<=level<L
  FieldVector<ctype, dim> low;    // lower left corner of the grid
  FieldVector<ctype, dim> H;      // length of cube per direction
  array<int,dim> *N;              // number of elements per direction
  FieldVector<ctype, dim> *h;     // mesh size per direction
  mutable CubeMapper<dim> *mapper;// a mapper for each level

  // boundary segement index set
  array<CubeMapper<dim-1>, dim> boundarymapper;  // a mapper for each coarse grid face
  int boundarysize;

  // faster implementation of subIndex 
  mutable array <int,dim> zrefStatic;     // for subIndex of SEntity
  mutable array <int,dim> zentityStatic;  // for subIndex of SEntity
};

namespace Capabilities
{

  /** \struct isParallel
  \ingroup SGrid
  */

  /** \struct hasBackupRestoreFacilities
  \ingroup SGrid
  */

  /** \brief SGrid has only one geometry type for codim 0 entities 
  \ingroup SGrid
  */
  template<int dim, int dimw>
  struct hasSingleGeometryType< SGrid<dim,dimw> >
  {
    static const bool v = true;
    static const unsigned int topologyId = GenericGeometry :: CubeTopology< dim > :: type :: id ;
  };
  
  /** \brief SGrid is a Cartesian grid 
      \ingroup SGrid
  */
  template<int dim, int dimw>
  struct isCartesian< SGrid<dim,dimw> >
  {
    static const bool v = true;
  };
  
  /** \brief SGrid has entities for all codimension
  \ingroup SGrid
  */
  template<int dim, int dimw, int cdim>
  struct hasEntity< SGrid<dim,dimw>, cdim>
  {
    static const bool v = true;
  };
  
  /** \brief SGrid is levelwise conforming
  \ingroup SGrid
  */
  template<int dim, int dimw>
  struct isLevelwiseConforming< SGrid<dim,dimw> >
  {
    static const bool v = true;
  };

  /** \brief SGrid is leafwise conforming
  \ingroup SGrid
  */
  template<int dim, int dimw>
  struct isLeafwiseConforming< SGrid<dim,dimw> >
  {
    static const bool v = true;
  };

} // end namespace Capabilities

} // end namespace Dune

#include"sgrid/sgrid.cc"

#endif