File: nsCellMap.cpp

package info (click to toggle)
iceweasel 2.0.0.19-0etch1
  • links: PTS
  • area: main
  • in suites: etch
  • size: 298,784 kB
  • ctags: 317,912
  • sloc: cpp: 1,796,902; ansic: 987,677; xml: 109,036; makefile: 47,777; asm: 35,201; perl: 26,983; sh: 20,879; cs: 6,232; java: 5,513; python: 3,249; pascal: 459; lex: 306; php: 244; csh: 132; objc: 97; yacc: 79; ada: 49; awk: 14; sql: 4; sed: 4
file content (2633 lines) | stat: -rw-r--r-- 88,304 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is mozilla.org code.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#include "nsLayoutAtoms.h"
#include "nsVoidArray.h"
#include "nsCellMap.h"
#include "nsTableFrame.h"
#include "nsTableCellFrame.h"
#include "nsTableRowGroupFrame.h"


// colspan=0 gets a minimum number of cols initially to make computations easier
#define MIN_NUM_COLS_FOR_ZERO_COLSPAN 2

// CellData 

MOZ_DECL_CTOR_COUNTER(CellData)

CellData::CellData(nsTableCellFrame* aOrigCell)
{
  MOZ_COUNT_CTOR(CellData);
  mOrigCell = aOrigCell;
}

CellData::~CellData()
{
  MOZ_COUNT_DTOR(CellData);
}

BCCellData::BCCellData(nsTableCellFrame* aOrigCell)
:CellData(aOrigCell)
{
  MOZ_COUNT_CTOR(BCCellData);
}

BCCellData::~BCCellData()
{
  MOZ_COUNT_DTOR(BCCellData);
}

MOZ_DECL_CTOR_COUNTER(nsCellMap)

// nsTableCellMap

nsTableCellMap::nsTableCellMap(nsTableFrame&   aTableFrame,
                               PRBool          aBorderCollapse)
:mTableFrame(aTableFrame), mFirstMap(nsnull), mBCInfo(nsnull)
{
  MOZ_COUNT_CTOR(nsTableCellMap);

  nsAutoVoidArray orderedRowGroups;
  PRUint32 numRowGroups;
  aTableFrame.OrderRowGroups(orderedRowGroups, numRowGroups);

  for (PRUint32 rgX = 0; rgX < numRowGroups; rgX++) {
    nsTableRowGroupFrame* rgFrame =
      nsTableFrame::GetRowGroupFrame((nsIFrame*)orderedRowGroups.ElementAt(rgX));
    if (rgFrame) {
      nsTableRowGroupFrame* prior = (0 == rgX)
        ? nsnull : nsTableFrame::GetRowGroupFrame((nsIFrame*)orderedRowGroups.ElementAt(rgX - 1));
      InsertGroupCellMap(*rgFrame, prior);
    }
  }
  if (aBorderCollapse) {
    mBCInfo = new BCInfo();
  }
}

nsTableCellMap::~nsTableCellMap()
{
  MOZ_COUNT_DTOR(nsTableCellMap);

  nsCellMap* cellMap = mFirstMap;
  while (cellMap) {
    nsCellMap* next = cellMap->GetNextSibling();
    delete cellMap;
    cellMap = next;
  }

  PRInt32 colCount = mCols.Count();
  for (PRInt32 colX = 0; colX < colCount; colX++) {
    nsColInfo* colInfo = (nsColInfo *)mCols.ElementAt(colX);
    if (colInfo) {
      delete colInfo;
    }
  }
  if (mBCInfo) {
    DeleteRightBottomBorders();
    delete mBCInfo;
  }
}

// Get the bcData holding the border segments of the right edge of the table
BCData*
nsTableCellMap::GetRightMostBorder(PRInt32 aRowIndex)
{
  if (!mBCInfo) ABORT1(nsnull);

  PRInt32 numRows = mBCInfo->mRightBorders.Count();
  if (aRowIndex < numRows) {
    return (BCData*)mBCInfo->mRightBorders.ElementAt(aRowIndex);
  }

  BCData* bcData;
  PRInt32 rowX = numRows;

  do {
    bcData = new BCData();
    if (!bcData) ABORT1(nsnull);
    mBCInfo->mRightBorders.AppendElement(bcData);
  } while (++rowX <= aRowIndex);

  return bcData;
}

// Get the bcData holding the border segments of the bottom edge of the table
BCData*
nsTableCellMap::GetBottomMostBorder(PRInt32 aColIndex)
{
  if (!mBCInfo) ABORT1(nsnull);

  PRInt32 numCols = mBCInfo->mBottomBorders.Count();
  if (aColIndex < numCols) {
    return (BCData*)mBCInfo->mBottomBorders.ElementAt(aColIndex);
  }

  BCData* bcData;
  PRInt32 colX = numCols;

  do {
    bcData = new BCData();
    if (!bcData) ABORT1(nsnull);
    mBCInfo->mBottomBorders.AppendElement(bcData);
  } while (++colX <= aColIndex);

  return bcData;
}

// delete the borders corresponding to the right and bottom edges of the table
void 
nsTableCellMap::DeleteRightBottomBorders()
{
  if (mBCInfo) {
    PRInt32 numCols = mBCInfo->mBottomBorders.Count();
    if (numCols > 0) {
      for (PRInt32 colX = numCols - 1; colX >= 0; colX--) {
        BCData* bcData = (BCData*)mBCInfo->mBottomBorders.ElementAt(colX);
        if (bcData) {
          delete bcData;
        }
        mBCInfo->mBottomBorders.RemoveElementAt(colX);
      }
    }
    PRUint32 numRows = mBCInfo->mRightBorders.Count();
    if (numRows > 0) {
      for (PRInt32 rowX = numRows - 1; rowX >= 0; rowX--) {
        BCData* bcData = (BCData*)mBCInfo->mRightBorders.ElementAt(rowX);
        if (bcData) {
          delete bcData;
        }
        mBCInfo->mRightBorders.RemoveElementAt(rowX);
      }
    }
  }
}
      
void 
nsTableCellMap::InsertGroupCellMap(nsCellMap* aPrevMap,
                                   nsCellMap& aNewMap)
{
  nsCellMap* next;
  if (aPrevMap) {
    next = aPrevMap->GetNextSibling();
    aPrevMap->SetNextSibling(&aNewMap);
  }
  else {
    next = mFirstMap;
    mFirstMap = &aNewMap;
  }
  aNewMap.SetNextSibling(next);
}

void nsTableCellMap::InsertGroupCellMap(nsTableRowGroupFrame&  aNewGroup,
                                        nsTableRowGroupFrame*& aPrevGroup)
{
  nsCellMap* newMap = new nsCellMap(aNewGroup);
  if (newMap) {
    nsCellMap* prevMap = nsnull;
    nsCellMap* lastMap = mFirstMap;
    if (aPrevGroup) {
      nsCellMap* map = mFirstMap;
      while (map) {
        lastMap = map;
        if (map->GetRowGroup() == aPrevGroup) {
          prevMap = map;
          break;
        }
        map = map->GetNextSibling();
      }
    }
    if (!prevMap) {
      if (aPrevGroup) {
        prevMap = lastMap;
        aPrevGroup = (prevMap) ? prevMap->GetRowGroup() : nsnull;
      }
      else {
        aPrevGroup = nsnull;
      }
    }
    InsertGroupCellMap(prevMap, *newMap);
  }
}

void nsTableCellMap::RemoveGroupCellMap(nsTableRowGroupFrame* aGroup)
{
  nsCellMap* map = mFirstMap;
  nsCellMap* prior = nsnull;
  while (map) {
    if (map->GetRowGroup() == aGroup) {
      nsCellMap* next = map->GetNextSibling();
      if (mFirstMap == map) {
        mFirstMap = next;
      }
      else {
        prior->SetNextSibling(next);
      }
      delete map;
      break;
    }
    prior = map;
    map = map->GetNextSibling();
  }
}

nsCellMap* 
nsTableCellMap::GetMapFor(nsTableRowGroupFrame& aRowGroup)
{
  NS_ASSERTION(!aRowGroup.GetPrevInFlow(), "GetMapFor called with continuation");
  for (nsCellMap* map = mFirstMap; map; map = map->GetNextSibling()) {
    if (&aRowGroup == map->GetRowGroup()) {
      return map;
    }
  }
  // if aRowGroup is a repeated header or footer find the header or footer it was repeated from
  if (aRowGroup.IsRepeatable()) {
    nsTableFrame* fifTable = NS_STATIC_CAST(nsTableFrame*, mTableFrame.GetFirstInFlow());

    nsAutoVoidArray rowGroups;
    PRUint32 numRowGroups;
    nsTableRowGroupFrame *thead, *tfoot;
    nsIFrame *ignore;
    // find the original header/footer 
    fifTable->OrderRowGroups(rowGroups, numRowGroups, &ignore, &thead, &tfoot);

    const nsStyleDisplay* display = aRowGroup.GetStyleDisplay();
    nsTableRowGroupFrame* rgOrig = 
      (NS_STYLE_DISPLAY_TABLE_HEADER_GROUP == display->mDisplay) ? thead : tfoot; 
    // find the row group cell map using the original header/footer
    if (rgOrig) {
      for (nsCellMap* map = mFirstMap; map; map = map->GetNextSibling()) {
        if (rgOrig == map->GetRowGroup()) {
          return map;
        }
      }
    }
  }

  return nsnull;
}

void
nsTableCellMap::Synchronize(nsTableFrame* aTableFrame)
{
  nsAutoVoidArray orderedRowGroups;
  nsAutoVoidArray maps;
  PRUint32 numRowGroups;
  PRInt32 mapIndex;

  maps.Clear();
  aTableFrame->OrderRowGroups(orderedRowGroups, numRowGroups);
  if (!numRowGroups) {
    return;
  }

  for (PRUint32 rgX = 0; rgX < numRowGroups; rgX++) {
    nsTableRowGroupFrame* rgFrame =
      nsTableFrame::GetRowGroupFrame((nsIFrame*)orderedRowGroups.ElementAt(rgX));
    if (rgFrame) {
      nsCellMap* map = GetMapFor(*(nsTableRowGroupFrame*)(rgFrame->GetFirstInFlow()));
      if (map) {
        if (!maps.AppendElement(map)) {
          delete map;
          NS_WARNING("Could not AppendElement");
        }
      }
    }
  }
  mapIndex = maps.Count() - 1;
  nsCellMap* nextMap = (nsCellMap*) maps.ElementAt(mapIndex);
  nextMap->SetNextSibling(nsnull);
  for (mapIndex-- ; mapIndex >= 0; mapIndex--) {
    nsCellMap* map = (nsCellMap*) maps.ElementAt(mapIndex);
    map->SetNextSibling(nextMap);
    nextMap = map;
  }
  mFirstMap = nextMap;
}

PRBool
nsTableCellMap::HasMoreThanOneCell(PRInt32 aRowIndex)
{
  PRInt32 rowIndex = aRowIndex;
  nsCellMap* map = mFirstMap;
  while (map) {
    if (map->GetRowCount() > rowIndex) {
      return map->HasMoreThanOneCell(*this, rowIndex);
    }
    rowIndex -= map->GetRowCount();
    map = map->GetNextSibling();
  }
  return PR_FALSE;
}

PRInt32 
nsTableCellMap::GetEffectiveRowSpan(PRInt32 aRowIndex,
                                    PRInt32 aColIndex)
{
  PRInt32 rowIndex = aRowIndex;
  nsCellMap* map = mFirstMap;
  while (map) {
    if (map->GetRowCount() > rowIndex) {
      PRBool zeroRowSpan;
      return map->GetRowSpan(*this, rowIndex, aColIndex, PR_TRUE, zeroRowSpan);
    }
    rowIndex -= map->GetRowCount();
    map = map->GetNextSibling();
  }
  return nsnull;
}

PRInt32 
nsTableCellMap::GetEffectiveColSpan(PRInt32 aRowIndex,
                                    PRInt32 aColIndex)
{
  PRInt32 rowIndex = aRowIndex;
  nsCellMap* map = mFirstMap;
  while (map) {
    if (map->GetRowCount() > rowIndex) {
      PRBool zeroColSpan;
      return map->GetEffectiveColSpan(*this, rowIndex, aColIndex, zeroColSpan);
    }
    rowIndex -= map->GetRowCount();
    map = map->GetNextSibling();
  }
  return nsnull;
}

nsTableCellFrame* 
nsTableCellMap::GetCellFrame(PRInt32   aRowIndex,
                             PRInt32   aColIndex,
                             CellData& aData,
                             PRBool    aUseRowIfOverlap) const
{
  PRInt32 rowIndex = aRowIndex;
  nsCellMap* map = mFirstMap;
  while (map) {
    if (map->GetRowCount() > rowIndex) {
      return map->GetCellFrame(rowIndex, aColIndex, aData, aUseRowIfOverlap);
    }
    rowIndex -= map->GetRowCount();
    map = map->GetNextSibling();
  }
  return nsnull;
}

nsColInfo* 
nsTableCellMap::GetColInfoAt(PRInt32 aColIndex)
{
  PRInt32 numColsToAdd = aColIndex + 1 - mCols.Count();
  if (numColsToAdd > 0) {
    AddColsAtEnd(numColsToAdd);  // XXX this could fail to add cols in theory
  }
  return (nsColInfo*)mCols.ElementAt(aColIndex);
}

PRInt32 
nsTableCellMap::GetRowCount() const
{
  PRInt32 numRows = 0;
  nsCellMap* map = mFirstMap;
  while (map) {
    numRows += map->GetRowCount();
    map = map->GetNextSibling();
  }
  return numRows;
}

CellData* 
nsTableCellMap::GetDataAt(PRInt32 aRowIndex, 
                          PRInt32 aColIndex,
                          PRBool  aUpdateZeroSpan)
{
  PRInt32 rowIndex = aRowIndex;
  nsCellMap* map = mFirstMap;
  while (map) {
    if (map->GetRowCount() > rowIndex) {
      return map->GetDataAt(*this, rowIndex, aColIndex, aUpdateZeroSpan);
    }
    rowIndex -= map->GetRowCount();
    map = map->GetNextSibling();
  }
  return nsnull;
}

void 
nsTableCellMap::AddColsAtEnd(PRUint32 aNumCols)
{
  PRBool added;
  // XXX We really should have a way to say "make this voidarray at least
  // N entries long" to avoid reallocating N times.  On the other hand, the
  // number of likely allocations here isn't TOO gigantic, and we may not
  // know about many of them at a time.
  for (PRUint32 numX = 1; numX <= aNumCols; numX++) {
    nsColInfo* colInfo = new nsColInfo();
    if (colInfo) {
      added = mCols.AppendElement(colInfo);
      if (!added) {
        delete colInfo;
        NS_WARNING("Could not AppendElement");
      }
    }
    if (mBCInfo) {
      BCData* bcData = new BCData();
      if (bcData) {
        added = mBCInfo->mBottomBorders.AppendElement(bcData);
        if (!added) {
          delete bcData;
          NS_WARNING("Could not AppendElement");
        }
      }
    }
  }
}

void 
nsTableCellMap::RemoveColsAtEnd()
{
  // Remove the cols at the end which don't have originating cells or cells spanning 
  // into them. Only do this if the col was created as eColAnonymousCell  
  PRInt32 numCols = GetColCount();
  PRInt32 lastGoodColIndex = mTableFrame.GetIndexOfLastRealCol();
  for (PRInt32 colX = numCols - 1; (colX >= 0) && (colX > lastGoodColIndex); colX--) {
    nsColInfo* colInfo = (nsColInfo*)mCols.ElementAt(colX);
    if (colInfo) {
      if ((colInfo->mNumCellsOrig <= 0) && (colInfo->mNumCellsSpan <= 0))  {

        delete colInfo;
        mCols.RemoveElementAt(colX);

        if (mBCInfo) { 
          PRInt32 count = mBCInfo->mBottomBorders.Count();
          if (colX < count) {
            BCData* bcData = (BCData*)mBCInfo->mBottomBorders.ElementAt(colX);
            if (bcData) {
              delete bcData;
            }
            mBCInfo->mBottomBorders.RemoveElementAt(colX);
          }
        }
      }
      else break; // only remove until we encounter the 1st valid one
    }
    else {
      NS_ASSERTION(0, "null entry in column info array");
      mCols.RemoveElementAt(colX);
    }
  }
}

void 
nsTableCellMap::ClearCols()
{
  PRInt32 numCols = GetColCount();
  for (PRInt32 colX = numCols - 1; (colX >= 0);colX--) {
    nsColInfo* colInfo = (nsColInfo*)mCols.ElementAt(colX);  
    delete colInfo;
    mCols.RemoveElementAt(colX);
    if (mBCInfo) { 
      PRInt32 count = mBCInfo->mBottomBorders.Count();
      if (colX < count) {
        BCData* bcData = (BCData*)mBCInfo->mBottomBorders.ElementAt(colX);
        if (bcData) {
              delete bcData;
        }
        mBCInfo->mBottomBorders.RemoveElementAt(colX);
      }
    }
  }
}
void
nsTableCellMap::InsertRows(nsTableRowGroupFrame& aParent,
                           nsVoidArray&          aRows,
                           PRInt32               aFirstRowIndex,
                           PRBool                aConsiderSpans,
                           nsRect&               aDamageArea)
{
  PRInt32 numNewRows = aRows.Count();
  if ((numNewRows <= 0) || (aFirstRowIndex < 0)) ABORT0(); 

  PRInt32 rowIndex = aFirstRowIndex;
  nsCellMap* cellMap = mFirstMap;
  while (cellMap) {
    nsTableRowGroupFrame* rg = cellMap->GetRowGroup();
    if (rg == &aParent) {
      cellMap->InsertRows(*this, aRows, rowIndex, aConsiderSpans, aDamageArea);
      aDamageArea.y = aFirstRowIndex;
      aDamageArea.height = PR_MAX(0, GetRowCount() - aFirstRowIndex);
#ifdef DEBUG_TABLE_CELLMAP 
      Dump("after InsertRows");
#endif
      if (mBCInfo) {
        BCData* bcData;
        PRInt32 count = mBCInfo->mRightBorders.Count();
        if (aFirstRowIndex < count) {
          for (PRInt32 rowX = aFirstRowIndex; rowX < aFirstRowIndex + numNewRows; rowX++) {
            bcData = new BCData(); if (!bcData) ABORT0();
            mBCInfo->mRightBorders.InsertElementAt(bcData, rowX);
          }
        }
        else {
          GetRightMostBorder(aFirstRowIndex); // this will create missing entries
          for (PRInt32 rowX = aFirstRowIndex + 1; rowX < aFirstRowIndex + numNewRows; rowX++) {
            bcData = new BCData(); if (!bcData) ABORT0();
            mBCInfo->mRightBorders.AppendElement(bcData);
          }
        }
      }
      return;
    }
    rowIndex -= cellMap->GetRowCount();
    cellMap = cellMap->GetNextSibling();
  }

  NS_ASSERTION(PR_FALSE, "Attempt to insert row into wrong map.");
}

void
nsTableCellMap::RemoveRows(PRInt32         aFirstRowIndex,
                           PRInt32         aNumRowsToRemove,
                           PRBool          aConsiderSpans,
                           nsRect&         aDamageArea)
{
  PRInt32 rowIndex = aFirstRowIndex;
  nsCellMap* cellMap = mFirstMap;
  while (cellMap) {
    if (cellMap->GetRowCount() > rowIndex) {
      cellMap->RemoveRows(*this, rowIndex, aNumRowsToRemove, aConsiderSpans, aDamageArea);
      nsTableRowGroupFrame* rg = cellMap->GetRowGroup();
      aDamageArea.y += (rg) ? rg->GetStartRowIndex() : 0;
      aDamageArea.height = PR_MAX(0, GetRowCount() - aFirstRowIndex);
      if (mBCInfo) {
        BCData* bcData;
        for (PRInt32 rowX = aFirstRowIndex + aNumRowsToRemove - 1; rowX >= aFirstRowIndex; rowX--) {
          if (rowX < mBCInfo->mRightBorders.Count()) {
            bcData = (BCData*)mBCInfo->mRightBorders.ElementAt(rowX);
            if (bcData) {
              delete bcData;
            }
            mBCInfo->mRightBorders.RemoveElementAt(rowX);
          }
        }
      }
      break;
    }
    rowIndex -= cellMap->GetRowCount();
    cellMap = cellMap->GetNextSibling();
  }
#ifdef DEBUG_TABLE_CELLMAP
  Dump("after RemoveRows");
#endif
}

PRInt32
nsTableCellMap::GetNumCellsOriginatingInRow(PRInt32 aRowIndex)
{
  PRInt32 originCount = 0;

  CellData* cellData;
  PRInt32   colIndex = 0;

  do {
	  cellData = GetDataAt(aRowIndex, colIndex);
	  if (cellData && cellData->GetCellFrame())
		  originCount++;
    colIndex++;
  } while(cellData);

  return originCount;
}

CellData* 
nsTableCellMap::AppendCell(nsTableCellFrame& aCellFrame,
                           PRInt32           aRowIndex,
                           PRBool            aRebuildIfNecessary,
                           nsRect&           aDamageArea)
{
  NS_ASSERTION(&aCellFrame == aCellFrame.GetFirstInFlow(), "invalid call on continuing frame");
  nsIFrame* rgFrame = aCellFrame.GetParent(); // get the row
  if (!rgFrame) return 0;
  rgFrame = rgFrame->GetParent();   // get the row group
  if (!rgFrame) return 0;

  CellData* result = nsnull;
  PRInt32 rowIndex = aRowIndex;
  nsCellMap* cellMap = mFirstMap;
  while (cellMap) {
    if (cellMap->GetRowGroup() == rgFrame) {
      result = cellMap->AppendCell(*this, &aCellFrame, rowIndex, aRebuildIfNecessary, aDamageArea);
      nsTableRowGroupFrame* rg = cellMap->GetRowGroup();
      aDamageArea.y += (rg) ? rg->GetStartRowIndex() : 0;
      break;
    }
    rowIndex -= cellMap->GetRowCount();
    cellMap = cellMap->GetNextSibling();
  }
#ifdef DEBUG_TABLE_CELLMAP
  Dump("after AppendCell");
#endif
  return result;
}


void 
nsTableCellMap::InsertCells(nsVoidArray&          aCellFrames,
                            PRInt32               aRowIndex,
                            PRInt32               aColIndexBefore,
                            nsRect&               aDamageArea)
{
  PRInt32 rowIndex = aRowIndex;
  nsCellMap* cellMap = mFirstMap;
  while (cellMap) {
    if (cellMap->GetRowCount() > rowIndex) {
      cellMap->InsertCells(*this, aCellFrames, rowIndex, aColIndexBefore, aDamageArea);
      nsTableRowGroupFrame* rg = cellMap->GetRowGroup();
      aDamageArea.y += (rg) ? rg->GetStartRowIndex() : 0;
      aDamageArea.width = PR_MAX(0, GetColCount() - aColIndexBefore - 1);
      break;
    }
    rowIndex -= cellMap->GetRowCount();
    cellMap = cellMap->GetNextSibling();
  }
#ifdef DEBUG_TABLE_CELLMAP
  Dump("after InsertCells");
#endif
}


void 
nsTableCellMap::RemoveCell(nsTableCellFrame* aCellFrame,
                           PRInt32           aRowIndex,
                           nsRect&           aDamageArea)
{
  if (!aCellFrame) ABORT0();
  NS_ASSERTION(aCellFrame == (nsTableCellFrame *)aCellFrame->GetFirstInFlow(),
               "invalid call on continuing frame");
  PRInt32 rowIndex = aRowIndex;
  nsCellMap* cellMap = mFirstMap;
  while (cellMap) {
    if (cellMap->GetRowCount() > rowIndex) {
      cellMap->RemoveCell(*this, aCellFrame, rowIndex, aDamageArea);
      nsTableRowGroupFrame* rg = cellMap->GetRowGroup();
      aDamageArea.y += (rg) ? rg->GetStartRowIndex() : 0;
      PRInt32 colIndex;
      aCellFrame->GetColIndex(colIndex);
      aDamageArea.width = PR_MAX(0, GetColCount() - colIndex - 1);
#ifdef DEBUG_TABLE_CELLMAP
      Dump("after RemoveCell");
#endif
      return;
    }
    rowIndex -= cellMap->GetRowCount();
    cellMap = cellMap->GetNextSibling();
  }
  // if we reach this point - the cell did not get removed, the caller of this routine 
  // will delete the cell and the cellmap will probably hold a reference to 
  // the deleted cell which will cause a subsequent crash when this cell is 
  // referenced later
  NS_ERROR("nsTableCellMap::RemoveCell - could not remove cell");
}

void
SetDamageArea(PRInt32 aXOrigin,
              PRInt32 aYOrigin,
              PRInt32 aWidth,
              PRInt32 aHeight,
              nsRect& aDamageArea)
{
  aDamageArea.x      = aXOrigin;
  aDamageArea.y      = aYOrigin;
  aDamageArea.width  = PR_MAX(1, aWidth);
  aDamageArea.height = PR_MAX(1, aHeight);
}

void 
nsTableCellMap::RebuildConsideringCells(nsCellMap*      aCellMap,
                                        nsVoidArray*    aCellFrames,
                                        PRInt32         aRowIndex,
                                        PRInt32         aColIndex,
                                        PRBool          aInsert,
                                        nsRect&         aDamageArea)
{
  PRInt32 numOrigCols = GetColCount();
  ClearCols();
  nsCellMap* cellMap = mFirstMap;
  PRInt32 rowCount = 0;
  while (cellMap) {
    if (cellMap == aCellMap) {
      cellMap->RebuildConsideringCells(*this, numOrigCols, aCellFrames, aRowIndex, aColIndex, aInsert, aDamageArea);
      
    }
    else {
      cellMap->RebuildConsideringCells(*this, numOrigCols, nsnull, -1, 0, PR_FALSE, aDamageArea);
    }
    rowCount += cellMap->GetRowCount();
    cellMap = cellMap->GetNextSibling();
  }
  SetDamageArea(0, 0, GetColCount(), rowCount, aDamageArea);
}

void 
nsTableCellMap::RebuildConsideringRows(nsCellMap*      aCellMap,
                                       PRInt32         aStartRowIndex,
                                       nsVoidArray*    aRowsToInsert,
                                       PRBool          aNumRowsToRemove,
                                       nsRect&         aDamageArea)
{
  PRInt32 numOrigCols = GetColCount();
  ClearCols();
  nsCellMap* cellMap = mFirstMap;
  PRInt32 rowCount = 0;
  while (cellMap) {
    if (cellMap == aCellMap) {
      cellMap->RebuildConsideringRows(*this, aStartRowIndex, aRowsToInsert, aNumRowsToRemove, aDamageArea);
    }
    else {
      cellMap->RebuildConsideringCells(*this, numOrigCols, nsnull, -1, 0, PR_FALSE, aDamageArea);
    }
    rowCount += cellMap->GetRowCount();
    cellMap = cellMap->GetNextSibling();
  }
  SetDamageArea(0, 0, GetColCount(), rowCount, aDamageArea);
}

PRInt32 
nsTableCellMap::GetNumCellsOriginatingInCol(PRInt32 aColIndex) const
{
  PRInt32 colCount = mCols.Count();
  if ((aColIndex >= 0) && (aColIndex < colCount)) {
    return ((nsColInfo *)mCols.ElementAt(aColIndex))->mNumCellsOrig;
  }
  else {
    NS_ASSERTION(PR_FALSE, "nsCellMap::GetNumCellsOriginatingInCol - bad col index");
    return 0;
  }
}

#ifdef NS_DEBUG
void 
nsTableCellMap::Dump(char* aString) const
{
  if (aString) 
    printf("%s \n", aString);
  printf("***** START TABLE CELL MAP DUMP ***** %p\n", this);
  // output col info
  PRInt32 colCount = mCols.Count();
  printf ("cols array orig/span-> %p", this);
  for (PRInt32 colX = 0; colX < colCount; colX++) {
    nsColInfo* colInfo = (nsColInfo *)mCols.ElementAt(colX);
    printf ("%d=%d/%d ", colX, colInfo->mNumCellsOrig, colInfo->mNumCellsSpan);
  }
  printf(" cols in cache %d\n", mTableFrame.GetColCache().Count());
  nsCellMap* cellMap = mFirstMap;
  while (cellMap) {
    cellMap->Dump(nsnull != mBCInfo);
    cellMap = cellMap->GetNextSibling();
  }
  if (nsnull != mBCInfo) {
    printf("***** bottom borders *****\n");
    nscoord       size;
    BCBorderOwner owner;
    PRUint8       side;
    PRBool        segStart;
    PRPackedBool  bevel;  
    PRInt32       colIndex;    
    PRInt32 numCols = mBCInfo->mBottomBorders.Count();
    for (PRInt32 i = 0; i <= 2; i++) {
     
      printf("\n          ");
      for (colIndex = 0; colIndex < numCols; colIndex++) {
        BCData* cd = (BCData*)mBCInfo->mBottomBorders.ElementAt(colIndex);;
        if (cd) {
          if (0 == i) {
            size = cd->GetTopEdge(owner, segStart);
            printf("t=%d%X%d ", size, owner, segStart);
          }
          else if (1 == i) {
            size = cd->GetLeftEdge(owner, segStart);
            printf("l=%d%X%d ", size, owner, segStart);
          }
          else {
            size = cd->GetCorner(side, bevel);
            printf("c=%d%X%d ", size, side, bevel);
          }
        }
      }
      BCData* cd = &mBCInfo->mLowerRightCorner;
      if (cd) {
        if (0 == i) {
           size = cd->GetTopEdge(owner, segStart);
           printf("t=%d%X%d ", size, owner, segStart);
        }
        else if (1 == i) {
          size = cd->GetLeftEdge(owner, segStart);
          printf("l=%d%X%d ", size, owner, segStart);
        }
        else {
          size = cd->GetCorner(side, bevel);
          printf("c=%d%X%d ", size, side, bevel);
        }
      }
    }
    printf("\n");
  }
  printf("***** END TABLE CELL MAP DUMP *****\n");
}
#endif

nsTableCellFrame* 
nsTableCellMap::GetCellInfoAt(PRInt32  aRowIndex, 
                              PRInt32  aColIndex, 
                              PRBool*  aOriginates, 
                              PRInt32* aColSpan)
{
  PRInt32 rowIndex = aRowIndex;
  nsCellMap* cellMap = mFirstMap;
  while (cellMap) {
    if (cellMap->GetRowCount() > rowIndex) {
      return cellMap->GetCellInfoAt(*this, rowIndex, aColIndex, aOriginates, aColSpan);
    }
    rowIndex -= cellMap->GetRowCount();
    cellMap = cellMap->GetNextSibling();
  }
  return nsnull;
}
  

PRBool nsTableCellMap::RowIsSpannedInto(PRInt32 aRowIndex)
{
  PRInt32 rowIndex = aRowIndex;
  nsCellMap* cellMap = mFirstMap;
  while (cellMap) {
    if (cellMap->GetRowCount() > rowIndex) {
      return cellMap->RowIsSpannedInto(*this, rowIndex);
    }
    rowIndex -= cellMap->GetRowCount();
    cellMap = cellMap->GetNextSibling();
  }
  return PR_FALSE;
}

PRBool nsTableCellMap::RowHasSpanningCells(PRInt32 aRowIndex)
{
  PRInt32 rowIndex = aRowIndex;
  nsCellMap* cellMap = mFirstMap;
  while (cellMap) {
    if (cellMap->GetRowCount() > rowIndex) {
      return cellMap->RowHasSpanningCells(*this, rowIndex);
    }
    rowIndex -= cellMap->GetRowCount();
    cellMap = cellMap->GetNextSibling();
  }
  return PR_FALSE;
}

PRBool nsTableCellMap::ColIsSpannedInto(PRInt32 aColIndex)
{
  PRBool result = PR_FALSE;

  PRInt32 colCount = mCols.Count();
  if ((aColIndex >= 0) && (aColIndex < colCount)) {
    result = (PRBool) ((nsColInfo *)mCols.ElementAt(aColIndex))->mNumCellsSpan;
  }
  return result;
}

PRBool nsTableCellMap::ColHasSpanningCells(PRInt32 aColIndex)
{
  nsCellMap* cellMap = mFirstMap;
  while (cellMap) {
    if (cellMap->ColHasSpanningCells(*this, aColIndex)) {
      return PR_TRUE;
    }
    cellMap = cellMap->GetNextSibling();
  }
  return PR_FALSE;
}

BCData* 
nsTableCellMap::GetBCData(PRUint8     aSide, 
                          nsCellMap&  aCellMap,
                          PRUint32    aRowIndex, 
                          PRUint32    aColIndex,
                          PRBool      aIsLowerRight)
{
  if (!mBCInfo || aIsLowerRight) ABORT1(nsnull);

  BCCellData* cellData;
  BCData* bcData = nsnull;

  switch(aSide) {
  case NS_SIDE_BOTTOM:
    aRowIndex++;
  case NS_SIDE_TOP:
    cellData = (BCCellData*)aCellMap.GetDataAt(*this, aRowIndex, aColIndex, PR_FALSE);
    if (cellData) {
      bcData = &cellData->mData;
    }
    else {
      NS_ASSERTION(aSide == NS_SIDE_BOTTOM, "program error");
      // try the next row group
      nsCellMap* cellMap = aCellMap.GetNextSibling();
      if (cellMap) {
        cellData = (BCCellData*)cellMap->GetDataAt(*this, 0, aColIndex, PR_FALSE);
        if (cellData) {
          bcData = &cellData->mData;
        }
        else {
          bcData = GetBottomMostBorder(aColIndex);
        }
      }
    }
    break;
  case NS_SIDE_RIGHT:
    aColIndex++;
  case NS_SIDE_LEFT:
    cellData = (BCCellData*)aCellMap.GetDataAt(*this, aRowIndex, aColIndex, PR_FALSE);
    if (cellData) {
      bcData = &cellData->mData;
    }
    else {
      NS_ASSERTION(aSide == NS_SIDE_RIGHT, "program error");
      bcData = GetRightMostBorder(aRowIndex);
    }
    break;
  }
  return bcData;
}

// store the aSide border segment at coord = (aRowIndex, aColIndex). For top/left, store
// the info at coord. For bottom/left store it at the adjacent location so that it is 
// top/left at that location. If the new location is at the right or bottom edge of the 
// table, then store it one of the special arrays (right most borders, bottom most borders).  
void 
nsTableCellMap::SetBCBorderEdge(PRUint8       aSide, 
                                nsCellMap&    aCellMap,
                                PRUint32      aCellMapStart,
                                PRUint32      aRowIndex, 
                                PRUint32      aColIndex,
                                PRUint32      aLength,
                                BCBorderOwner aOwner,
                                nscoord       aSize,
                                PRBool        aChanged)
{
  if (!mBCInfo) ABORT0();
  //if (aRowIndex >= 80) {
  //  NS_ASSERTION(PR_FALSE, "hello");
  //}

  BCCellData* cellData;
  PRInt32 lastIndex, xIndex, yIndex;
  PRInt32 xPos = aColIndex;
  PRInt32 yPos = aRowIndex;
  PRInt32 rgYPos = aRowIndex - aCellMapStart;
  PRBool changed;

  switch(aSide) {
  case NS_SIDE_BOTTOM:
    rgYPos++;
    yPos++;
  case NS_SIDE_TOP:
    lastIndex = xPos + aLength - 1;
    for (xIndex = xPos; xIndex <= lastIndex; xIndex++) {
      changed = aChanged && (xIndex == xPos);
      BCData* bcData = nsnull;
      cellData = (BCCellData*)aCellMap.GetDataAt(*this, rgYPos, xIndex, PR_FALSE);
      if (!cellData) {
        PRInt32 numRgRows = aCellMap.GetRowCount();
        if (yPos < numRgRows) { // add a dead cell data
          nsRect damageArea;
          cellData = (BCCellData*)aCellMap.AppendCell(*this, nsnull, rgYPos, PR_FALSE, damageArea); if (!cellData) ABORT0();
        }
        else {
          NS_ASSERTION(aSide == NS_SIDE_BOTTOM, "program error");
          // try the next non empty row group
          nsCellMap* cellMap = aCellMap.GetNextSibling();
          while (cellMap && (0 == cellMap->GetRowCount())) {
            cellMap = cellMap->GetNextSibling();
          }
          if (cellMap) {
            cellData = (BCCellData*)cellMap->GetDataAt(*this, 0, xIndex, PR_FALSE);
            if (!cellData) { // add a dead cell
              nsRect damageArea;
              cellData = (BCCellData*)cellMap->AppendCell(*this, nsnull, 0, PR_FALSE, damageArea); 
            }
          }
          else { // must be at the end of the table
            bcData = GetBottomMostBorder(xIndex);
          }
        }
      }
      if (!bcData && cellData) {
        bcData = &cellData->mData;
      }
      if (bcData) {
        bcData->SetTopEdge(aOwner, aSize, changed);
      }
      else NS_ASSERTION(PR_FALSE, "program error");
    }
    break;
  case NS_SIDE_RIGHT:
    xPos++;
  case NS_SIDE_LEFT:
    // since top, bottom borders were set, there should already be a cellData entry
    lastIndex = rgYPos + aLength - 1;
    for (yIndex = rgYPos; yIndex <= lastIndex; yIndex++) {
      changed = aChanged && (yIndex == rgYPos);
      cellData = (BCCellData*)aCellMap.GetDataAt(*this, yIndex, xPos, PR_FALSE);
      if (cellData) {
        cellData->mData.SetLeftEdge(aOwner, aSize, changed);
      }
      else {
        NS_ASSERTION(aSide == NS_SIDE_RIGHT, "program error");
        BCData* bcData = GetRightMostBorder(yIndex + aCellMapStart);
        if (bcData) {
          bcData->SetLeftEdge(aOwner, aSize, changed);
        }
        else NS_ASSERTION(PR_FALSE, "program error");
      }
    }
    break;
  }
}

// store corner info (aOwner, aSubSize, aBevel). For aCorner = eTopLeft, store the info at 
// (aRowIndex, aColIndex). For eTopRight, store it in the entry to the right where
// it would be top left. For eBottomRight, store it in the entry to the bottom. etc. 
void 
nsTableCellMap::SetBCBorderCorner(Corner      aCorner,
                                  nsCellMap&  aCellMap,
                                  PRUint32    aCellMapStart,
                                  PRUint32    aRowIndex, 
                                  PRUint32    aColIndex,
                                  PRUint8     aOwner,
                                  nscoord     aSubSize,
                                  PRBool      aBevel,
                                  PRBool      aIsBottomRight)
{
  if (!mBCInfo) ABORT0();

  if (aIsBottomRight) { 
    mBCInfo->mLowerRightCorner.SetCorner(aSubSize, aOwner, aBevel);
    return;
  }

  PRInt32 xPos = aColIndex;
  PRInt32 yPos = aRowIndex;
  PRInt32 rgYPos = aRowIndex - aCellMapStart;

  if (eTopRight == aCorner) {
    xPos++;
  }
  else if (eBottomRight == aCorner) {
    xPos++;
    rgYPos++;
    yPos++;
  }
  else if (eBottomLeft == aCorner) {
    rgYPos++;
    yPos++;
  }

  BCCellData* cellData = nsnull;
  BCData*     bcData   = nsnull;
  if (GetColCount() <= xPos) {
    NS_ASSERTION(xPos == GetColCount(), "program error");
    // at the right edge of the table as we checked the corner before
    bcData = GetRightMostBorder(yPos);
  }
  else {
    cellData = (BCCellData*)aCellMap.GetDataAt(*this, rgYPos, xPos, PR_FALSE);
    if (!cellData) {
      PRInt32 numRgRows = aCellMap.GetRowCount();
      if (yPos < numRgRows) { // add a dead cell data
        nsRect damageArea;
        cellData = (BCCellData*)aCellMap.AppendCell(*this, nsnull, rgYPos, PR_FALSE, damageArea); 
      }
      else {
        // try the next non empty row group
        nsCellMap* cellMap = aCellMap.GetNextSibling();
        while (cellMap && (0 == cellMap->GetRowCount())) {
          cellMap = cellMap->GetNextSibling();
        }
        if (cellMap) {
          cellData = (BCCellData*)cellMap->GetDataAt(*this, 0, xPos, PR_FALSE);
          if (!cellData) { // add a dead cell
            nsRect damageArea;
            cellData = (BCCellData*)cellMap->AppendCell(*this, nsnull, 0, PR_FALSE, damageArea); 
          }
        }
        else { // must be a the bottom of the table
          bcData = GetBottomMostBorder(xPos);
        }
      }
    }
  }
  if (!bcData && cellData) {
    bcData = &cellData->mData;
  }
  if (bcData) {
    bcData->SetCorner(aSubSize, aOwner, aBevel);
  }
  else NS_ASSERTION(PR_FALSE, "program error");
}

nsCellMap::nsCellMap(nsTableRowGroupFrame& aRowGroup)
  : mRowCount(0), mRowGroupFrame(&aRowGroup), mNextSibling(nsnull)
{
  MOZ_COUNT_CTOR(nsCellMap);
}

nsCellMap::~nsCellMap()
{
  MOZ_COUNT_DTOR(nsCellMap);
  
  PRInt32 mapRowCount = mRows.Count();
  for (PRInt32 rowX = 0; rowX < mapRowCount; rowX++) {
    nsVoidArray* row = (nsVoidArray *)(mRows.ElementAt(rowX));
    PRInt32 colCount = row->Count();
    for (PRInt32 colX = 0; colX < colCount; colX++) {
      CellData* data = (CellData *)(row->ElementAt(colX));
      if (data) {
        delete data;
      } 
    }
    delete row;
  }
}

nsTableCellFrame* 
nsCellMap::GetCellFrame(PRInt32   aRowIndexIn,
                        PRInt32   aColIndexIn,
                        CellData& aData,
                        PRBool    aUseRowIfOverlap) const
{
  PRInt32 rowIndex = aRowIndexIn - aData.GetRowSpanOffset();
  PRInt32 colIndex = aColIndexIn - aData.GetColSpanOffset();
  if (aData.IsOverlap()) {
    if (aUseRowIfOverlap) {
      colIndex = aColIndexIn;
    }
    else {
      rowIndex = aRowIndexIn;
    }
  }

  nsVoidArray* row = (nsVoidArray*) mRows.SafeElementAt(rowIndex);
  if (row) {
    CellData* data = (CellData*)row->SafeElementAt(colIndex);
    if (data) {
      return data->GetCellFrame();
    }
  }
  return nsnull;
}

PRBool nsCellMap::Grow(nsTableCellMap& aMap,
                       PRInt32         aNumRows,
                       PRInt32         aRowIndex)
{
  PRInt32 numCols = aMap.GetColCount();
  PRInt32 startRowIndex = (aRowIndex >= 0) ? aRowIndex : mRows.Count();
  PRInt32 endRowIndex = startRowIndex + aNumRows - 1;
  // XXX We really should have a way to say "make this voidarray at least
  // N entries long" to avoid reallocating N times.  On the other hand, the
  // number of likely allocations here isn't TOO gigantic, and we may not
  // know about many of them at a time.
  for (PRInt32 rowX = startRowIndex; rowX <= endRowIndex; rowX++) {
    nsVoidArray* row;
    row = (0 == numCols) ? new nsVoidArray(4) : new nsVoidArray(numCols);
    if (row) {
      mRows.InsertElementAt(row, rowX);
    }
    else return PR_FALSE;
  }
  return PR_TRUE;
}

void nsCellMap::GrowRow(nsVoidArray& aRow,
                        PRInt32      aNumCols)
                     
{
  for (PRInt32 colX = 0; colX < aNumCols; colX++) {
    aRow.AppendElement(nsnull);
  }
}

void
nsCellMap::InsertRows(nsTableCellMap& aMap,
                      nsVoidArray&    aRows,
                      PRInt32         aFirstRowIndex,
                      PRBool          aConsiderSpans,
                      nsRect&         aDamageArea)
{
  PRInt32 numCols = aMap.GetColCount();
  NS_ASSERTION(aFirstRowIndex >= 0, "nsCellMap::InsertRows called with negative rowIndex");
  if (aFirstRowIndex > mRowCount) {
    // create (aFirstRowIndex - mRowCount) empty rows up to aFirstRowIndex
    PRInt32 numEmptyRows = aFirstRowIndex - mRowCount;
    if (!Grow(aMap, numEmptyRows, mRowCount)) {
      return;
    }
    // update mRowCount, since non-empty rows will be added
    mRowCount += numEmptyRows;
  }

  if (!aConsiderSpans) {
    ExpandWithRows(aMap, aRows, aFirstRowIndex, aDamageArea);
    return;
  }

  // if any cells span into or out of the row being inserted, then rebuild
  PRBool spansCauseRebuild = CellsSpanInOrOut(aMap, aFirstRowIndex, 
                                              aFirstRowIndex, 0, numCols - 1);

  // if any of the new cells span out of the new rows being added, then rebuild
  // XXX it would be better to only rebuild the portion of the map that follows the new rows
  if (!spansCauseRebuild && (aFirstRowIndex < mRows.Count())) {
    spansCauseRebuild = CellsSpanOut(aRows);
  }

  if (spansCauseRebuild) {
    aMap.RebuildConsideringRows(this, aFirstRowIndex, &aRows, 0, aDamageArea);
  }
  else {
    ExpandWithRows(aMap, aRows, aFirstRowIndex, aDamageArea);
  }
}

void
nsCellMap::RemoveRows(nsTableCellMap& aMap,
                      PRInt32         aFirstRowIndex,
                      PRInt32         aNumRowsToRemove,
                      PRBool          aConsiderSpans,
                      nsRect&         aDamageArea)
{
  PRInt32 numRows = mRows.Count();
  PRInt32 numCols = aMap.GetColCount();

  if (aFirstRowIndex >= numRows) {
    // reduce the content based row count based on the function arguments
    // as they are known to be real rows even if the cell map did not create
    // rows for them before.
    mRowCount -= aNumRowsToRemove;
    return;
  }
  if (!aConsiderSpans) {
    ShrinkWithoutRows(aMap, aFirstRowIndex, aNumRowsToRemove, aDamageArea);
    return;
  }
  PRInt32 endRowIndex = aFirstRowIndex + aNumRowsToRemove - 1;
  if (endRowIndex >= numRows) {
    NS_ASSERTION(PR_FALSE, "nsCellMap::RemoveRows tried to remove too many rows");
    endRowIndex = numRows - 1;
  }
  PRBool spansCauseRebuild = CellsSpanInOrOut(aMap, aFirstRowIndex, endRowIndex,
                                              0, numCols - 1);

  if (spansCauseRebuild) {
    aMap.RebuildConsideringRows(this, aFirstRowIndex, nsnull, aNumRowsToRemove, aDamageArea);
  }
  else {
    ShrinkWithoutRows(aMap, aFirstRowIndex, aNumRowsToRemove, aDamageArea);
  }
}




CellData* 
nsCellMap::AppendCell(nsTableCellMap&   aMap,
                      nsTableCellFrame* aCellFrame, 
                      PRInt32           aRowIndex,
                      PRBool            aRebuildIfNecessary,
                      nsRect&           aDamageArea,
                      PRInt32*          aColToBeginSearch)
{
  PRInt32 origNumMapRows = mRows.Count();
  PRInt32 origNumCols = aMap.GetColCount();
  PRBool  zeroRowSpan;
  PRInt32 rowSpan = (aCellFrame) ? GetRowSpanForNewCell(*aCellFrame, aRowIndex, zeroRowSpan) : 1;
  // add new rows if necessary
  PRInt32 endRowIndex = aRowIndex + rowSpan - 1;
  if (endRowIndex >= origNumMapRows) {
    Grow(aMap, 1 + endRowIndex - origNumMapRows);
  }

  // get the first null or dead CellData in the desired row. It will equal origNumCols if there are none
  CellData* origData = nsnull;
  PRInt32 startColIndex = 0;
  if (aColToBeginSearch)
    startColIndex = *aColToBeginSearch;
  for (; startColIndex < origNumCols; startColIndex++) {
    CellData* data = GetDataAt(aMap, aRowIndex, startColIndex, PR_TRUE);
    if (!data) 
      break;
    if (data->IsDead()) {
      origData = data;
      break; 
    }
  }
  // We found the place to append the cell, when the next cell is appended 
  // the next search does not need to duplicate the search but can start 
  // just at the next cell.
  if (aColToBeginSearch)
    *aColToBeginSearch =  startColIndex + 1; 
  
  PRBool  zeroColSpan;
  PRInt32 colSpan = (aCellFrame) ? GetColSpanForNewCell(*aCellFrame, startColIndex, origNumCols, zeroColSpan) : 1;

  // if the new cell could potentially span into other rows and collide with 
  // originating cells there, we will play it safe and just rebuild the map
  if (aRebuildIfNecessary && (aRowIndex < mRowCount - 1) && (rowSpan > 1)) {
    nsAutoVoidArray newCellArray;
    newCellArray.AppendElement(aCellFrame);
    aMap.RebuildConsideringCells(this, &newCellArray, aRowIndex, startColIndex, PR_TRUE, aDamageArea);
    return origData;
  }
  mRowCount = PR_MAX(mRowCount, aRowIndex + 1);

  // add new cols to the table map if necessary
  PRInt32 endColIndex = startColIndex + colSpan - 1;
  if (endColIndex >= origNumCols) {
    NS_ASSERTION(aCellFrame, "dead cells should not require new columns");
    aMap.AddColsAtEnd(1 + endColIndex - origNumCols);
  }

  // Setup CellData for this cell
  if (origData) {
    NS_ASSERTION(origData->IsDead(), "replacing a non dead cell is a memory leak");
    if (aCellFrame) { // do nothing to replace a dead cell with a dead cell
      origData->Init(aCellFrame);
      // we are replacing a dead cell, increase the number of cells 
      // originating at this column
      nsColInfo* colInfo = aMap.GetColInfoAt(startColIndex);
      NS_ASSERTION(colInfo, "access to a non existing column");
      if (colInfo) { 
        colInfo->mNumCellsOrig++;
      }
    }
  }
  else {
    origData = (aMap.mBCInfo) ? new BCCellData(aCellFrame) : new CellData(aCellFrame); if (!origData) ABORT1(origData);
    SetDataAt(aMap, *origData, aRowIndex, startColIndex, PR_TRUE);
  }

  SetDamageArea(startColIndex, aRowIndex, 1 + endColIndex - startColIndex, 1 + endRowIndex - aRowIndex, aDamageArea); 

  if (!aCellFrame) {
    return origData;
  }

  // initialize the cell frame
  aCellFrame->SetColIndex(startColIndex);

  // Create CellData objects for the rows that this cell spans. Set
  // their mOrigCell to nsnull and their mSpanData to point to data.
  for (PRInt32 rowX = aRowIndex; rowX <= endRowIndex; rowX++) {
    for (PRInt32 colX = startColIndex; colX <= endColIndex; colX++) {
      if ((rowX != aRowIndex) || (colX != startColIndex)) { // skip orig cell data done above
        CellData* cellData = GetDataAt(aMap, rowX, colX, PR_FALSE);
        if (cellData) {
          if (cellData->IsOrig()) {
            NS_ASSERTION(PR_FALSE, "cannot overlap originating cell");
            continue;
          }
          if (rowX > aRowIndex) { // row spanning into cell
            if (cellData->IsRowSpan()) {
              NS_ASSERTION(PR_FALSE, "invalid overlap");
            }
            else {
              cellData->SetRowSpanOffset(rowX - aRowIndex);
              if (zeroRowSpan) {
                cellData->SetZeroRowSpan(PR_TRUE);
              }
            }
          }
          if (colX > startColIndex) { // col spanning into cell
            if (!cellData->IsColSpan()) { 
              if (cellData->IsRowSpan()) {
                cellData->SetOverlap(PR_TRUE);
              }
              cellData->SetColSpanOffset(colX - startColIndex);
              if (zeroColSpan) {
                cellData->SetZeroColSpan(PR_TRUE);
              }
              // only count the 1st spanned col of a zero col span
              if (!zeroColSpan || (colX == startColIndex + 1)) {
                nsColInfo* colInfo = aMap.GetColInfoAt(colX);
                colInfo->mNumCellsSpan++;
              }
            }
          }
        }
        else { 
          cellData = (aMap.mBCInfo) ? new BCCellData(nsnull) : new CellData(nsnull);
          if (!cellData) return origData;
          if (rowX > aRowIndex) {
            cellData->SetRowSpanOffset(rowX - aRowIndex);
          }
          if (zeroRowSpan) {
            cellData->SetZeroRowSpan(PR_TRUE);
          }
          if (colX > startColIndex) {
            cellData->SetColSpanOffset(colX - startColIndex);
          }
          if (zeroColSpan) {
            cellData->SetZeroColSpan(PR_TRUE);
          }
          // only count the 1st spanned col of a zero col span
          SetDataAt(aMap, *cellData, rowX, colX, (colX == startColIndex + 1));
        }
      }
    }
  }
#ifdef DEBUG_TABLE_CELLMAP
  printf("appended cell=%p row=%d \n", aCellFrame, aRowIndex);
  aMap.Dump();
#endif
  return origData;
}

PRBool nsCellMap::CellsSpanOut(nsVoidArray&    aRows)
{ 
  PRInt32 numNewRows = aRows.Count();
  for (PRInt32 rowX = 0; rowX < numNewRows; rowX++) {
    nsIFrame* rowFrame = (nsIFrame *) aRows.ElementAt(rowX);
    nsIFrame* cellFrame = rowFrame->GetFirstChild(nsnull);
    while (cellFrame) {
      if (IS_TABLE_CELL(cellFrame->GetType())) {
        PRBool zeroSpan;
        PRInt32 rowSpan = GetRowSpanForNewCell((nsTableCellFrame &)*cellFrame, rowX, zeroSpan);
        if (rowX + rowSpan > numNewRows) {
          return PR_TRUE;
        }
      }
      cellFrame = cellFrame->GetNextSibling();
    }
  }
  return PR_FALSE;
}
    
// return PR_TRUE if any cells have rows spans into or out of the region 
// defined by the row and col indices or any cells have colspans into the region
PRBool nsCellMap::CellsSpanInOrOut(nsTableCellMap& aMap,
                                   PRInt32         aStartRowIndex, 
                                   PRInt32         aEndRowIndex,
                                   PRInt32         aStartColIndex, 
                                   PRInt32         aEndColIndex)
{
  /*
   * this routine will watch the cells adjacent to the region or at the edge
   * they are marked with *. The routine will verify whether they span in or
   * are spanned out.
   *
   *                           startCol          endCol
   *             r1c1   r1c2   r1c3      r1c4    r1c5    r1rc6  r1c7
   *  startrow   r2c1   r2c2  *r2c3     *r2c4   *r2c5   *r2rc6  r2c7
   *  endrow     r3c1   r3c2  *r3c3      r3c4    r3c5   *r3rc6  r3c7
   *             r4c1   r4c2  *r4c3     *r4c4   *r4c5    r4rc6  r4c7
   *             r5c1   r5c2   r5c3      r5c4    r5c5    r5rc6  r5c7  
   */

  PRInt32 numRows = mRows.Count(); // use the cellmap rows to determine the 
                                   // current cellmap extent.
  for (PRInt32 colX = aStartColIndex; colX <= aEndColIndex; colX++) {
    CellData* cellData;
    if (aStartRowIndex > 0) {
      cellData = GetDataAt(aMap, aStartRowIndex, colX, PR_TRUE);
      if (cellData && (cellData->IsRowSpan())) {
        return PR_TRUE; // there is a row span into the region
      }
    }
    if (aEndRowIndex < numRows - 1) { // is there anything below aEndRowIndex
      cellData = GetDataAt(aMap, aEndRowIndex + 1, colX, PR_TRUE);
      if ((cellData) && (cellData->IsRowSpan())) {
        return PR_TRUE; // there is a row span out of the region
      }
    }
    else {
      cellData = GetDataAt(aMap, aEndRowIndex, colX, PR_TRUE);
      if ((cellData) && (cellData->IsRowSpan()) && (mRowCount < numRows)) {
        return PR_TRUE; // this cell might be the cause of a dead row
      }
    }
  }
  if (aStartColIndex > 0) {
    for (PRInt32 rowX = aStartRowIndex; rowX <= aEndRowIndex; rowX++) {
      CellData* cellData = GetDataAt(aMap, rowX, aStartColIndex, PR_TRUE);
      if (cellData && (cellData->IsColSpan())) {
        return PR_TRUE; // there is a col span into the region
      }
      nsVoidArray* row = (nsVoidArray *)(mRows.SafeElementAt(rowX));
      if (row) {
        cellData = (CellData *)(row->SafeElementAt(aEndColIndex + 1));
        if (cellData && (cellData->IsColSpan())) {
          return PR_TRUE; // there is a col span out of the region 
        }
      }
    }
  }
  return PR_FALSE;
}

void nsCellMap::InsertCells(nsTableCellMap& aMap,
                            nsVoidArray&    aCellFrames, 
                            PRInt32         aRowIndex,
                            PRInt32         aColIndexBefore,
                            nsRect&         aDamageArea)
{
  if (aCellFrames.Count() == 0) return;
  PRInt32 numCols = aMap.GetColCount();
  if (aColIndexBefore >= numCols) {
    NS_ERROR("Inserting instead of appending cells indicates a serious cellmap error");
    aColIndexBefore = numCols - 1;
  }

  // get the starting col index of the 1st new cells 
  PRInt32 startColIndex;
  for (startColIndex = aColIndexBefore + 1; startColIndex < numCols; startColIndex++) {
    CellData* data = GetDataAt(aMap, aRowIndex, startColIndex, PR_TRUE);
    if (!data || data->IsOrig()) { // stop unless it is a span
      break; 
    }
  }

  // record whether inserted cells are going to cause complications due 
  // to existing row spans, col spans or table sizing. 
  PRBool spansCauseRebuild = PR_FALSE;

  // check that all cells have the same row span
  PRInt32 numNewCells = aCellFrames.Count();
  PRBool zeroRowSpan = PR_FALSE;
  PRInt32 rowSpan = 0;
  for (PRInt32 cellX = 0; cellX < numNewCells; cellX++) {
    nsTableCellFrame* cell = (nsTableCellFrame*) aCellFrames.ElementAt(cellX);
    PRInt32 rowSpan2 = GetRowSpanForNewCell(*cell, aRowIndex, zeroRowSpan);
    if (rowSpan == 0) {
      rowSpan = rowSpan2;
    }
    else if (rowSpan != rowSpan2) {
      spansCauseRebuild = PR_TRUE;
      break;
    }
  }

  // check if the new cells will cause the table to add more rows
  if (!spansCauseRebuild) {
    if (mRows.Count() < aRowIndex + rowSpan) {
      spansCauseRebuild = PR_TRUE;
    }
  }

  if (!spansCauseRebuild) {
    spansCauseRebuild = CellsSpanInOrOut(aMap, aRowIndex, aRowIndex + rowSpan - 1, 
                                         startColIndex, numCols - 1);
  }

  if (spansCauseRebuild) {
    aMap.RebuildConsideringCells(this, &aCellFrames, aRowIndex, startColIndex, PR_TRUE, aDamageArea);
  }
  else {
    ExpandWithCells(aMap, aCellFrames, aRowIndex, startColIndex, rowSpan, zeroRowSpan, aDamageArea);
  }
}
 
void
nsCellMap::ExpandWithRows(nsTableCellMap& aMap,
                          nsVoidArray&    aRowFrames,
                          PRInt32         aStartRowIndexIn,
                          nsRect&         aDamageArea)
{
  PRInt32 startRowIndex = (aStartRowIndexIn >= 0) ? aStartRowIndexIn : 0;
  PRInt32 numNewRows  = aRowFrames.Count();
  PRInt32 endRowIndex = startRowIndex + numNewRows - 1;

  // create the new rows first
  if (!Grow(aMap, numNewRows, startRowIndex)) {
    return;
  }
  mRowCount += numNewRows;

  PRInt32 newRowIndex = 0;
  for (PRInt32 rowX = startRowIndex; rowX <= endRowIndex; rowX++) {
    nsTableRowFrame* rFrame = (nsTableRowFrame *)aRowFrames.ElementAt(newRowIndex);
    // append cells 
    nsIFrame* cFrame = rFrame->GetFirstChild(nsnull);
    PRInt32 colIndex = 0;
    while (cFrame) {
      if (IS_TABLE_CELL(cFrame->GetType())) {
        AppendCell(aMap, (nsTableCellFrame *)cFrame, rowX, PR_FALSE, aDamageArea, &colIndex);
      }
      cFrame = cFrame->GetNextSibling();
    }
    newRowIndex++;
  }

  SetDamageArea(0, startRowIndex, aMap.GetColCount(), 1 + endRowIndex - startRowIndex, aDamageArea); 
}

void nsCellMap::ExpandWithCells(nsTableCellMap& aMap,
                                nsVoidArray&    aCellFrames,
                                PRInt32         aRowIndex,
                                PRInt32         aColIndex,
                                PRInt32         aRowSpan, // same for all cells
                                PRBool          aRowSpanIsZero,
                                nsRect&         aDamageArea)
{
  PRInt32 endRowIndex = aRowIndex + aRowSpan - 1;
  PRInt32 startColIndex = aColIndex;
  PRInt32 endColIndex = aColIndex;
  PRInt32 numCells = aCellFrames.Count();
  PRInt32 totalColSpan = 0;

  // add cellData entries for the space taken up by the new cells
  for (PRInt32 cellX = 0; cellX < numCells; cellX++) {
    nsTableCellFrame* cellFrame = (nsTableCellFrame*) aCellFrames.ElementAt(cellX);
    CellData* origData = (aMap.mBCInfo) ? new BCCellData(cellFrame) : new CellData(cellFrame); // the originating cell
    if (!origData) return;

    // set the starting and ending col index for the new cell
    PRBool zeroColSpan = PR_FALSE;
    PRInt32 colSpan = GetColSpanForNewCell(*cellFrame, aColIndex, aMap.GetColCount(), zeroColSpan);
    totalColSpan += colSpan;
    if (cellX == 0) {
      endColIndex = aColIndex + colSpan - 1;
    }
    else {
      startColIndex = endColIndex + 1;
      endColIndex   = startColIndex + colSpan - 1;
    }
 
    // add the originating cell data and any cell data corresponding to row/col spans
    for (PRInt32 rowX = aRowIndex; rowX <= endRowIndex; rowX++) {
      nsVoidArray* row = (nsVoidArray *)mRows.ElementAt(rowX);
      for (PRInt32 colX = aColIndex; colX <= endColIndex; colX++) {
        row->InsertElementAt(nsnull, colX);
        CellData* data = origData;
        if ((rowX != aRowIndex) || (colX != startColIndex)) {
          data = (aMap.mBCInfo) ? new BCCellData(nsnull) : new CellData(nsnull);
          if (!data) return;
          if (rowX > aRowIndex) {
            data->SetRowSpanOffset(rowX - aRowIndex);
            if (aRowSpanIsZero) {
              data->SetZeroRowSpan(PR_TRUE);
            }
          }
          if (colX > startColIndex) {
            data->SetColSpanOffset(colX - startColIndex);
            if (zeroColSpan) {
              data->SetZeroColSpan(PR_TRUE);
            }
          }
        }
        // only count 1st spanned col of colspan=0
        SetDataAt(aMap, *data, rowX, colX, (colX == aColIndex + 1)); 
      }
    }
    cellFrame->SetColIndex(startColIndex);
  }
  PRInt32 damageHeight = (aRowSpanIsZero) ? aMap.GetColCount() - aRowIndex : aRowSpan;
  SetDamageArea(aColIndex, aRowIndex, 1 + endColIndex - aColIndex, damageHeight, aDamageArea); 

  PRInt32 rowX;

  // update the row and col info due to shifting
  for (rowX = aRowIndex; rowX <= endRowIndex; rowX++) {
    nsVoidArray* row = (nsVoidArray *)mRows.ElementAt(rowX);
    PRInt32 numCols = row->Count();
    PRInt32 colX;
    for (colX = aColIndex + totalColSpan; colX < numCols; colX++) {
      CellData* data = (CellData*) row->ElementAt(colX);
      if (data) {
        // increase the origin and span counts beyond the spanned cols
        if (data->IsOrig()) {
          // a cell that gets moved needs adjustment as well as it new orignating col
          data->GetCellFrame()->SetColIndex(colX);
          nsColInfo* colInfo = aMap.GetColInfoAt(colX);
          colInfo->mNumCellsOrig++;
        }
        // if the colspan is 0 only count the 1st spanned col
        PRBool countAsSpan = PR_FALSE;
        if (data->IsColSpan()) {
          if ( (!data->IsZeroColSpan()) ||
               ((data->IsZeroColSpan()) && (colX > aColIndex + totalColSpan) &&
                (!IsZeroColSpan(rowX, colX - 1)))) {
            nsColInfo* colInfo = aMap.GetColInfoAt(colX);
            colInfo->mNumCellsSpan++;
            countAsSpan = PR_TRUE;
          }
        }
        
        // decrease the origin and span counts within the spanned cols
        PRInt32 colX2 = colX - totalColSpan;
        nsColInfo* colInfo2 = aMap.GetColInfoAt(colX2);
        if (data->IsOrig()) {
          // the old originating col of a moved cell needs adjustment
          colInfo2->mNumCellsOrig--;
        }
        else if (countAsSpan) {
          colInfo2->mNumCellsSpan--;
        }
      }
    }
  }
}

void nsCellMap::ShrinkWithoutRows(nsTableCellMap& aMap,
                                  PRInt32         aStartRowIndex,
                                  PRInt32         aNumRowsToRemove,
                                  nsRect&         aDamageArea)
{
  PRInt32 endRowIndex = aStartRowIndex + aNumRowsToRemove - 1;
  PRInt32 colCount = aMap.GetColCount();
  for (PRInt32 rowX = endRowIndex; rowX >= aStartRowIndex; --rowX) {
    nsVoidArray* row = (nsVoidArray *)(mRows.ElementAt(rowX));
    PRInt32 colX;
    for (colX = 0; colX < colCount; colX++) {
      CellData* data = (CellData *) row->SafeElementAt(colX);
      if (data) {
        // Adjust the column counts.
        if (data->IsOrig()) {
          // Decrement the column count.
          nsColInfo* colInfo = aMap.GetColInfoAt(colX);
          colInfo->mNumCellsOrig--;
        }
        // colspan=0 is only counted as a spanned cell in the 1st col it spans
        else if (data->IsColSpan()) {
          if ( (!data->IsZeroColSpan()) ||
               ((data->IsZeroColSpan()) && (rowX == aStartRowIndex) && (!IsZeroColSpan(rowX, colX - 1)))) {
            nsColInfo* colInfo = aMap.GetColInfoAt(colX);
            colInfo->mNumCellsSpan--;
          }
        }
      }
    }

    PRInt32 rowLength = row->Count();
    // Delete our row information.
    for (colX = 0; colX < rowLength; colX++) {
      CellData* data = (CellData *)(row->ElementAt(colX));
      if (data) {
        delete data;
      }
    }

    mRows.RemoveElementAt(rowX);
    delete row;

    // Decrement our row and next available index counts.
    mRowCount--;
  }
  aMap.RemoveColsAtEnd();

  SetDamageArea(0, aStartRowIndex, aMap.GetColCount(), 0, aDamageArea); 
}

PRInt32 nsCellMap::GetColSpanForNewCell(nsTableCellFrame& aCellFrameToAdd, 
                                        PRInt32           aColIndex,
                                        PRInt32           aNumColsInTable,
                                        PRBool&           aIsZeroColSpan)
{
  aIsZeroColSpan = PR_FALSE;
  PRInt32 colSpan = aCellFrameToAdd.GetColSpan();
  if (0 == colSpan) {
    // use a min value for a zero colspan to make computations easier elsewhere 
    colSpan = PR_MAX(MIN_NUM_COLS_FOR_ZERO_COLSPAN, aNumColsInTable - aColIndex);
    aIsZeroColSpan = PR_TRUE;
  }
  return colSpan;
}

PRInt32 nsCellMap::GetEffectiveColSpan(nsTableCellMap& aMap,
                                       PRInt32         aRowIndex,
                                       PRInt32         aColIndex,
                                       PRBool&         aZeroColSpan)
{
  PRInt32 numColsInTable = aMap.GetColCount();
  aZeroColSpan = PR_FALSE;
  PRInt32 colSpan = 1;
  nsVoidArray* row = (nsVoidArray *)(mRows.SafeElementAt(aRowIndex));
  if (row) {
    PRInt32 colX;
    CellData* data;
    PRInt32 maxCols = numColsInTable;
    PRBool hitOverlap = PR_FALSE; // XXX this is not ever being set to PR_TRUE
    for (colX = aColIndex + 1; colX < maxCols; colX++) {
      data = GetDataAt(aMap, aRowIndex, colX, PR_TRUE);
      if (data) {
        // for an overlapping situation get the colspan from the originating cell and
        // use that as the max number of cols to iterate. Since this is rare, only 
        // pay the price of looking up the cell's colspan here.
        if (!hitOverlap && data->IsOverlap()) {
          CellData* origData = GetDataAt(aMap, aRowIndex, aColIndex, PR_TRUE);
          if (origData && origData->IsOrig()) {
            nsTableCellFrame* cellFrame = origData->GetCellFrame();
            if (cellFrame) {
              // possible change the number of colums to iterate
              maxCols = PR_MIN(aColIndex + cellFrame->GetColSpan(), maxCols);
              if (colX >= maxCols) 
                break;
            }
          }
        }
        if (data->IsColSpan()) {
          colSpan++;
          if (data->IsZeroColSpan()) {
            aZeroColSpan = PR_TRUE;
          }
        }
        else {
          break;
        }
      }
      else break;
    }
  }
  return colSpan;
}

PRInt32 
nsCellMap::GetRowSpanForNewCell(nsTableCellFrame& aCellFrameToAdd, 
                                PRInt32           aRowIndex,
                                PRBool&           aIsZeroRowSpan)
{
  aIsZeroRowSpan = PR_FALSE;
  PRInt32 rowSpan = aCellFrameToAdd.GetRowSpan();
  if (0 == rowSpan) {
    // use a min value of 2 for a zero rowspan to make computations easier elsewhere 
    rowSpan = PR_MAX(2, mRows.Count() - aRowIndex);
    aIsZeroRowSpan = PR_TRUE;
  }
  return rowSpan;
}

PRBool nsCellMap::HasMoreThanOneCell(nsTableCellMap& aMap,
                                     PRInt32       aRowIndex)
{
  nsVoidArray* row = (nsVoidArray *)(mRows.SafeElementAt(aRowIndex));
  if (row) {
    PRInt32 maxColIndex = row->Count();
    PRInt32 count = 0;
    PRInt32 colIndex;
    for (colIndex = 0; colIndex < maxColIndex; colIndex++) {
      CellData* cellData = GetDataAt(aMap, aRowIndex, colIndex, PR_FALSE);
      if (cellData && (cellData->GetCellFrame() || cellData->IsRowSpan()))
        count++;
      if (count > 1)
        return PR_TRUE;
    }
  }
  return PR_FALSE;
}

PRInt32 nsCellMap::GetRowSpan(nsTableCellMap& aMap,
                              PRInt32         aRowIndex,
                              PRInt32         aColIndex,
                              PRBool          aGetEffective,
                              PRBool&         aZeroRowSpan)
{
  aZeroRowSpan = PR_FALSE;
  PRInt32 rowSpan = 1;
  PRInt32 rowCount = (aGetEffective) ? mRowCount : mRows.Count();
  PRInt32 rowX;
  for (rowX = aRowIndex + 1; rowX < rowCount; rowX++) {
    CellData* data = GetDataAt(aMap, rowX, aColIndex, PR_TRUE);
    if (data) {
      if (data->IsRowSpan()) {
        rowSpan++;
        if (data->IsZeroRowSpan()) {
          aZeroRowSpan = PR_TRUE;
        }
      }
      else {
        break;
      }
    } 
    else break;
  }
  if (aZeroRowSpan && (rowX < rowCount)) {
    rowSpan += rowCount - rowX;
  }
  return rowSpan;
}

void nsCellMap::ShrinkWithoutCell(nsTableCellMap&   aMap,
                                  nsTableCellFrame& aCellFrame,
                                  PRInt32           aRowIndex,
                                  PRInt32           aColIndex,
                                  nsRect&           aDamageArea)
{
  PRInt32 colX, rowX;

  // get the rowspan and colspan from the cell map since the content may have changed
  PRBool  zeroRowSpan, zeroColSpan;
  PRInt32 numCols = aMap.GetColCount();
  PRInt32 rowSpan = GetRowSpan(aMap, aRowIndex, aColIndex, PR_FALSE, zeroRowSpan);
  PRInt32 colSpan = GetEffectiveColSpan(aMap, aRowIndex, aColIndex, zeroColSpan);
  PRInt32 endRowIndex = aRowIndex + rowSpan - 1;
  PRInt32 endColIndex = aColIndex + colSpan - 1;

  SetDamageArea(aColIndex, aRowIndex, 1 + endColIndex - aColIndex, 1 + endRowIndex - aRowIndex, aDamageArea); 

  // adjust the col counts due to the deleted cell before removing it
  for (colX = aColIndex; colX <= endColIndex; colX++) {
    nsColInfo* colInfo = aMap.GetColInfoAt(colX);
    if (colX == aColIndex) {
      colInfo->mNumCellsOrig--;
    }
    // a colspan=0 cell is only counted as a spanner in the 1st col it spans
    else if (!zeroColSpan || (zeroColSpan && (colX == aColIndex + 1))) {
      colInfo->mNumCellsSpan--;
    }
  }

  // remove the deleted cell and cellData entries for it
  for (rowX = aRowIndex; rowX <= endRowIndex; rowX++) {
    nsVoidArray* row = (nsVoidArray *)mRows.ElementAt(rowX);
    for (colX = endColIndex; colX >= aColIndex; colX--) {
      CellData* doomedData = (CellData*) row->ElementAt(colX);
      delete doomedData;
      row->RemoveElementAt(colX);
    }
  }

  numCols = aMap.GetColCount();

  // update the row and col info due to shifting
  for (rowX = aRowIndex; rowX <= endRowIndex; rowX++) {
    nsVoidArray* row = (nsVoidArray *)mRows.ElementAt(rowX);
    PRInt32 rowCount = row->Count();
    for (colX = aColIndex; colX < numCols - colSpan; colX++) {
      CellData* data = (colX < rowCount) ? (CellData*)row->ElementAt(colX) : nsnull;
      if (data) {
        if (data->IsOrig()) {
          // a cell that gets moved to the left needs adjustment in its new location 
          data->GetCellFrame()->SetColIndex(colX);
          nsColInfo* colInfo = aMap.GetColInfoAt(colX);
          colInfo->mNumCellsOrig++;
          // a cell that gets moved to the left needs adjustment in its old location 
          colInfo = aMap.GetColInfoAt(colX + colSpan);
          if (colInfo) {
            colInfo->mNumCellsOrig--;
          }
        }
        // a colspan=0 cell is only counted as a spanner in the 1st col it spans
        else if (data->IsColSpan()) {
          if ( (!data->IsZeroColSpan()) ||
               ((data->IsZeroColSpan()) && (rowX == aRowIndex) && (!IsZeroColSpan(rowX, colX - 1)))) {
            // a cell that gets moved to the left needs adjustment in its new location 
            nsColInfo* colInfo = aMap.GetColInfoAt(colX);
            colInfo->mNumCellsSpan++;
            // a cell that gets moved to the left needs adjustment in its old location 
            colInfo = aMap.GetColInfoAt(colX + colSpan);
            if (colInfo) {
              colInfo->mNumCellsSpan--;
            }
          }
        }
      }
    }
  }
  aMap.RemoveColsAtEnd();
}

void
nsCellMap::RebuildConsideringRows(nsTableCellMap& aMap,
                                  PRInt32         aStartRowIndex,
                                  nsVoidArray*    aRowsToInsert,
                                  PRBool          aNumRowsToRemove,
                                  nsRect&         aDamageArea)
{
  // copy the old cell map into a new array
  PRInt32 numOrigRows = mRows.Count();
  void** origRows = new void*[numOrigRows];
  if (!origRows) return;
  PRInt32 rowX, colX;
  // copy the orig rows
  for (rowX = 0; rowX < numOrigRows; rowX++) {
    nsVoidArray* row = (nsVoidArray *)mRows.ElementAt(rowX);
    origRows[rowX] = row;
  }

  mRows.Clear();
  // adjust mRowCount based on the function arguments as they are known to
  // be real rows.
  mRowCount -= aNumRowsToRemove;
  if (aRowsToInsert) { 
    mRowCount += aRowsToInsert->Count();
    Grow(aMap, numOrigRows); 
  }

  // aStartRowIndex might be after all existing rows so we should limit the
  // copy to the amount of exisiting rows
  PRInt32 copyEndRowIndex = PR_MIN(numOrigRows, aStartRowIndex);

  // put back the rows before the affected ones just as before
  for (rowX = 0; rowX < copyEndRowIndex; rowX++) {
    nsVoidArray* row = (nsVoidArray *)origRows[rowX];
    PRInt32 numCols = row->Count();
    for (colX = 0; colX < numCols; colX++) {
      // put in the original cell from the cell map
      CellData* data = (CellData*) row->ElementAt(colX);
      if (data && data->IsOrig()) {
        AppendCell(aMap, data->GetCellFrame(), rowX, PR_FALSE, aDamageArea);
      }
    }
  }
  PRInt32 copyStartRowIndex;
  if (aRowsToInsert) {
    // add in the new cells and create rows if necessary
    PRInt32 numNewRows = aRowsToInsert->Count();
    rowX = aStartRowIndex;
    for (PRInt32 newRowX = 0; newRowX < numNewRows; newRowX++) {
      nsTableRowFrame* rFrame = (nsTableRowFrame *)aRowsToInsert->ElementAt(newRowX);
      nsIFrame* cFrame = rFrame->GetFirstChild(nsnull);
      while (cFrame) {
        if (IS_TABLE_CELL(cFrame->GetType())) {
          AppendCell(aMap, (nsTableCellFrame *)cFrame, rowX, PR_FALSE, aDamageArea);
        }
        cFrame = cFrame->GetNextSibling();
      }
      rowX++;
    }
    copyStartRowIndex = aStartRowIndex;
  }
  else {
    rowX = aStartRowIndex;
    copyStartRowIndex = aStartRowIndex + aNumRowsToRemove;
  }
  // put back the rows after the affected ones just as before
  for (PRInt32 copyRowX = copyStartRowIndex; copyRowX < numOrigRows; copyRowX++) {
    nsVoidArray* row = (nsVoidArray *)origRows[copyRowX];
    PRInt32 numCols = row->Count();
    for (colX = 0; colX < numCols; colX++) {
      // put in the original cell from the cell map
      CellData* data = (CellData*) row->ElementAt(colX);
      if (data && data->IsOrig()) {
        AppendCell(aMap, data->GetCellFrame(), rowX, PR_FALSE, aDamageArea);
      }
    }
    rowX++;
  }

  // delete the old cell map
  for (rowX = 0; rowX < numOrigRows; rowX++) {
    nsVoidArray* row = (nsVoidArray *)origRows[rowX];
    PRInt32 len = row->Count();
    for (colX = 0; colX < len; colX++) {
      CellData* data = (CellData*) row->ElementAt(colX);
      delete data;
    }
    delete row;
  }
  delete [] origRows;

  SetDamageArea(0, 0, aMap.GetColCount(), GetRowCount(), aDamageArea); 
}

void nsCellMap::RebuildConsideringCells(nsTableCellMap& aMap,
                                        PRInt32         aNumOrigCols,
                                        nsVoidArray*    aCellFrames,
                                        PRInt32         aRowIndex,
                                        PRInt32         aColIndex,
                                        PRBool          aInsert,
                                        nsRect&         aDamageArea)
{
  // copy the old cell map into a new array
  PRInt32 mRowCountOrig = mRowCount;
  PRInt32 numOrigRows   = mRows.Count();
  void** origRows = new void*[numOrigRows];
  if (!origRows) return;
  PRInt32 rowX;
  for (rowX = 0; rowX < numOrigRows; rowX++) {
    nsVoidArray* row = (nsVoidArray *)mRows.ElementAt(rowX);
    origRows[rowX] = row;
  }

  // reinitialize data members
  mRows.Clear();
  mRowCount = 0;

  PRInt32 numNewCells = (aCellFrames) ? aCellFrames->Count() : 0;
  
  // the new cells might extend the previous column number
  NS_ASSERTION(aNumOrigCols >= aColIndex, "Appending cells far beyond cellmap data?!");
  PRInt32 numCols = aInsert ? PR_MAX(aNumOrigCols, aColIndex + 1) : aNumOrigCols;  
  
  // build the new cell map 
  for (rowX = 0; rowX < numOrigRows; rowX++) {
    nsVoidArray* row = (nsVoidArray *)origRows[rowX];
    for (PRInt32 colX = 0; colX < numCols; colX++) {
      if ((rowX == aRowIndex) && (colX == aColIndex)) { 
        if (aInsert) { // put in the new cells
          for (PRInt32 cellX = 0; cellX < numNewCells; cellX++) {
            nsTableCellFrame* cell = (nsTableCellFrame*)aCellFrames->ElementAt(cellX);
            if (cell) {
              AppendCell(aMap, cell, rowX, PR_FALSE, aDamageArea);
            }
          }
        }
        else {
          continue; // do not put the deleted cell back
        }
      }
      // put in the original cell from the cell map
      CellData* data = (CellData*) row->SafeElementAt(colX);
      if (data && data->IsOrig()) {
        AppendCell(aMap, data->GetCellFrame(), rowX, PR_FALSE, aDamageArea);
      }
    }
  }

  if (aInsert && numOrigRows <= aRowIndex) { // append the new cells 
                                             // below the last original row
    NS_ASSERTION (numOrigRows == aRowIndex, 
                  "Appending cells far beyond the last row");
    for (PRInt32 cellX = 0; cellX < numNewCells; cellX++) {
      nsTableCellFrame* cell = (nsTableCellFrame*)aCellFrames->ElementAt(cellX);
      if (cell) {
        AppendCell(aMap, cell, aRowIndex, PR_FALSE, aDamageArea);
      }
    }
  }
  // For for cell deletion, since the row is not being deleted, 
  // keep mRowCount the same as before. 
  mRowCount = PR_MAX(mRowCount, mRowCountOrig);

  // delete the old cell map
  for (rowX = 0; rowX < numOrigRows; rowX++) {
    nsVoidArray* row = (nsVoidArray *)origRows[rowX];
    PRInt32 len = row->Count();
    for (PRInt32 colX = 0; colX < len; colX++) {
      CellData* data = (CellData*) row->SafeElementAt(colX);
      if(data)
        delete data;
    }
    delete row;
  }
  delete [] origRows; 
}

void nsCellMap::RemoveCell(nsTableCellMap&   aMap,
                           nsTableCellFrame* aCellFrame,
                           PRInt32           aRowIndex,
                           nsRect&           aDamageArea)
{
  PRInt32 numRows = mRows.Count();
  if ((aRowIndex < 0) || (aRowIndex >= numRows)) {
    NS_ASSERTION(PR_FALSE, "bad arg in nsCellMap::RemoveCell");
    return;
  }
  PRInt32 numCols = aMap.GetColCount();

  // get the starting col index of the cell to remove
  PRInt32 startColIndex;
  for (startColIndex = 0; startColIndex < numCols; startColIndex++) {
    CellData* data = GetDataAt(aMap, aRowIndex, startColIndex, PR_FALSE);
    if (data && (data->IsOrig()) && (aCellFrame == data->GetCellFrame())) {
      break; // we found the col index
    }
  }

  PRBool isZeroRowSpan;
  PRInt32 rowSpan = GetRowSpan(aMap, aRowIndex, startColIndex, PR_FALSE, isZeroRowSpan);
  // record whether removing the cells is going to cause complications due 
  // to existing row spans, col spans or table sizing. 
  PRBool spansCauseRebuild = CellsSpanInOrOut(aMap, aRowIndex, aRowIndex + rowSpan - 1, 
                                              startColIndex, numCols - 1);
  // XXX if the cell has a col span to the end of the map, and the end has no originating 
  // cells, we need to assume that this the only such cell, and rebuild so that there are 
  // no extraneous cols at the end. The same is true for removing rows.
  if (!aCellFrame->GetRowSpan() || !aCellFrame->GetColSpan())
    spansCauseRebuild = PR_TRUE;

  if (spansCauseRebuild) {
    aMap.RebuildConsideringCells(this, nsnull, aRowIndex, startColIndex, PR_FALSE, aDamageArea);
  }
  else {
    ShrinkWithoutCell(aMap, *aCellFrame, aRowIndex, startColIndex, aDamageArea);
  }
}

#ifdef NS_DEBUG
void nsCellMap::Dump(PRBool aIsBorderCollapse) const
{
  printf("\n  ***** START GROUP CELL MAP DUMP ***** %p\n", this);
  nsTableRowGroupFrame* rg = GetRowGroup();
  const nsStyleDisplay* display = rg->GetStyleDisplay();
  switch (display->mDisplay) {
  case NS_STYLE_DISPLAY_TABLE_HEADER_GROUP:
    printf("  thead ");
    break;
  case NS_STYLE_DISPLAY_TABLE_FOOTER_GROUP:
    printf("  tfoot ");
    break;
  case NS_STYLE_DISPLAY_TABLE_ROW_GROUP:
    printf("  tbody ");
    break;
  default:
    printf("HUH? wrong display type on rowgroup");
  }
  PRInt32 mapRowCount = mRows.Count();
  printf("mapRowCount=%d tableRowCount=%d\n", mapRowCount, mRowCount);
  

  PRInt32 rowIndex, colIndex;
  for (rowIndex = 0; rowIndex < mapRowCount; rowIndex++) {
    nsVoidArray* row = (nsVoidArray *)mRows.ElementAt(rowIndex);
    printf("  row %d : ", rowIndex);
    PRInt32 colCount = row->Count();
    for (colIndex = 0; colIndex < colCount; colIndex++) {
      CellData* cd = (CellData *)row->ElementAt(colIndex);
      if (cd) {
        if (cd->IsOrig()) {
          printf("C%d,%d  ", rowIndex, colIndex);
        } else {
          nsTableCellFrame* cell = nsnull;
          if (cd->IsRowSpan()) {
            cell = GetCellFrame(rowIndex, colIndex, *cd, PR_TRUE);
            printf("R ");
          }
          if (cd->IsColSpan()) {
            cell = GetCellFrame(rowIndex, colIndex, *cd, PR_FALSE);
            printf("C ");
          }
          if (!(cd->IsRowSpan() && cd->IsColSpan())) {
            printf("  ");
          } 
          printf("  ");  
        }
      } else {
        printf("----  ");
      }
    }
    if (aIsBorderCollapse) {
      nscoord       size;
      BCBorderOwner owner;
      PRUint8       side;
      PRBool        segStart;
      PRPackedBool  bevel;      
      for (PRInt32 i = 0; i <= 2; i++) {
        printf("\n          ");
        for (colIndex = 0; colIndex < colCount; colIndex++) {
          BCCellData* cd = (BCCellData *)row->ElementAt(colIndex);
          if (cd) {
            if (0 == i) {
              size = cd->mData.GetTopEdge(owner, segStart);
              printf("t=%d%d%d ", size, owner, segStart);
            }
            else if (1 == i) {
              size = cd->mData.GetLeftEdge(owner, segStart);
              printf("l=%d%d%d ", size, owner, segStart);
            }
            else {
              size = cd->mData.GetCorner(side, bevel);
              printf("c=%d%d%d ", size, side, bevel);
            }
          }
        }
      }
    }
    printf("\n");
  }

  // output info mapping Ci,j to cell address
  PRInt32 cellCount = 0;
  for (PRInt32 rIndex = 0; rIndex < mapRowCount; rIndex++) {
    nsVoidArray* row = (nsVoidArray *)mRows.ElementAt(rIndex);
    PRInt32 colCount = row->Count();
    printf("  ");
    for (colIndex = 0; colIndex < colCount; colIndex++) {
      CellData* cd = (CellData *)row->ElementAt(colIndex);
      if (cd) {
        if (cd->IsOrig()) {
          nsTableCellFrame* cellFrame = cd->GetCellFrame();
          PRInt32 cellFrameColIndex;
          cellFrame->GetColIndex(cellFrameColIndex);
          printf("C%d,%d=%p(%d)  ", rIndex, colIndex, cellFrame, cellFrameColIndex);
          cellCount++;
        }
      }
    }
    printf("\n");
  }

  printf("  ***** END GROUP CELL MAP DUMP *****\n");
}
#endif

PRBool 
nsCellMap::IsZeroColSpan(PRInt32 aRowIndex,
                         PRInt32 aColIndex) const
{
  nsVoidArray* row = (nsVoidArray*)mRows.SafeElementAt(aRowIndex);
  if (row) {
    CellData* data = (CellData*)row->SafeElementAt(aColIndex);
    if (data && data->IsZeroColSpan()) {
      return PR_TRUE;
    }
  }
  return PR_FALSE;
}

void 
nsCellMap::AdjustForZeroSpan(nsTableCellMap& aMap,
                             PRInt32         aRowIndex,
                             PRInt32         aColIndex)
{
  PRInt32 numColsInTable = aMap.GetColCount();
  CellData* data = GetDataAt(aMap, aRowIndex, aColIndex, PR_FALSE);
  if (!data) return;

  nsTableCellFrame* cell = (data->IsOrig()) ? data->GetCellFrame() : nsnull;
  if (!cell) return;

  PRInt32 cellRowSpan = cell->GetRowSpan();
  PRInt32 cellColSpan = cell->GetColSpan();

  PRInt32 endRowIndex = (0 == cell->GetRowSpan()) ? mRows.Count() - 1 : aRowIndex + cellRowSpan - 1;
  PRInt32 endColIndex = (0 == cell->GetColSpan()) ? numColsInTable - 1 : aColIndex + cellColSpan - 1;
  // if there is both a rowspan=0 and colspan=0 then only expand the cols to a minimum
  if ((0 == cellRowSpan) && (0 == cellColSpan)) {
    endColIndex = aColIndex + MIN_NUM_COLS_FOR_ZERO_COLSPAN - 1;
  }

  // Create span CellData objects filling out the rows to the end of the
  // map if the rowspan is 0, and/or filling out the cols to the end of 
  // table if the colspan is 0. If there is both a rowspan=0 and colspan=0
  // then only fill out the cols to a minimum value.
  for (PRInt32 colX = aColIndex; colX <= endColIndex; colX++) {
    PRInt32 rowX;
    // check to see if there is any cells originating after the cols 
    PRBool cellsOrig = PR_FALSE;
    if (colX >= aColIndex + MIN_NUM_COLS_FOR_ZERO_COLSPAN - 1) {
      for (rowX = aRowIndex; rowX <= endRowIndex; rowX++) {
        CellData* cellData = GetDataAt(aMap, rowX, colX, PR_FALSE);
        if (cellData && cellData->IsOrig()) {
          cellsOrig = PR_TRUE;
          break; // there are cells in this col, so don't consider it
        }
      }
    }
    if (cellsOrig) break;
    for (rowX = aRowIndex; rowX <= endRowIndex; rowX++) {
      if ((colX > aColIndex) || (rowX > aRowIndex)) {
        CellData* oldData = GetDataAt(aMap, rowX, colX, PR_FALSE); 
        if (!oldData) {
          CellData* newData = (aMap.mBCInfo) ? new BCCellData(nsnull) : new CellData(nsnull);
          if (!newData) return;
          if (colX > aColIndex) {
            newData->SetColSpanOffset(colX - aColIndex);
            newData->SetZeroColSpan(PR_TRUE);
          }
          if (rowX > aRowIndex) {
            newData->SetRowSpanOffset(rowX - aRowIndex);
            newData->SetZeroRowSpan(PR_TRUE);
          }
          // colspan=0 is only counted as spanning the 1st col to the right of its origin
          SetDataAt(aMap, *newData, rowX, colX, (colX == aColIndex + 1));
        }
      }
    }
  }
}

CellData* 
nsCellMap::GetDataAt(nsTableCellMap& aMap,
                     PRInt32         aMapRowIndex, 
                     PRInt32         aColIndex,
                     PRBool          aUpdateZeroSpan)
{
  PRInt32 numColsInTable = aMap.GetColCount();
  if ((aMapRowIndex < 0) || (aMapRowIndex >= mRows.Count())) {
    return nsnull;
  }

  nsVoidArray* row = (nsVoidArray *)(mRows.ElementAt(aMapRowIndex));
  if (!row) return nsnull;

  CellData* data = (CellData *)(row->SafeElementAt(aColIndex));
  if (!data && aUpdateZeroSpan) {
    PRBool didZeroExpand = PR_FALSE;
    // check for special zero row span
    PRInt32 prevRowX = aMapRowIndex - 1;
    // find the last non null data in the same col
    for ( ; prevRowX > 0; prevRowX--) {
      nsVoidArray* prevRow = (nsVoidArray *)(mRows.ElementAt(prevRowX));
      CellData* prevData = (CellData *)(prevRow->SafeElementAt(aColIndex));
      if (prevData) {
        if (prevData->IsZeroRowSpan()) {
          PRInt32 rowIndex = prevRowX - prevData->GetRowSpanOffset();
          PRInt32 colIndex = 0;
          // if there is a colspan and no overlap then the rowspan offset 
          // and colspan offset point to the same cell
          if ((prevData->IsColSpan()) && (!prevData->IsOverlap())) {
            colIndex = prevData->GetColSpanOffset();
          }
          AdjustForZeroSpan(aMap, rowIndex, colIndex);
          didZeroExpand = PR_TRUE;
        }
        break;
      }
    }

    // check for special zero col span
    if (!didZeroExpand && (aColIndex > 0) && (aColIndex < numColsInTable)) { 
      PRInt32 prevColX = aColIndex - 1;
      // find the last non null data in the same row
      for ( ; prevColX > 0; prevColX--) {
        CellData* prevData = GetDataAt(aMap, aMapRowIndex, prevColX, PR_FALSE);
        if (prevData) {
          if (prevData->IsZeroColSpan()) {
            PRInt32 colIndex = prevColX - prevData->GetColSpanOffset();
            // if there were also a rowspan, it would have been handled above
            AdjustForZeroSpan(aMap, aMapRowIndex, colIndex);
            didZeroExpand = PR_TRUE;
          }
          break;
        }
      }
    }

    // if zero span adjustments were made the data may be available now
    if (!data && didZeroExpand) {
      data = GetDataAt(aMap, aMapRowIndex, aColIndex, PR_FALSE);
    }
  }
  return data;
}

// only called if the cell at aMapRowIndex, aColIndex is null
void nsCellMap::SetDataAt(nsTableCellMap& aMap,
                          CellData&       aNewCell, 
                          PRInt32         aMapRowIndex, 
                          PRInt32         aColIndex,
                          PRBool          aCountZeroSpanAsSpan)
{
  nsVoidArray* row = (nsVoidArray *)(mRows.SafeElementAt(aMapRowIndex));
  if (row) {
    // the table map may need cols added
    PRInt32 numColsToAdd = aColIndex + 1 - aMap.GetColCount();
    if (numColsToAdd > 0) {
      aMap.AddColsAtEnd(numColsToAdd);
    }
    // the row may need cols added
    numColsToAdd = aColIndex + 1 - row->Count();
    if (numColsToAdd > 0) {
      GrowRow(*row, numColsToAdd);
    }

    CellData* doomedData = (CellData*)row->ElementAt(aColIndex);
    delete doomedData;

    row->ReplaceElementAt(&aNewCell, aColIndex);
    // update the originating cell counts if cell originates in this row, col
    nsColInfo* colInfo = aMap.GetColInfoAt(aColIndex);
    if (colInfo) {
      if (aNewCell.IsOrig()) { 
        colInfo->mNumCellsOrig++;
      }
      else if ((aNewCell.IsColSpan()) && 
               (!aNewCell.IsZeroColSpan() || aCountZeroSpanAsSpan)) {
        colInfo->mNumCellsSpan++;
      }
    }
    else NS_ASSERTION(PR_FALSE, "SetDataAt called with col index > table map num cols");
  }
  else NS_ASSERTION(PR_FALSE, "SetDataAt called with row index > num rows");
}

nsTableCellFrame* 
nsCellMap::GetCellInfoAt(nsTableCellMap& aMap,
                         PRInt32         aRowX, 
                         PRInt32         aColX, 
                         PRBool*         aOriginates, 
                         PRInt32*        aColSpan)
{
  if (aOriginates) {
    *aOriginates = PR_FALSE;
  }
  CellData* data = GetDataAt(aMap, aRowX, aColX, PR_TRUE);
  nsTableCellFrame* cellFrame = nsnull;  
  if (data) {
    if (data->IsOrig()) {
      cellFrame = data->GetCellFrame();
      if (aOriginates)
        *aOriginates = PR_TRUE;
      if (cellFrame && aColSpan) {
        PRInt32 initialColIndex;
        cellFrame->GetColIndex(initialColIndex);
        PRBool zeroSpan;
        *aColSpan = GetEffectiveColSpan(aMap, aRowX, initialColIndex, zeroSpan);
      }
    }
    else {
      cellFrame = GetCellFrame(aRowX, aColX, *data, PR_TRUE);
      if (aColSpan)
        *aColSpan = 0;
    }
  }
  return cellFrame;
}
  

PRBool nsCellMap::RowIsSpannedInto(nsTableCellMap& aMap,
                                   PRInt32         aRowIndex)
{
  PRInt32 numColsInTable = aMap.GetColCount();
  if ((0 > aRowIndex) || (aRowIndex >= mRowCount)) {
    return PR_FALSE;
  }
  for (PRInt32 colIndex = 0; colIndex < numColsInTable; colIndex++) {
    CellData* cd = GetDataAt(aMap, aRowIndex, colIndex, PR_TRUE);
    if (cd) { // there's really a cell at (aRowIndex, colIndex)
      if (cd->IsSpan()) { // the cell at (aRowIndex, colIndex) is the result of a span
        if (cd->IsRowSpan() && GetCellFrame(aRowIndex, colIndex, *cd, PR_TRUE)) { // XXX why the last check
          return PR_TRUE;
        }
      }
    }
  }
  return PR_FALSE;
}

PRBool nsCellMap::RowHasSpanningCells(nsTableCellMap& aMap,
                                      PRInt32         aRowIndex)
{
  PRInt32 numColsInTable = aMap.GetColCount();
  if ((0 > aRowIndex) || (aRowIndex >= mRowCount)) {
    return PR_FALSE;
  }
  if (aRowIndex != mRowCount - 1) {
    // aRowIndex is not the last row, so we check the next row after aRowIndex for spanners
    for (PRInt32 colIndex = 0; colIndex < numColsInTable; colIndex++) {
      CellData* cd = GetDataAt(aMap, aRowIndex, colIndex, PR_TRUE);
      if (cd && (cd->IsOrig())) { // cell originates 
        CellData* cd2 = GetDataAt(aMap, aRowIndex + 1, colIndex, PR_TRUE);
        if (cd2 && cd2->IsRowSpan()) { // cd2 is spanned by a row
          if (cd->GetCellFrame() == GetCellFrame(aRowIndex + 1, colIndex, *cd2, PR_TRUE)) {
            return PR_TRUE;
          }
        }
      }
    }
  }
  return PR_FALSE;
}

PRBool nsCellMap::ColHasSpanningCells(nsTableCellMap& aMap,
                                      PRInt32         aColIndex)
{
  PRInt32 numColsInTable = aMap.GetColCount();
  NS_PRECONDITION (aColIndex < numColsInTable, "bad col index arg");
  if ((0 > aColIndex) || (aColIndex >= numColsInTable - 1)) 
    return PR_FALSE;
 
  for (PRInt32 rowIndex = 0; rowIndex < mRowCount; rowIndex++) {
    CellData* cd = GetDataAt(aMap, rowIndex, aColIndex, PR_TRUE);
    if (cd && (cd->IsOrig())) { // cell originates 
      CellData* cd2 = GetDataAt(aMap, rowIndex, aColIndex +1, PR_TRUE);
      if (cd2 && cd2->IsColSpan()) { // cd2 is spanned by a col
        if (cd->GetCellFrame() == GetCellFrame(rowIndex , aColIndex + 1, *cd2, PR_FALSE)) {
          return PR_TRUE;
        }
      }
    }
  }
  return PR_FALSE;
}