Source

pflotran-dev / src / pflotran / patch.F90

Full commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
module Patch_module

  use Option_module
  use Grid_module
  use Coupler_module
  use Observation_module
  use Strata_module
  use Region_module
  use Reaction_Aux_module
  use Dataset_Aux_module
  use Material_module
  use Field_module
  use Saturation_Function_module
#ifdef SURFACE_FLOW
  use Surface_field_module
  use Surface_Material_module
  use Surface_Auxiliary_module
#endif
  
  use Auxiliary_module

  implicit none

  private

#include "definitions.h"

  type, public :: patch_type 
    
    PetscInt :: id
    
    ! These arrays will be used by all modes, mode-specific arrays should
    ! go in the auxiliary data stucture for that mode
    PetscInt, pointer :: imat(:)
    PetscInt, pointer :: sat_func_id(:)

    PetscReal, pointer :: internal_velocities(:,:)
    PetscReal, pointer :: boundary_velocities(:,:)
    PetscReal, pointer :: internal_fluxes(:,:,:)    
    PetscReal, pointer :: boundary_fluxes(:,:,:)  
    PetscReal, pointer :: internal_tran_coefs(:,:)
    PetscReal, pointer :: boundary_tran_coefs(:,:)
    PetscReal, pointer :: ss_fluid_fluxes(:,:)

    type(grid_type), pointer :: grid

    type(region_list_type), pointer :: regions

    type(coupler_list_type), pointer :: boundary_conditions
    type(coupler_list_type), pointer :: initial_conditions
    type(coupler_list_type), pointer :: source_sinks

    type(material_property_type), pointer :: material_properties
    type(material_property_ptr_type), pointer :: material_property_array(:)
    type(saturation_function_type), pointer :: saturation_functions
    type(saturation_function_ptr_type), pointer :: saturation_function_array(:)

    type(strata_list_type), pointer :: strata
    type(observation_list_type), pointer :: observation

    ! Pointers to objects in mother realization object
    type(field_type), pointer :: field 
    type(reaction_type), pointer :: reaction
    type(dataset_type), pointer :: datasets
    
    type(auxiliary_type) :: aux
    
    type(patch_type), pointer :: next

    PetscInt :: surf_or_subsurf_flag  ! Flag to identify if the current patch
                                      ! is a surface or subsurface (default)
#ifdef SURFACE_FLOW
    type(surface_material_property_type), pointer     :: surf_material_properties
    type(surface_material_property_ptr_type), pointer :: surf_material_property_array(:)
    type(surface_field_type),pointer                  :: surf_field
    type(surface_auxiliary_type) :: surf_aux
    
    PetscReal,pointer :: surf_internal_fluxes(:,:)
    PetscReal,pointer :: surf_boundary_fluxes(:,:)
#endif

  end type patch_type

  ! pointer data structure required for making an array of patch pointers in F90
  type, public :: patch_ptr_type
    type(patch_type), pointer :: ptr           ! pointer to the patch_type
  end type patch_ptr_type 

  type, public :: patch_list_type
    PetscInt :: num_patch_objects
    type(patch_type), pointer :: first
    type(patch_type), pointer :: last
    type(patch_ptr_type), pointer :: array(:)
  end type patch_list_type

  PetscInt, parameter, public :: INT_VAR = 0
  PetscInt, parameter, public :: REAL_VAR = 1
    
  interface PatchGetDataset
    module procedure PatchGetDataset1
#ifdef SURFACE_FLOW
    module procedure PatchGetDataset2
#endif
  end interface

  public :: PatchCreate, PatchDestroy, PatchCreateList, PatchDestroyList, &
            PatchAddToList, PatchConvertListToArray, PatchProcessCouplers, &
            PatchUpdateAllCouplerAuxVars, PatchInitAllCouplerAuxVars, &
            PatchLocalizeRegions, PatchUpdateUniformVelocity, &
            PatchGetDataset, PatchGetDatasetValueAtCell, &
            PatchSetDataset, &
            PatchInitConstraints, &
            PatchCountCells, PatchGetIvarsFromKeyword, &
            PatchGetVarNameFromKeyword, &
            PatchCalculateCFL1Timestep

contains

! ************************************************************************** !
!
! PatchCreate: Allocates and initializes a new Patch object
! author: Glenn Hammond
! date: 02/22/08
!
! ************************************************************************** !
function PatchCreate()

  implicit none
  
  type(patch_type), pointer :: PatchCreate
  
  type(patch_type), pointer :: patch
  
  allocate(patch)

  patch%id = 0
  patch%surf_or_subsurf_flag = SUBSURFACE
  nullify(patch%imat)
  nullify(patch%sat_func_id)
  nullify(patch%internal_velocities)
  nullify(patch%boundary_velocities)
  nullify(patch%internal_fluxes)
  nullify(patch%boundary_fluxes)
  nullify(patch%internal_tran_coefs)
  nullify(patch%boundary_tran_coefs)
  nullify(patch%ss_fluid_fluxes)

  nullify(patch%grid)

  allocate(patch%regions)
  call RegionInitList(patch%regions)
  
  allocate(patch%boundary_conditions)
  call CouplerInitList(patch%boundary_conditions)
  allocate(patch%initial_conditions)
  call CouplerInitList(patch%initial_conditions)
  allocate(patch%source_sinks)
  call CouplerInitList(patch%source_sinks)

  nullify(patch%material_properties)
  nullify(patch%material_property_array)
  nullify(patch%saturation_functions)
  nullify(patch%saturation_function_array)

  allocate(patch%observation)
  call ObservationInitList(patch%observation)

  allocate(patch%strata)
  call StrataInitList(patch%strata)
  
  call AuxInit(patch%aux)
  
  nullify(patch%field)
  nullify(patch%reaction)
  nullify(patch%datasets)
  
  nullify(patch%next)
  
#ifdef SURFACE_FLOW
    nullify(patch%surf_material_properties)
    nullify(patch%surf_material_property_array)
    nullify(patch%surf_field)
    nullify(patch%surf_internal_fluxes)
    nullify(patch%surf_boundary_fluxes)
    call SurfaceAuxInit(patch%surf_aux)
#endif

  PatchCreate => patch
  
end function PatchCreate

! ************************************************************************** !
!
! PatchListCreate: Creates a patch list
! author: Glenn Hammond
! date: 02/22/08
!
! ************************************************************************** !
function PatchCreateList()

  implicit none

  type(patch_list_type), pointer :: PatchCreateList

  type(patch_list_type), pointer :: patch_list
  
  allocate(patch_list)
  nullify(patch_list%first)
  nullify(patch_list%last)
  nullify(patch_list%array)
  patch_list%num_patch_objects = 0

  PatchCreateList => patch_list

end function PatchCreateList

! ************************************************************************** !
!
! PatchAddToList: Adds a new patch to list
! author: Glenn Hammond
! date: 02/22/08
!
! ************************************************************************** !
subroutine PatchAddToList(new_patch,patch_list)

  implicit none
  
  type(patch_type), pointer :: new_patch
  type(patch_list_type) :: patch_list
  
  if(associated(new_patch)) then
     patch_list%num_patch_objects = patch_list%num_patch_objects + 1
     new_patch%id = patch_list%num_patch_objects
     if (.not.associated(patch_list%first)) patch_list%first => new_patch
     if (associated(patch_list%last)) patch_list%last%next => new_patch
     patch_list%last => new_patch
  end if
end subroutine PatchAddToList

! ************************************************************************** !
!
! PatchConvertListToArray: Creates an array of pointers to the 
!                               patchs in the patch list
! author: Glenn Hammond
! date: 02/22/08
!
! ************************************************************************** !
subroutine PatchConvertListToArray(patch_list)

  implicit none
  
  type(patch_list_type) :: patch_list
    
  PetscInt :: count
  type(patch_type), pointer :: cur_patch
  
  
  allocate(patch_list%array(patch_list%num_patch_objects))
  
  cur_patch => patch_list%first
  do 
    if (.not.associated(cur_patch)) exit
    patch_list%array(cur_patch%id)%ptr => cur_patch
    cur_patch => cur_patch%next
  enddo

end subroutine PatchConvertListToArray

! ************************************************************************** !
!
! PatchLocalizeRegions: Localizes regions within each patch
! author: Glenn Hammond
! date: 02/22/08
!
! ************************************************************************** !
subroutine PatchLocalizeRegions(patch,regions,option)

  use Option_module
  use Region_module

  implicit none
  
  type(patch_type) :: patch
  type(region_list_type) :: regions
  type(option_type) :: option
  
  type(region_type), pointer :: cur_region
  type(region_type), pointer :: patch_region
  
  cur_region => regions%first
  do
    if (.not.associated(cur_region)) exit
    patch_region => RegionCreate(cur_region)
    call RegionAddToList(patch_region,patch%regions)
    cur_region => cur_region%next
  enddo
  
  !geh: All grids must be localized through GridLocalizeRegions.  Patch
  !     should not differentiate between structured/unstructured, etc.
  call GridLocalizeRegions(patch%grid,patch%regions,option)
 
end subroutine PatchLocalizeRegions

! ************************************************************************** !
!
! PatchProcessCouplers: Assigns conditions and regions to couplers
! author: Glenn Hammond
! date: 02/22/08
!
! ************************************************************************** !
subroutine PatchProcessCouplers(patch,flow_conditions,transport_conditions, &
                                option)

  use Option_module
  use Material_module
  use Condition_module
  use Constraint_module
  use Connection_module

  implicit none
  
  type(patch_type) :: patch
  type(condition_list_type) :: flow_conditions
  type(tran_condition_list_type) :: transport_conditions
  type(option_type) :: option
  
  type(coupler_type), pointer :: coupler
  type(coupler_list_type), pointer :: coupler_list 
  type(strata_type), pointer :: strata
  type(observation_type), pointer :: observation, next_observation
  
  PetscInt :: temp_int, isub
  
  ! boundary conditions
  coupler => patch%boundary_conditions%first
  do
    if (.not.associated(coupler)) exit
    ! pointer to region
    coupler%region => RegionGetPtrFromList(coupler%region_name, &
                                           patch%regions)
    if (.not.associated(coupler%region)) then
      option%io_buffer = 'Region ' // trim(coupler%region_name) // &
                 '" in boundary condition ' // &
                 trim(coupler%name) // &
                 ' not found in region list'
      call printErrMsg(option)
    endif
    if (associated(patch%grid%structured_grid)) then
      if (coupler%region%num_cells > 0 .and. &
          (coupler%region%iface == 0 .and. &
           .not.associated(coupler%region%faces))) then
        option%io_buffer = 'Region ' // trim(coupler%region_name) // &
                 ', which is tied to a boundary condition, has not ' // &
                 'been assigned a face in the structured grid. '
        call printErrMsg(option)
      endif
    endif
    ! pointer to flow condition
    if (option%nflowdof > 0) then
      if (len_trim(coupler%flow_condition_name) > 0) then
        coupler%flow_condition => &
          FlowConditionGetPtrFromList(coupler%flow_condition_name,flow_conditions)
        if (.not.associated(coupler%flow_condition)) then
          option%io_buffer = 'Flow condition "' // &
                   trim(coupler%flow_condition_name) // &
                   '" in boundary condition ' // &
                   trim(coupler%name) // &
                   ' not found in flow condition list'
          call printErrMsg(option)
        endif
      else
        option%io_buffer = 'A FLOW_CONDITION must be specified in ' // &
                           'BOUNDARY_CONDITION: ' // trim(coupler%name) // '.'
        call printErrMsg(option)
      endif
    endif
    ! pointer to transport condition
    if (option%ntrandof > 0) then
      if (len_trim(coupler%tran_condition_name) > 0) then
        coupler%tran_condition => &
          TranConditionGetPtrFromList(coupler%tran_condition_name,transport_conditions)
        if (.not.associated(coupler%tran_condition)) then
           option%io_buffer = 'Transport condition "' // &
                   trim(coupler%tran_condition_name) // &
                   '" in boundary condition ' // &
                   trim(coupler%name) // &
                   ' not found in transport condition list'
          call printErrMsg(option)
        endif
      else
        option%io_buffer = 'A TRANSPORT_CONDITION must be specified in ' // &
                           'BOUNDARY_CONDITION: ' // trim(coupler%name) // '.'
        call printErrMsg(option)
      endif
    endif
    coupler => coupler%next
  enddo


  ! initial conditions
  coupler => patch%initial_conditions%first
  do
    if (.not.associated(coupler)) exit
    ! pointer to region
    coupler%region => RegionGetPtrFromList(coupler%region_name, &
                                           patch%regions)
    if (.not.associated(coupler%region)) then
      option%io_buffer = 'Region ' // trim(coupler%region_name) // &
                 '" in initial condition ' // &
                 trim(coupler%name) // &
                 ' not found in region list'
      call printErrMsg(option)
    endif
    ! pointer to flow condition
    if (option%nflowdof > 0) then
      if (len_trim(coupler%flow_condition_name) > 0) then
        coupler%flow_condition => &
          FlowConditionGetPtrFromList(coupler%flow_condition_name,flow_conditions)
        if (.not.associated(coupler%flow_condition)) then
          option%io_buffer = 'Flow condition "' // &
                   trim(coupler%flow_condition_name) // &
                   '" in initial condition ' // &
                   trim(coupler%name) // &
                   ' not found in flow condition list'
          call printErrMsg(option)
        endif
      else
        option%io_buffer = 'A FLOW_CONDITION must be specified in ' // &
                           'INITIAL_CONDITION: ' // trim(coupler%name) // '.'
        call printErrMsg(option)
      endif
    endif
    ! pointer to transport condition
    if (option%ntrandof > 0) then
      if (len_trim(coupler%tran_condition_name) > 0) then
        coupler%tran_condition => &
          TranConditionGetPtrFromList(coupler%tran_condition_name,transport_conditions)
        if (.not.associated(coupler%tran_condition)) then
          option%io_buffer = 'Transport condition "' // &
                   trim(coupler%tran_condition_name) // &
                   '" in initial condition ' // &
                   trim(coupler%name) // &
                   ' not found in transport condition list'
          call printErrMsg(option)
        endif
      else
        option%io_buffer = 'A TRANSPORT_CONDITION must be specified in ' // &
                           'INITIAL_CONDITION: ' // trim(coupler%name) // '.'
        call printErrMsg(option)
      endif
    endif
    coupler => coupler%next
  enddo

  ! source/sinks
  coupler => patch%source_sinks%first
  do
    if (.not.associated(coupler)) exit
    ! pointer to region
    coupler%region => RegionGetPtrFromList(coupler%region_name, &
                                           patch%regions)
    if (.not.associated(coupler%region)) then
      option%io_buffer = 'Region ' // trim(coupler%region_name) // &
                 '" in source/sink ' // &
                 trim(coupler%name) // &
                 ' not found in region list'
      call printErrMsg(option)
    endif
    ! pointer to flow condition
    if (option%nflowdof > 0) then    
      if (len_trim(coupler%flow_condition_name) > 0) then
        coupler%flow_condition => &
          FlowConditionGetPtrFromList(coupler%flow_condition_name,flow_conditions)
        if (.not.associated(coupler%flow_condition)) then
          option%io_buffer = 'Flow condition "' // &
                   trim(coupler%flow_condition_name) // &
                   '" in source/sink ' // &
                   trim(coupler%name) // &
                   ' not found in flow condition list'
          call printErrMsg(option)
        endif
      else
        option%io_buffer = 'A FLOW_CONDITION must be specified in ' // &
                           'SOURCE_SINK: ' // trim(coupler%name) // '.'
        call printErrMsg(option)
      endif
    endif
    ! pointer to transport condition
    if (option%ntrandof > 0) then    
      if (len_trim(coupler%tran_condition_name) > 0) then
        coupler%tran_condition => &
          TranConditionGetPtrFromList(coupler%tran_condition_name, &
                                      transport_conditions)
        if (.not.associated(coupler%tran_condition)) then
          option%io_buffer = 'Transport condition "' // &
                   trim(coupler%flow_condition_name) // &
                   '" in source/sink ' // &
                   trim(coupler%name) // &
                   ' not found in transport condition list'
          call printErrMsg(option)
        endif
      else
        option%io_buffer = 'A TRANSPORT_CONDITION must be specified in ' // &
                           'SOURCE_SINK: ' // trim(coupler%name) // '.'
        call printErrMsg(option)
      endif
    endif
    coupler => coupler%next
  enddo

!----------------------------  
! AUX  
    
  ! strata
  ! connect pointers from strata to regions
  strata => patch%strata%first
  do
    if (.not.associated(strata)) exit
    ! pointer to region
    if (len_trim(strata%region_name) > 1) then
      strata%region => RegionGetPtrFromList(strata%region_name, &
                                                  patch%regions)
      if (.not.associated(strata%region)) then
        option%io_buffer = 'Region ' // trim(strata%region_name) // &
                 '" in strata not found in region list'
        call printErrMsg(option)
      endif
      if (strata%active) then
        ! pointer to material
        ! gb: Depending on a surface/subsurface patch, use corresponding
        !     material properties
        if (patch%surf_or_subsurf_flag == SUBSURFACE) then
          strata%material_property => &
            MaterialPropGetPtrFromArray(strata%material_property_name, &
                                        patch%material_property_array)
          if (.not.associated(strata%material_property)) then
            option%io_buffer = 'Material ' // &
                              trim(strata%material_property_name) // &
                              ' not found in material list'
            call printErrMsg(option)
          endif
        endif

#ifdef SURFACE_FLOW
        if(patch%surf_or_subsurf_flag == SURFACE) then
          strata%surf_material_property => &
            SurfaceMaterialPropGetPtrFromArray(strata%material_property_name, &
                                            patch%surf_material_property_array)
          if (.not.associated(strata%surf_material_property)) then
            option%io_buffer = 'Material ' // &
                              trim(strata%material_property_name) // &
                              ' not found in material list'
            call printErrMsg(option)
          endif
        endif
#endif

      endif
    else
      nullify(strata%region)
      nullify(strata%material_property)
    endif
    strata => strata%next
  enddo

  ! connectivity between initial conditions, boundary conditions, srcs/sinks, etc and grid
  call CouplerListComputeConnections(patch%grid,option, &
                                     patch%initial_conditions)
  call CouplerListComputeConnections(patch%grid,option, &
                                     patch%boundary_conditions)
  call CouplerListComputeConnections(patch%grid,option, &
                                     patch%source_sinks)

  ! linkage of observation to regions and couplers must take place after
  ! connection list have been created.
  ! observation
  observation => patch%observation%first
  do
    if (.not.associated(observation)) exit
    next_observation => observation%next
    select case(observation%itype)
      case(OBSERVATION_SCALAR)
        ! pointer to region
        observation%region => RegionGetPtrFromList(observation%linkage_name, &
                                                    patch%regions)
        if (.not.associated(observation%region)) then
          option%io_buffer = 'Region "' // &
                   trim(observation%linkage_name) // &
                 '" in observation point ' // &
                 trim(observation%name) // &
                 ' not found in region list'                   
          call printErrMsg(option)
        endif
        if (observation%region%num_cells == 0) then
          ! remove the observation object
          call ObservationRemoveFromList(observation,patch%observation)
        endif
      case(OBSERVATION_FLUX)
        coupler => CouplerGetPtrFromList(observation%linkage_name, &
                                         patch%boundary_conditions)
        if (associated(coupler)) then
          observation%connection_set => coupler%connection_set
        else
          option%io_buffer = 'Boundary Condition ' // &
                   trim(observation%linkage_name) // &
                   ' not found in Boundary Condition list'
          call printErrMsg(option)
        endif
        if (observation%connection_set%num_connections == 0) then
          ! cannot remove from list, since there must be a global reduction
          ! across all procs
          ! therefore, just nullify connection set
          nullify(observation%connection_set)
        endif                                      
    end select
    observation => next_observation
  enddo
 
  temp_int = ConnectionGetNumberInList(patch%grid%internal_connection_set_list)
  allocate(patch%internal_velocities(option%nphase,temp_int))
  patch%internal_velocities = 0.d0
  allocate(patch%internal_tran_coefs(option%nphase,temp_int))
  patch%internal_tran_coefs = 0.d0
  if (option%store_solute_fluxes) then
    allocate(patch%internal_fluxes(option%nphase,option%ntrandof,temp_int))
    patch%internal_fluxes = 0.d0
  endif
  if (option%store_flowrate) then
    if(option%store_solute_fluxes) then
      option%io_buffer='Model does not support store_solute_fluxes and flowrate ' // &
      ' options together. If you run into this message, complain on pflotran-dev@googlegroups.com'
      call printErrMsg(option)
    endif
    allocate(patch%internal_fluxes(option%nflowdof,1,temp_int))
    allocate(patch%boundary_fluxes(option%nflowdof,1,temp_int))
    patch%internal_fluxes = 0.d0
    patch%boundary_fluxes = 0.d0
  endif
#ifdef SURFACE_FLOW
  if (patch%surf_or_subsurf_flag == SURFACE) then
    if (option%store_flowrate) then
      allocate(patch%surf_internal_fluxes(option%nflowdof,temp_int))
      allocate(patch%surf_boundary_fluxes(option%nflowdof,temp_int))
      patch%surf_internal_fluxes = 0.d0
      patch%surf_boundary_fluxes = 0.d0
    endif
  endif
#endif
 
  if (patch%grid%itype == STRUCTURED_GRID_MIMETIC.or. &
      patch%grid%discretization_itype == UNSTRUCTURED_GRID_MIMETIC ) then
    temp_int = CouplerGetNumBoundConnectionsInListMFD(patch%grid, &
                                                 patch%boundary_conditions, &
                                                 option)
  else  
    temp_int = CouplerGetNumConnectionsInList(patch%boundary_conditions)
  end if

  if (temp_int > 0) then
    allocate(patch%boundary_velocities(option%nphase,temp_int)) 
    patch%boundary_velocities = 0.d0
    allocate(patch%boundary_tran_coefs(option%nphase,temp_int))
    patch%boundary_tran_coefs = 0.d0
    if (option%store_solute_fluxes) then
      allocate(patch%boundary_fluxes(option%nphase,option%ntrandof,temp_int))
      patch%boundary_fluxes = 0.d0
    endif
  endif

  temp_int = CouplerGetNumConnectionsInList(patch%source_sinks)
  if (temp_int > 0) then
    allocate(patch%ss_fluid_fluxes(option%nphase,temp_int))
    patch%ss_fluid_fluxes = 0.d0
  endif

end subroutine PatchProcessCouplers

! ************************************************************************** !
!
! PatchInitAllCouplerAuxVars: Initializes coupler auxillary variables 
!                                within list
! author: Glenn Hammond
! date: 02/22/08
!
! ************************************************************************** !
subroutine PatchInitAllCouplerAuxVars(patch,option)

  use Option_module
  use Reaction_Aux_module
  
  implicit none
  
  type(patch_type), pointer :: patch
  type(option_type) :: option
  
  PetscBool :: force_update_flag = PETSC_TRUE
  
  call PatchInitCouplerAuxVars(patch%initial_conditions,patch, &
                               option)
  call PatchInitCouplerAuxVars(patch%boundary_conditions,patch, &
                               option)
  call PatchInitCouplerAuxVars(patch%source_sinks,patch, &
                               option)

  !geh: This should not be included in PatchUpdateAllCouplerAuxVars
  ! as it will result in excessive updates to initial conditions
  ! that are not necessary after the simulation has started time stepping.
  call PatchUpdateCouplerAuxVars(patch,patch%initial_conditions, &
                                 force_update_flag,option)
  call PatchUpdateAllCouplerAuxVars(patch,force_update_flag,option)

end subroutine PatchInitAllCouplerAuxVars

! ************************************************************************** !
!
! PatchInitCouplerAuxVars: Initializes coupler auxillary variables 
!                                within list
! author: Glenn Hammond
! date: 02/22/08
!
! ************************************************************************** !
subroutine PatchInitCouplerAuxVars(coupler_list,patch,option)

  use Option_module
  use Connection_module
  use Reaction_Aux_module
  use Reactive_Transport_Aux_module
  use Global_Aux_module
  use Condition_module
  use Constraint_module
  use Dataset_Aux_module
  
  implicit none
  
  type(coupler_list_type), pointer :: coupler_list
  type(patch_type), pointer :: patch
  type(option_type) :: option
  
  PetscInt :: num_connections
  PetscBool :: force_update_flag
  
  type(coupler_type), pointer :: coupler
  type(tran_constraint_coupler_type), pointer :: cur_constraint_coupler
  type(dataset_type), pointer :: dataset
  PetscInt :: idof
  character(len=MAXSTRINGLENGTH) :: string
  
  if (.not.associated(coupler_list)) return
    
  coupler => coupler_list%first
  do
    if (.not.associated(coupler)) exit
    
    if (associated(coupler%connection_set)) then
      num_connections = coupler%connection_set%num_connections
      
      ! FLOW
      if (associated(coupler%flow_condition) .and. &
          (coupler%itype == INITIAL_COUPLER_TYPE .or. &
           coupler%itype == BOUNDARY_COUPLER_TYPE)) then

        if (associated(coupler%flow_condition%pressure) .or. &
            associated(coupler%flow_condition%concentration) .or. &
            associated(coupler%flow_condition%saturation) .or. &
            associated(coupler%flow_condition%rate) .or. &
            associated(coupler%flow_condition%temperature) .or. &
            associated(coupler%flow_condition%general)) then

          ! allocate arrays that match the number of connections
          select case(option%iflowmode)

            case(RICHARDS_MODE)
!geh              allocate(coupler%flow_aux_real_var(option%nflowdof*option%nphase,num_connections))
              if (option%mimetic) then
                 if (coupler%itype == INITIAL_COUPLER_TYPE) then 
                     num_connections = coupler%numfaces_set + coupler%region%num_cells
                 else 
                     num_connections = coupler%numfaces_set
                 end if
              end if
              allocate(coupler%flow_aux_real_var(2,num_connections))
              allocate(coupler%flow_aux_int_var(1,num_connections))
              coupler%flow_aux_real_var = 0.d0
              coupler%flow_aux_int_var = 0

            case(TH_MODE)
              allocate(coupler%flow_aux_real_var(option%nflowdof*option%nphase,num_connections))
              allocate(coupler%flow_aux_int_var(1,num_connections))
              coupler%flow_aux_real_var = 0.d0
              coupler%flow_aux_int_var = 0

            case(THC_MODE)
              allocate(coupler%flow_aux_real_var(option%nflowdof*option%nphase,num_connections))
              allocate(coupler%flow_aux_int_var(1,num_connections))
              coupler%flow_aux_real_var = 0.d0
              coupler%flow_aux_int_var = 0
              
            case(THMC_MODE)
              allocate(coupler%flow_aux_real_var(option%nflowdof*option%nphase,num_connections))
              allocate(coupler%flow_aux_int_var(1,num_connections))
              coupler%flow_aux_real_var = 0.d0
              coupler%flow_aux_int_var = 0

            case(MPH_MODE, IMS_MODE, FLASH2_MODE, MIS_MODE)
!geh              allocate(coupler%flow_aux_real_var(option%nflowdof*option%nphase,num_connections))
              allocate(coupler%flow_aux_real_var(option%nflowdof,num_connections))
              allocate(coupler%flow_aux_int_var(1,num_connections))
              coupler%flow_aux_real_var = 0.d0
              coupler%flow_aux_int_var = 0
                
            case(G_MODE)
              allocate(coupler%flow_aux_real_var(FOUR_INTEGER,num_connections))
              allocate(coupler%flow_aux_int_var(ONE_INTEGER,num_connections))
              coupler%flow_aux_real_var = 0.d0
              coupler%flow_aux_int_var = 0
                
            case default
          end select
      
        endif ! associated(coupler%flow_condition%pressure)
      
      else if (coupler%itype == SRC_SINK_COUPLER_TYPE) then

        if (associated(coupler%flow_condition%rate)) then

          select case(coupler%flow_condition%rate%itype)
            case(SCALED_MASS_RATE_SS,SCALED_VOLUMETRIC_RATE_SS, &
                 HET_VOL_RATE_SS,HET_MASS_RATE_SS)
              select case(option%iflowmode)
                case(RICHARDS_MODE)
                  allocate(coupler%flow_aux_real_var(1,num_connections))
                  coupler%flow_aux_real_var = 0.d0
                case(TH_MODE)
                  allocate(coupler%flow_aux_real_var(option%nflowdof*option%nphase,num_connections))
                  coupler%flow_aux_real_var = 0.d0
                case default
                  write(string,*),coupler%flow_condition%rate%itype
                  option%io_buffer='Source/Sink of rate%itype = ' // &
                    trim(adjustl(string)) // ', not implemented in this mode.'
                  call printErrMsg(option)
              end select
          end select
        endif ! associated(coupler%flow_condition%rate)
      endif ! coupler%itype == SRC_SINK_COUPLER_TYPE
    endif ! associated(coupler%connection_set)

    ! TRANSPORT   
    if (associated(coupler%tran_condition)) then
      cur_constraint_coupler => &
        coupler%tran_condition%constraint_coupler_list
      do
        if (.not.associated(cur_constraint_coupler)) exit
        ! Setting option%iflag = 0 ensures that the "mass_balance" array
        ! is not allocated.
        option%iflag = 0
        ! Only allocate the XXX_auxvar objects if they have not been allocated.
        ! Since coupler%tran_condition is a pointer to a separate list of
        ! tran conditions, the XXX_auxvar object may already be allocated.
        if (.not.associated(cur_constraint_coupler%global_auxvar)) then
          allocate(cur_constraint_coupler%global_auxvar)
          call GlobalAuxVarInit(cur_constraint_coupler%global_auxvar,option)
        endif
        if (.not.associated(cur_constraint_coupler%rt_auxvar)) then
          allocate(cur_constraint_coupler%rt_auxvar)
          call RTAuxVarInit(cur_constraint_coupler%rt_auxvar,patch%reaction, &
                            option)
        endif
        cur_constraint_coupler => cur_constraint_coupler%next
      enddo
    endif
      
    coupler => coupler%next
  enddo
  
end subroutine PatchInitCouplerAuxVars

! ************************************************************************** !
!
! PatchUpdateAllCouplerAuxVars: Updates auxiliary variables associated 
!                                  with couplers in list
! author: Glenn Hammond
! date: 02/22/08
!
! ************************************************************************** !
subroutine PatchUpdateAllCouplerAuxVars(patch,force_update_flag,option)

  use Option_module
  
  implicit none
  
  type(patch_type) :: patch
  PetscBool :: force_update_flag
  type(option_type) :: option

  PetscInt :: iconn
  
  !geh: no need to update initial conditions as they only need updating
  !     once as performed in PatchInitCouplerAuxVars()
  call PatchUpdateCouplerAuxVars(patch,patch%boundary_conditions, &
                                 force_update_flag,option)
  call PatchUpdateCouplerAuxVars(patch,patch%source_sinks, &
                                 force_update_flag,option)

!  stop
end subroutine PatchUpdateAllCouplerAuxVars

! ************************************************************************** !
!
! PatchUpdateCouplerAuxVars: Updates auxiliary variables associated 
!                                  with couplers in list
! author: Glenn Hammond
! date: 11/26/07
!
! ************************************************************************** !
subroutine PatchUpdateCouplerAuxVars(patch,coupler_list,force_update_flag, &
                                     option)
  use Option_module
  use Condition_module
  use Hydrostatic_module
  use Saturation_module
  use Water_EOS_module
  use Dataset_Aux_module
  
  use General_Aux_module
  use Grid_module

  implicit none
  
  type(patch_type) :: patch
  type(coupler_list_type), pointer :: coupler_list
  PetscBool :: force_update_flag
  type(option_type) :: option
  
  type(coupler_type), pointer :: coupler
  type(flow_condition_type), pointer :: flow_condition
  type(tran_condition_type), pointer :: tran_condition
  type(flow_general_condition_type), pointer :: general
  type(dataset_type), pointer :: dataset
  PetscBool :: update
  PetscBool :: dof1, dof2, dof3
  PetscReal :: temperature, p_sat
  PetscReal :: x(option%nflowdof)
  character(len=MAXSTRINGLENGTH) :: string, string2
  PetscErrorCode :: ierr
  
  PetscInt :: idof, num_connections,sum_connection
  PetscInt :: iconn, local_id, ghosted_id
  

  if (.not.associated(coupler_list)) return
 
  coupler => coupler_list%first
  sum_connection=0
  
  do
    if (.not.associated(coupler)) exit
    
    ! FLOW
    if (associated(coupler%flow_aux_real_var)) then

      num_connections = coupler%connection_set%num_connections
#ifdef DASVYAT      
      if (option%mimetic) then
        num_connections = coupler%numfaces_set
      end if
#endif

      flow_condition => coupler%flow_condition

      if (force_update_flag .or. FlowConditionIsTransient(flow_condition)) then

        select case(option%iflowmode)
          case(G_MODE) ! general phase mode
            general => flow_condition%general
            dof1 = PETSC_FALSE
            dof2 = PETSC_FALSE
            dof3 = PETSC_FALSE
            coupler%flow_aux_int_var(COUPLER_IPHASE_INDEX,1:num_connections) = &
              flow_condition%iphase            
            select case(flow_condition%iphase)
              case(TWO_PHASE_STATE)
                select case(general%gas_pressure%itype)
                  case(DIRICHLET_BC)
                    coupler%flow_aux_real_var(GENERAL_GAS_PRESSURE_DOF,1:num_connections) = &
                      general%gas_pressure%flow_dataset%time_series%cur_value(1)
                    dof1 = PETSC_TRUE
                  case default
                end select
                select case(general%gas_saturation%itype)
                  case(DIRICHLET_BC)
                    coupler%flow_aux_real_var(GENERAL_GAS_SATURATION_DOF,1:num_connections) = &
                      general%gas_saturation%flow_dataset%time_series%cur_value(1)
                    dof2 = PETSC_TRUE
                end select
                select case(general%temperature%itype)
                  case(DIRICHLET_BC)
                    temperature = general%temperature%flow_dataset%time_series%cur_value(1)
                    call psat(temperature,p_sat,ierr)
                    coupler%flow_aux_real_var(GENERAL_AIR_PRESSURE_DOF,1:num_connections) = &
                      general%gas_pressure%flow_dataset%time_series%cur_value(1) - p_sat
                    dof3 = PETSC_TRUE
                end select
              case(LIQUID_STATE)
                if (general%liquid_pressure%itype == HYDROSTATIC_BC) then
                  if (general%mole_fraction%itype /= DIRICHLET_BC) then
                    option%io_buffer = 'Hydrostatic liquid state pressure bc for flow condition "' // &
                      trim(flow_condition%name) // '" requires a mole fraction bc of type dirichlet'
                    call printErrMsg(option)
                  endif
                  if (general%temperature%itype /= DIRICHLET_BC) then
                    option%io_buffer = 'Hydrostatic liquid state pressure bc for flow condition "' // &
                      trim(flow_condition%name) // '" requires a temperature bc of type dirichlet'
                    call printErrMsg(option)
                  endif
                  call HydrostaticUpdateCoupler(coupler,option,patch%grid)
#if 0                  
                  do iconn=1,coupler%connection_set%num_connections
                    local_id = coupler%connection_set%id_dn(iconn)
                    ghosted_id = patch%grid%nL2G(local_id)
                    x(1:option%nflowdof) = &
                      coupler%flow_aux_real_var(1:option%nflowdof,iconn)
                    patch%aux%Global%aux_vars(ghosted_id)%istate = LIQUID_STATE
                    call GeneralAuxVarUpdateState(x, &
                           patch%aux%General%aux_vars(ZERO_INTEGER,ghosted_id), &
                           patch%aux%Global%aux_vars(ghosted_id), &
                           patch%saturation_function_array( &
                             patch%sat_func_id(ghosted_id))%ptr, &
                           0.d0,0.d0,ghosted_id,option)
                    coupler%flow_aux_real_var(1:option%nflowdof,iconn) = &
                      x(1:option%nflowdof)
                    coupler%flow_aux_int_var(ONE_INTEGER,iconn) = &
                      patch%aux%Global%aux_vars(ghosted_id)%istate  
                    patch%aux%Global%aux_vars(ghosted_id)%istate = &
                      patch%aux%Global%aux_vars(ghosted_id)%istate    
                  enddo
#endif                  
                else
                  select case(general%liquid_pressure%itype)
                    case(DIRICHLET_BC)
                      coupler%flow_aux_real_var(GENERAL_LIQUID_PRESSURE_DOF,1:num_connections) = &
                        general%liquid_pressure%flow_dataset%time_series%cur_value(1)
                      dof1 = PETSC_TRUE
                  end select
                  select case(general%mole_fraction%itype)
                    case(DIRICHLET_BC)
                      coupler%flow_aux_real_var(GENERAL_LIQUID_STATE_MOLE_FRACTION_DOF,1:num_connections) = &
                        general%mole_fraction%flow_dataset%time_series%cur_value(1)
                      dof2 = PETSC_TRUE
                  end select
                  select case(general%temperature%itype)
                    case(DIRICHLET_BC)
                      coupler%flow_aux_real_var(GENERAL_LIQUID_STATE_TEMPERATURE_DOF,1:num_connections) = &
                        general%temperature%flow_dataset%time_series%cur_value(1)
                      dof3 = PETSC_TRUE
                  end select
                endif
              case(GAS_STATE)
                select case(general%gas_pressure%itype)
                  case(DIRICHLET_BC)
                    coupler%flow_aux_real_var(GENERAL_GAS_PRESSURE_DOF,1:num_connections) = &
                      general%gas_pressure%flow_dataset%time_series%cur_value(1)
                    dof1 = PETSC_TRUE
                end select
                select case(general%mole_fraction%itype)
                  case(DIRICHLET_BC)
                    coupler%flow_aux_real_var(GENERAL_AIR_PRESSURE_DOF,1:num_connections) = &
                      general%mole_fraction%flow_dataset%time_series%cur_value(1) * &
                      general%gas_pressure%flow_dataset%time_series%cur_value(1)
                    dof2 = PETSC_TRUE
                end select                
                select case(general%temperature%itype)
                  case(DIRICHLET_BC)
                    coupler%flow_aux_real_var(GENERAL_GAS_STATE_TEMPERATURE_DOF,1:num_connections) = &
                      general%temperature%flow_dataset%time_series%cur_value(1)
                    dof3 = PETSC_TRUE
                end select
              case(ANY_STATE)
                do iconn = 1, num_connections
                  coupler%flow_aux_real_var(1:3,iconn) = &
                      general%temperature%flow_dataset%time_series%cur_value(1:3)
                enddo
                dof1 = PETSC_TRUE
                dof2 = PETSC_TRUE
                dof3 = PETSC_TRUE
            end select  
            !geh: is this really correct, or should it be .or.
            if (.not.dof1 .or. .not.dof2 .or. .not.dof3) then
              option%io_buffer = 'Error with general phase boundary condition'
            endif
            
          case(MPH_MODE,IMS_MODE,FLASH2_MODE,THC_MODE) ! updated 10/17/11
            if (associated(flow_condition%pressure)) then
              coupler%flow_aux_int_var(COUPLER_IPHASE_INDEX,1:num_connections) = &
                          flow_condition%iphase
              select case(flow_condition%pressure%itype)
                case(DIRICHLET_BC,NEUMANN_BC,ZERO_GRADIENT_BC)
                  coupler%flow_aux_real_var(MPH_PRESSURE_DOF,1:num_connections) = &
                          flow_condition%pressure%flow_dataset%time_series%cur_value(1)
                case(HYDROSTATIC_BC,SEEPAGE_BC,CONDUCTANCE_BC)
                  call HydrostaticUpdateCoupler(coupler,option,patch%grid)
           !  case(SATURATION_BC)
              end select
              select case(flow_condition%temperature%itype)
                case(DIRICHLET_BC,NEUMANN_BC,ZERO_GRADIENT_BC)
                  if (flow_condition%pressure%itype /= HYDROSTATIC_BC .or. &
                     (flow_condition%pressure%itype == HYDROSTATIC_BC .and. &
                     flow_condition%temperature%itype /= DIRICHLET_BC)) then
                    coupler%flow_aux_real_var(MPH_TEMPERATURE_DOF,1:num_connections) = &
                            flow_condition%temperature%flow_dataset%time_series%cur_value(1)
                  endif
              end select
              select case(flow_condition%concentration%itype)
                case(DIRICHLET_BC,ZERO_GRADIENT_BC)
                  if (flow_condition%pressure%itype /= HYDROSTATIC_BC .or. &
                     (flow_condition%pressure%itype == HYDROSTATIC_BC .and. &
                     flow_condition%concentration%itype /= DIRICHLET_BC)) then
                    coupler%flow_aux_real_var(MPH_CONCENTRATION_DOF,1:num_connections) = &
                            flow_condition%concentration%flow_dataset%time_series%cur_value(1)
                  endif
              end select
            else
              select case(flow_condition%temperature%itype)
                case(DIRICHLET_BC,NEUMANN_BC,ZERO_GRADIENT_BC)
                  coupler%flow_aux_real_var(MPH_TEMPERATURE_DOF,1:num_connections) = &
                            flow_condition%temperature%flow_dataset%time_series%cur_value(1)
              end select
              select case(flow_condition%concentration%itype)
                case(DIRICHLET_BC,ZERO_GRADIENT_BC)
                   coupler%flow_aux_real_var(MPH_CONCENTRATION_DOF,1:num_connections) = &
                            flow_condition%concentration%flow_dataset%time_series%cur_value(1)
              end select
            endif
            if (associated(flow_condition%rate)) then
              select case(flow_condition%rate%itype)
                case(SCALED_MASS_RATE_SS,SCALED_VOLUMETRIC_RATE_SS)
                  call PatchScaleSourceSink(patch,coupler,option)
              end select
            endif
            if (associated(flow_condition%saturation)) then
              call SaturationUpdateCoupler(coupler,option,patch%grid, &
                                           patch%saturation_function_array, &
                                           patch%sat_func_id)
            endif
  
          case(TH_MODE)
            if (associated(flow_condition%pressure)) then
              coupler%flow_aux_int_var(COUPLER_IPHASE_INDEX,1:num_connections) = &
                          flow_condition%iphase
              select case(flow_condition%pressure%itype)
                case(DIRICHLET_BC,NEUMANN_BC,ZERO_GRADIENT_BC)
                  coupler%flow_aux_real_var(TH_PRESSURE_DOF,1:num_connections) = &
                          flow_condition%pressure%flow_dataset%time_series%cur_value(1)
                case(HYDROSTATIC_BC,SEEPAGE_BC,CONDUCTANCE_BC)
                  call HydrostaticUpdateCoupler(coupler,option,patch%grid)
                case default
                  write(string,*),flow_condition%pressure%itype
                  option%io_buffer='For TH mode: flow_condition%pressure%itype = ' // &
                    trim(adjustl(string)) // ', not implemented.'
                  call printErrMsg(option)
              end select
              select case(flow_condition%temperature%itype)
                case(DIRICHLET_BC,NEUMANN_BC,ZERO_GRADIENT_BC)
                  if (flow_condition%pressure%itype /= HYDROSTATIC_BC .or. &
                     (flow_condition%pressure%itype == HYDROSTATIC_BC .and. &
                     flow_condition%temperature%itype /= DIRICHLET_BC)) then
                    coupler%flow_aux_real_var(TH_TEMPERATURE_DOF,1:num_connections) = &
                            flow_condition%temperature%flow_dataset%time_series%cur_value(1)
                  endif
                case (HET_DIRICHLET)
                  call PatchUpdateHetroCouplerAuxVars(patch,coupler, &
                          flow_condition%temperature%flow_dataset, &
                          num_connections,TH_TEMPERATURE_DOF,option)
                case default
                  write(string,*),flow_condition%temperature%itype
                  option%io_buffer='For TH mode: flow_condition%temperature%itype = ' // &
                    trim(adjustl(string)) // ', not implemented.'
                  call printErrMsg(option)
              end select
            else
              select case(flow_condition%temperature%itype)
                case(DIRICHLET_BC,NEUMANN_BC,ZERO_GRADIENT_BC)
                  coupler%flow_aux_real_var(TH_TEMPERATURE_DOF,1:num_connections) = &
                            flow_condition%temperature%flow_dataset%time_series%cur_value(1)
                case (HET_DIRICHLET)
                  call PatchUpdateHetroCouplerAuxVars(patch,coupler, &
                          flow_condition%temperature%flow_dataset, &
                          num_connections,TH_TEMPERATURE_DOF,option)
                case default
                  write(string,*),flow_condition%temperature%itype
                  option%io_buffer='For TH mode: flow_condition%temperature%itype = ' // &
                    trim(adjustl(string)) // ', not implemented.'
                  call printErrMsg(option)
              end select
            endif
            if (associated(flow_condition%rate)) then
              select case(flow_condition%rate%itype)
                case (HET_MASS_RATE_SS,HET_VOL_RATE_SS)
                  call PatchUpdateHetroCouplerAuxVars(patch,coupler, &
                            flow_condition%rate%flow_dataset, &
                            num_connections,TH_PRESSURE_DOF,option)
                case (MASS_RATE_SS)
                    coupler%flow_aux_real_var(TH_PRESSURE_DOF,1:num_connections) = &
                            flow_condition%rate%flow_dataset%time_series%cur_value(1)
                case default
                  write(string,*),flow_condition%rate%itype
                  option%io_buffer='For TH mode: flow_condition%rate%itype = ' // &
                    trim(adjustl(string)) // ', not implemented.'
                  call printErrMsg(option)
              end select
            endif
            if (associated(flow_condition%saturation)) then
              call SaturationUpdateCoupler(coupler,option,patch%grid, &
                                           patch%saturation_function_array, &
                                           patch%sat_func_id)
            endif

          case(MIS_MODE) ! Miscible mode, added by Chuan Lu, 12/23/11
            if (associated(flow_condition%pressure)) then
              select case(flow_condition%pressure%itype)
                case(DIRICHLET_BC,NEUMANN_BC,ZERO_GRADIENT_BC)
                  coupler%flow_aux_real_var(MIS_PRESSURE_DOF, &
                                            1:num_connections) = &
                    flow_condition%pressure%flow_dataset%time_series%cur_value(1)
                case(HYDROSTATIC_BC,SEEPAGE_BC,CONDUCTANCE_BC)
                  call HydrostaticUpdateCoupler(coupler,option,patch%grid)
             !  case(SATURATION_BC)
              end select
            endif
            if (associated(flow_condition%concentration)) then
              select case(flow_condition%concentration%itype)
                case(DIRICHLET_BC,NEUMANN_BC,ZERO_GRADIENT_BC)
                  if (associated(flow_condition%concentration%flow_dataset% &
                                   time_series)) then
                    coupler%flow_aux_real_var(MIS_CONCENTRATION_DOF, &
                                              1:num_connections) = &
                      flow_condition%concentration%flow_dataset%time_series%cur_value(1)
                  endif
                case(HYDROSTATIC_BC,SEEPAGE_BC,CONDUCTANCE_BC)
                  call HydrostaticUpdateCoupler(coupler,option,patch%grid)
             !  case(SATURATION_BC)
              end select
            endif
            if (associated(flow_condition%rate)) then
              select case(flow_condition%rate%itype)
                case(SCALED_MASS_RATE_SS,SCALED_VOLUMETRIC_RATE_SS)
                  call PatchScaleSourceSink(patch,coupler,option)
              end select
            endif

          case(THMC_MODE) ! updated 10/17/11 
            if (associated(flow_condition%pressure)) then
              coupler%flow_aux_int_var(COUPLER_IPHASE_INDEX,1:num_connections) = &
                          flow_condition%iphase
              select case(flow_condition%pressure%itype)
                case(DIRICHLET_BC,NEUMANN_BC,ZERO_GRADIENT_BC)
                  coupler%flow_aux_real_var(MPH_PRESSURE_DOF,1:num_connections) = &
                          flow_condition%pressure%flow_dataset%time_series%cur_value(1)
                case(HYDROSTATIC_BC,SEEPAGE_BC,CONDUCTANCE_BC)
                  call HydrostaticUpdateCoupler(coupler,option,patch%grid)
           !  case(SATURATION_BC)
              end select
              select case(flow_condition%temperature%itype)
                case(DIRICHLET_BC,NEUMANN_BC,ZERO_GRADIENT_BC)
                  if (flow_condition%pressure%itype /= HYDROSTATIC_BC .or. &
                     (flow_condition%pressure%itype == HYDROSTATIC_BC .and. &
                     flow_condition%temperature%itype /= DIRICHLET_BC)) then
                    coupler%flow_aux_real_var(MPH_TEMPERATURE_DOF,1:num_connections) = &
                            flow_condition%temperature%flow_dataset%time_series%cur_value(1)
                  endif
              end select
              select case(flow_condition%concentration%itype)
                case(DIRICHLET_BC,ZERO_GRADIENT_BC)
                  if (flow_condition%pressure%itype /= HYDROSTATIC_BC .or. &
                     (flow_condition%pressure%itype == HYDROSTATIC_BC .and. &
                     flow_condition%concentration%itype /= DIRICHLET_BC)) then
                    coupler%flow_aux_real_var(MPH_CONCENTRATION_DOF,1:num_connections) = &
                            flow_condition%concentration%flow_dataset%time_series%cur_value(1)
                  endif
              end select
            else
              select case(flow_condition%temperature%itype)
                case(DIRICHLET_BC,NEUMANN_BC,ZERO_GRADIENT_BC)
                  coupler%flow_aux_real_var(MPH_TEMPERATURE_DOF,1:num_connections) = &
                            flow_condition%temperature%flow_dataset%time_series%cur_value(1)
              end select
              select case(flow_condition%concentration%itype)
                case(DIRICHLET_BC,ZERO_GRADIENT_BC)
                   coupler%flow_aux_real_var(MPH_CONCENTRATION_DOF,1:num_connections) = &
                            flow_condition%concentration%flow_dataset%time_series%cur_value(1)
              end select
            endif
            if (associated(flow_condition%displacement_x)) then
              select case(flow_condition%displacement_x%itype) 
                case(DIRICHLET_BC)
                  coupler%flow_aux_real_var(THMC_DISP_X_DOF,1:num_connections) = &
                           flow_condition%displacement_x%flow_dataset%time_series%cur_value(1)
                case default
                  option%io_buffer = 'bc for "' // &
                  trim(flow_condition%name) // '" requires type dirichlet'
                  call printErrMsg(option)
              end select
            endif
            if (associated(flow_condition%displacement_y)) then
              select case(flow_condition%displacement_y%itype) 
                case(DIRICHLET_BC)
                  coupler%flow_aux_real_var(THMC_DISP_Y_DOF,1:num_connections) = &
                           flow_condition%displacement_y%flow_dataset%time_series%cur_value(1)
                case default
                  option%io_buffer = 'bc for "' // &
                  trim(flow_condition%name) // '" requires type dirichlet'
                  call printErrMsg(option)
              end select
            endif          
            if (associated(flow_condition%displacement_z)) then
              select case(flow_condition%displacement_z%itype) 
                case(DIRICHLET_BC)
                  coupler%flow_aux_real_var(THMC_DISP_Z_DOF,1:num_connections) = &
                           flow_condition%displacement_z%flow_dataset%time_series%cur_value(1)
                case default
                  option%io_buffer = 'bc for "' // &
                  trim(flow_condition%name) // '" requires type dirichlet'
                  call printErrMsg(option)
              end select
            endif
            if (associated(flow_condition%rate)) then
              select case(flow_condition%rate%itype)
                case(SCALED_MASS_RATE_SS,SCALED_VOLUMETRIC_RATE_SS)
                  call PatchScaleSourceSink(patch,coupler,option)
              end select
            endif
            if (associated(flow_condition%saturation)) then
              call SaturationUpdateCoupler(coupler,option,patch%grid, &
                                           patch%saturation_function_array, &
                                           patch%sat_func_id)
            endif
  
          case(RICHARDS_MODE) ! Richards mode, added by Satish Karra, 10/11/11
            if (associated(flow_condition%pressure)) then
              select case(flow_condition%pressure%itype)
                case(DIRICHLET_BC,NEUMANN_BC,ZERO_GRADIENT_BC)
                  coupler%flow_aux_real_var(RICHARDS_PRESSURE_DOF, &
                                            1:num_connections) = &
                    flow_condition%pressure%flow_dataset%time_series%cur_value(1)
                case(HYDROSTATIC_BC,SEEPAGE_BC,CONDUCTANCE_BC)
                  call HydrostaticUpdateCoupler(coupler,option,patch%grid)
             !  case(SATURATION_BC)
              end select
            endif
            if (associated(flow_condition%saturation)) then
              call SaturationUpdateCoupler(coupler,option,patch%grid, &
                                           patch%saturation_function_array, &
                                           patch%sat_func_id)
            endif
            if (associated(flow_condition%rate)) then
              select case(flow_condition%rate%itype)
                case(SCALED_MASS_RATE_SS,SCALED_VOLUMETRIC_RATE_SS)
                  call PatchScaleSourceSink(patch,coupler,option)
                case (HET_VOL_RATE_SS,HET_MASS_RATE_SS)
                  call PatchUpdateHetroCouplerAuxVars(patch,coupler, &
                          flow_condition%rate%flow_dataset, &
                          num_connections,RICHARDS_PRESSURE_DOF,option)
              end select
            endif
          
          case default
      
        end select
      sum_connection=sum_connection+num_connections
      endif
    endif
      
    ! TRANSPORT
    ! nothing for transport at this point in time

    coupler => coupler%next
  enddo

end subroutine PatchUpdateCouplerAuxVars

! ************************************************************************** !
!
! PatchScaleSourceSink: Scales select source/sinks based on perms*volume
! author: Glenn Hammond
! date: 01/12/11
!
! ************************************************************************** !
subroutine PatchScaleSourceSink(patch,source_sink,option)

  use Option_module
  use Field_module
  use Coupler_module
  use Connection_module
  use Condition_module
  use Grid_module
  
  implicit none

#include "finclude/petscvec.h"
#include "finclude/petscvec.h90"
#include "finclude/petscdmda.h"
  
  type(patch_type) :: patch
  type(coupler_type) :: source_sink
  type(option_type) :: option
  
  PetscErrorCode :: ierr
  
  type(grid_type), pointer :: grid
  type(connection_set_type), pointer :: cur_connection_set
  type(field_type), pointer :: field
  
  PetscReal, pointer :: vec_ptr(:)
  PetscReal, pointer :: perm_loc_ptr(:)
  PetscReal, pointer :: vol_ptr(:)
  PetscInt :: local_id
  PetscInt :: ghosted_id, neighbor_ghosted_id
  PetscInt :: iconn
  PetscInt :: iscale_type
  PetscReal :: scale, sum
  PetscInt :: icount, x_count, y_count, z_count
  PetscInt, parameter :: x_width = 1, y_width = 1, z_width = 0
  PetscInt :: ghosted_neighbors(27)
    
  field => patch%field
  grid => patch%grid

  call GridVecGetArrayF90(grid,field%perm_xx_loc,perm_loc_ptr,ierr)
  call GridVecGetArrayF90(grid,field%volume,vol_ptr,ierr)

  grid => patch%grid

  call VecZeroEntries(field%work,ierr)
  call GridVecGetArrayF90(grid,field%work,vec_ptr,ierr)

  cur_connection_set => source_sink%connection_set

  iscale_type = source_sink%flow_condition%rate%isubtype
  
  select case(iscale_type)
    case(SCALE_BY_VOLUME)
      do iconn = 1, cur_connection_set%num_connections
        local_id = cur_connection_set%id_dn(iconn)
        vec_ptr(local_id) = vec_ptr(local_id) + vol_ptr(local_id)
      enddo
    case(SCALE_BY_PERM)
      do iconn = 1, cur_connection_set%num_connections
        local_id = cur_connection_set%id_dn(iconn)
        ghosted_id = grid%nL2G(local_id)
        vec_ptr(local_id) = vec_ptr(local_id) + perm_loc_ptr(ghosted_id) * &
                                                vol_ptr(local_id)
      enddo
    case(SCALE_BY_NEIGHBOR_PERM)
      do iconn = 1, cur_connection_set%num_connections
        local_id = cur_connection_set%id_dn(iconn)
        ghosted_id = grid%nL2G(local_id)
        call GridGetGhostedNeighbors(grid,ghosted_id,DMDA_STENCIL_STAR, &
                                    x_width,y_width,z_width, &
                                    x_count,y_count,z_count, &
                                    ghosted_neighbors,option)
        ! ghosted neighbors is ordered first in x, then, y, then z
        icount = 0
        sum = 0.d0
        ! x-direction
        do while (icount < x_count)
          icount = icount + 1
          neighbor_ghosted_id = ghosted_neighbors(icount)
          sum = sum + perm_loc_ptr(neighbor_ghosted_id)* &
                      grid%structured_grid%dy(neighbor_ghosted_id)* &
                      grid%structured_grid%dz(neighbor_ghosted_id)
             
        enddo
        ! y-direction
        do while (icount < x_count + y_count)
          icount = icount + 1
          neighbor_ghosted_id = ghosted_neighbors(icount)                 
          sum = sum + perm_loc_ptr(neighbor_ghosted_id)* &
                      grid%structured_grid%dx(neighbor_ghosted_id)* &
                      grid%structured_grid%dz(neighbor_ghosted_id)
             
        enddo
        ! z-direction
        do while (icount < x_count + y_count + z_count)
          icount = icount + 1
          neighbor_ghosted_id = ghosted_neighbors(icount)                 
          sum = sum + perm_loc_ptr(neighbor_ghosted_id)* &
                      grid%structured_grid%dx(neighbor_ghosted_id)* &
                      grid%structured_grid%dy(neighbor_ghosted_id)
        enddo
        vec_ptr(local_id) = vec_ptr(local_id) + sum
      enddo
  end select

  call GridVecRestoreArrayF90(grid,field%work,vec_ptr,ierr)
  call VecNorm(field%work,NORM_1,scale,ierr)
  scale = 1.d0/scale
  call VecScale(field%work,scale,ierr)

  call GridVecGetArrayF90(grid,field%work,vec_ptr, ierr)
  do iconn = 1, cur_connection_set%num_connections      
    local_id = cur_connection_set%id_dn(iconn)
    select case(option%iflowmode)
      case(RICHARDS_MODE,G_MODE)
        source_sink%flow_aux_real_var(ONE_INTEGER,iconn) = &
          vec_ptr(local_id)
      case(TH_MODE)
      case(THC_MODE)
      case(THMC_MODE)
      case(MPH_MODE)
      case(IMS_MODE)
      case(MIS_MODE)
      case(FLASH2_MODE)
    end select 

  enddo
  call GridVecRestoreArrayF90(grid,field%work,vec_ptr,ierr)

  call GridVecRestoreArrayF90(grid,field%perm_xx_loc,perm_loc_ptr, ierr)
  call GridVecRestoreArrayF90(grid,field%volume,vol_ptr, ierr)
   
end subroutine PatchScaleSourceSink

! ************************************************************************** !
!> This subroutine updates aux vars for distributed copuler_type
!!
!> @author
!! Gautam Bisht, LBL
!!
!! date: 10/03/2012
! ************************************************************************** !
subroutine PatchUpdateHetroCouplerAuxVars(patch,coupler,flow_dataset, &
          sum_connection,isub_condition,option)

  use Option_module
  use Field_module
  use Coupler_module
  use Connection_module
  use Condition_module
  use Grid_module
  use Dataset_module
  use Dataset_Aux_module

  implicit none

#include "finclude/petscvec.h"
#include "finclude/petscvec.h90"
#include "finclude/petscdmda.h"

  type(patch_type) :: patch
  type(coupler_type) :: coupler
  type(flow_condition_dataset_type) :: flow_dataset
  PetscInt :: isub_condition
  type(option_type) :: option

  type(connection_set_type), pointer :: cur_connection_set
  type(grid_type),pointer :: grid
  PetscErrorCode :: ierr
  PetscInt       :: iconn,sum_connection
  PetscInt :: ghosted_id,local_id
  PetscInt,pointer::cell_ids_nat(:)
  type(flow_sub_condition_type) :: flow_sub_condition

  type(dataset_type), pointer :: dataset

  grid => patch%grid
  
  if (isub_condition>option%nflowdof*option%nphase) then
    option%io_buffer='ERROR: PatchUpdateHetroCouplerAuxVars  '// &
      'isub_condition > option%nflowdof*option%nphase.'
    call printErrMsg(option)
  endif
  
  !flow_sub_condition =>

  if(option%iflowmode/=RICHARDS_MODE.and.option%iflowmode/=TH_MODE) then
    option%io_buffer='PatchUpdateHetroCouplerAuxVars only implemented '// &
      ' for RICHARDS or TH mode.'
    call printErrMsg(option)
  endif

!  if(.not.associated(coupler%flow_condition%rate)) then
!    option%io_buffer='PatchUpdateHetroCouplerAuxVars only implemented '// &
!      ' for RATE flow condition.'
!    call printErrMsg(option)
!  endif

  dataset => flow_dataset%dataset
  cur_connection_set => coupler%connection_set

  if(associated(dataset)) then

    if(.not.associated(dataset%dataset_map)) then
      !
      ! Older scheme: Only works on a single proc run and assumes SS values are
      ! prescribed in the dataset at each CV
      !
      if(option%mycommsize>1) then
        option%io_buffer='PatchUpdateHetroCouplerAuxVars only implemented '// &
          ' for single processor runs.'
        call printErrMsg(option)
      endif

      if(size(dataset%rarray)/=cur_connection_set%num_connections) then
        option%io_buffer='Length of array in dataset does not match no. of connection '// &
          ' sets.'
        call printErrMsg(option)
      endif

      do iconn=1,cur_connection_set%num_connections
        coupler%flow_aux_real_var(isub_condition,iconn) = dataset%rarray(iconn)
      enddo

    else !if(.not.associated(dataset%dataset_map))

      ! New scheme: Mapping data is provided in HDF file
      !
    
      ! If called for the first time, create the map
      if (dataset%dataset_map%first_time) then
        allocate(cell_ids_nat(cur_connection_set%num_connections))
        do iconn=1,cur_connection_set%num_connections
          sum_connection = sum_connection + 1
          local_id = cur_connection_set%id_dn(iconn)
          ghosted_id = grid%nL2G(local_id)
          cell_ids_nat(iconn)=grid%nG2A(ghosted_id)
        enddo

        call PatchCreateFlowConditionDatasetMap(patch%grid,dataset%dataset_map,&
                cell_ids_nat,cur_connection_set%num_connections,option)

        dataset%dataset_map%first_time = PETSC_FALSE
        deallocate(cell_ids_nat)

      endif
    
      ! Save the data in the array
      do iconn=1,cur_connection_set%num_connections
        coupler%flow_aux_real_var(isub_condition,iconn) = &
          dataset%rarray(dataset%dataset_map%datatocell_ids(iconn))
      enddo

    endif !if(.not.associated(dataset%dataset_map))

  else ! if(associated(dataset)) 

    do iconn=1,cur_connection_set%num_connections
        coupler%flow_aux_real_var(isub_condition,iconn) = &
          flow_dataset%time_series%cur_value(1)
    enddo
  endif
  
end subroutine PatchUpdateHetroCouplerAuxVars

! ************************************************************************** !
!> This routine creates dataset-map for flow condition
!!
!> @author
!! Gautam Bisht, LBL
!!
!! date: 10/26/12
! ************************************************************************** !
subroutine PatchCreateFlowConditionDatasetMap(grid,dataset_map,cell_ids,ncells,option)

  use Grid_module
  use Dataset_module
  use Option_module
  
  implicit none
#include "finclude/petscvec.h"
#include "finclude/petscvec.h90"
#include "finclude/petscis.h"
#include "finclude/petscis.h90"
#include "finclude/petscviewer.h"

  type(grid_type) :: grid
  type(dataset_map_type) :: dataset_map
  type(option_type):: option
  PetscInt,pointer :: cell_ids(:)
  PetscInt :: ncells
  
  PetscInt, allocatable :: int_array(:)
  PetscInt :: ghosted_id,local_id
  PetscInt :: ii,count
  PetscReal, pointer :: vec_ptr(:)  
  PetscErrorCode :: ierr
  PetscInt :: nloc,nglo
  PetscInt :: istart
  
  IS :: is_from, is_to
  Vec:: map_ids_1, map_ids_2,map_ids_3
  VecScatter::vec_scatter
  PetscViewer :: viewer
  
  ! Step-1: Rearrange map dataset
  nloc = maxval(dataset_map%map(2,:))
  call MPI_Allreduce(nloc,nglo,ONE_INTEGER,MPIU_INTEGER,MPI_Max,option%mycomm,ierr)
  call VecCreateMPI(option%mycomm,dataset_map%map_dims_local(2),&
                    PETSC_DETERMINE,map_ids_1,ierr)
  call VecCreateMPI(option%mycomm,PETSC_DECIDE,nglo,map_ids_2,ierr)
  call VecSet(map_ids_2,0,ierr)

  istart = 0
  call MPI_Exscan(dataset_map%map_dims_local(2), istart, ONE_INTEGER_MPI, &
                  MPIU_INTEGER, MPI_SUM, option%mycomm, ierr)

  allocate(int_array(dataset_map%map_dims_local(2)))
  do ii=1,dataset_map%map_dims_local(2)
    int_array(ii)=ii+istart
  enddo
  int_array=int_array-1
  
  call ISCreateBlock(option%mycomm,1,dataset_map%map_dims_local(2), &
                     int_array,PETSC_COPY_VALUES,is_from,ierr)
  deallocate(int_array)
  
  allocate(int_array(dataset_map%map_dims_local(2)))
  do ii=1,dataset_map%map_dims_local(2)
    int_array(ii)=dataset_map%map(2,ii)
  enddo
  int_array=int_array-1

  call ISCreateBlock(option%mycomm,1,dataset_map%map_dims_local(2), &
                     int_array,PETSC_COPY_VALUES,is_to,ierr)
  deallocate(int_array)

  !call VecCreateSeq(PETSC_COMM_SELF,dataset_map%map_dims_global(2),map_ids_1,ierr)
  !call VecCreateSeq(PETSC_COMM_SELF,maxval(dataset_map%map(2,:)),map_ids_2,ierr)
  !call VecSet(map_ids_2,0,ierr)

  call VecScatterCreate(map_ids_1,is_from,map_ids_2,is_to,vec_scatter,ierr)
  call ISDestroy(is_from,ierr)
  call ISDestroy(is_to,ierr)

  call VecGetArrayF90(map_ids_1,vec_ptr,ierr)
  do ii=1,dataset_map%map_dims_local(2)
    vec_ptr(ii)=dataset_map%map(1,ii)
  enddo
  call VecRestoreArrayF90(map_ids_1,vec_ptr,ierr)

  call VecScatterBegin(vec_scatter,map_ids_1,map_ids_2, &
                       INSERT_VALUES,SCATTER_FORWARD,ierr)
  call VecScatterEnd(vec_scatter,map_ids_1,map_ids_2, &
                     INSERT_VALUES,SCATTER_FORWARD,ierr)
  call VecScatterDestroy(vec_scatter,ierr)

  ! Step-2: Get ids in map dataset for cells
  allocate(int_array(ncells))
  allocate(dataset_map%cell_ids_local(ncells))
  int_array=cell_ids-1

  call ISCreateBlock(option%mycomm,1,ncells,int_array,PETSC_COPY_VALUES,is_from,ierr)
    
  istart = 0
  call MPI_Exscan(ncells, istart, ONE_INTEGER_MPI, &
                  MPIU_INTEGER, MPI_SUM, option%mycomm, ierr)

  do local_id=1,ncells
    int_array(local_id)=local_id+istart
  enddo
  int_array=int_array-1
  
  call ISCreateBlock(option%mycomm,1,ncells,int_array,PETSC_COPY_VALUES,is_to,ierr)
  deallocate(int_array)
  
  !call VecCreateSeq(PETSC_COMM_SELF,ncells,map_ids_3,ierr)
  call VecCreateMPI(option%mycomm,ncells,PETSC_DETERMINE,map_ids_3,ierr)
  
  call VecScatterCreate(map_ids_2,is_from,map_ids_3,is_to,vec_scatter,ierr)
  call ISDestroy(is_from,ierr)
  call ISDestroy(is_to,ierr)

  call VecScatterBegin(vec_scatter,map_ids_2,map_ids_3, &
                       INSERT_VALUES,SCATTER_FORWARD,ierr)
  call VecScatterEnd(vec_scatter,map_ids_2,map_ids_3, &
                     INSERT_VALUES,SCATTER_FORWARD,ierr)
  call VecScatterDestroy(vec_scatter,ierr)

  ! Step-3: Save the datatocell_ids
  allocate(dataset_map%datatocell_ids(ncells))
  call VecGetArrayF90(map_ids_3,vec_ptr,ierr)
  do local_id=1,ncells
    dataset_map%datatocell_ids(local_id) = int(vec_ptr(local_id))
  enddo
  call VecRestoreArrayF90(map_ids_3,vec_ptr,ierr)
  
  call VecDestroy(map_ids_1,ierr)
  call VecDestroy(map_ids_2,ierr)
  call VecDestroy(map_ids_3,ierr)

end subroutine PatchCreateFlowConditionDatasetMap

! ************************************************************************** !
!
! PatchInitConstraints: Initializes constraint concentrations
! author: Glenn Hammond
! date: 12/04/08
!
! ************************************************************************** !
subroutine PatchInitConstraints(patch,reaction,option)

  use Reaction_Aux_module
    
  implicit none

  type(patch_type) :: patch
  type(option_type) :: option
  type(reaction_type), pointer :: reaction
  
  call PatchInitCouplerConstraints(patch%initial_conditions, &
                                   reaction,option)
  
  call PatchInitCouplerConstraints(patch%boundary_conditions, &
                                   reaction,option)
  
  call PatchInitCouplerConstraints(patch%source_sinks, &
                                   reaction,option)

end subroutine PatchInitConstraints

! ************************************************************************** !
!
! PatchInitCouplerConstraints: Initializes constraint concentrations
!                              for a given coupler
! author: Glenn Hammond
! date: 12/04/08
!
! ************************************************************************** !
subroutine PatchInitCouplerConstraints(coupler_list,reaction,option)

  use Reaction_module
  use Reactive_Transport_Aux_module
  use Reaction_Aux_module
  use Global_Aux_module
  use Constraint_module
  use Water_EOS_module
    
  implicit none

  type(coupler_list_type), pointer :: coupler_list
  type(option_type) :: option
  type(reaction_type), pointer :: reaction

  type(reactive_transport_auxvar_type), pointer :: rt_auxvar
  type(global_auxvar_type), pointer :: global_auxvar
  type(coupler_type), pointer :: cur_coupler
  type(tran_constraint_coupler_type), pointer :: cur_constraint_coupler
  PetscReal :: r1, r2, r3, r4, r5, r6
  PetscErrorCode :: ierr
  
  cur_coupler => coupler_list%first
  do
    if (.not.associated(cur_coupler)) exit

    if (.not.associated(cur_coupler%tran_condition)) then
      option%io_buffer = 'Null transport condition found in coupler'
      if (len_trim(cur_coupler%name) > 1) then
        option%io_buffer = trim(option%io_buffer) // &
                           ' "' // trim(cur_coupler%name) // '"'
      endif
      call printErrMsg(option)
    endif

    cur_constraint_coupler => &
      cur_coupler%tran_condition%constraint_coupler_list
    do
      if (.not.associated(cur_constraint_coupler)) exit
      global_auxvar => cur_constraint_coupler%global_auxvar
      rt_auxvar => cur_constraint_coupler%rt_auxvar
      if (associated(cur_coupler%flow_condition)) then
        if (associated(cur_coupler%flow_condition%pressure)) then
          if (associated(cur_coupler%flow_condition%pressure% &
                         flow_dataset%time_series)) then
            global_auxvar%pres = &
              cur_coupler%flow_condition%pressure%flow_dataset% &
                time_series%cur_value(1)
          else
            global_auxvar%pres = option%reference_pressure
          endif
        else
          global_auxvar%pres = option%reference_pressure
        endif
        if (associated(cur_coupler%flow_condition%temperature)) then
          if (associated(cur_coupler%flow_condition%temperature% &
                         flow_dataset%time_series)) then
            global_auxvar%temp = &
              cur_coupler%flow_condition%temperature%flow_dataset% &
                time_series%cur_value(1)
          else
            global_auxvar%temp = option%reference_temperature
          endif
        else
          global_auxvar%temp = option%reference_temperature
        endif

#ifndef DONT_USE_WATEOS
        call wateos(global_auxvar%temp(1),global_auxvar%pres(1), &
                    global_auxvar%den_kg(1),r1,r2,r3,r4,r5,r6, &
                    option%scale,ierr)
#else
        call density(global_auxvar%temp(1),global_auxvar%pres(1), &
                     global_auxvar%den_kg(1))
#endif                     
      else
        global_auxvar%pres = option%reference_pressure
        global_auxvar%temp = option%reference_temperature
        global_auxvar%den_kg = option%reference_water_density
      endif     
      global_auxvar%sat = option%reference_saturation  
  
      call ReactionEquilibrateConstraint(rt_auxvar,global_auxvar, &
                            reaction,cur_constraint_coupler%constraint_name, &
                            cur_constraint_coupler%aqueous_species, &
                            cur_constraint_coupler%minerals, &
                            cur_constraint_coupler%surface_complexes, &
                            cur_constraint_coupler%colloids, &
                            cur_constraint_coupler%immobile_species, &
                            option%reference_porosity, &
                            cur_constraint_coupler%num_iterations, &
                            PETSC_FALSE,option)
      cur_constraint_coupler => cur_constraint_coupler%next
    enddo
    cur_coupler => cur_coupler%next
  enddo

end subroutine PatchInitCouplerConstraints

! ************************************************************************** !
!
! PatchUpdateUniformVelocity: Assigns uniform velocity in connection list
!                        darcy velocities
! author: Glenn Hammond
! date: 02/20/08
!
! ************************************************************************** !
subroutine PatchUpdateUniformVelocity(patch,velocity,option)

  use Option_module
  use Coupler_module
  use Condition_module
  use Connection_module
  
  implicit none
  
  type(patch_type), pointer :: patch   
  PetscReal :: velocity(3)
  type(option_type), pointer :: option

  type(grid_type), pointer :: grid
  type(coupler_type), pointer :: boundary_condition
  type(connection_set_type), pointer :: cur_connection_set
  PetscInt :: iconn, sum_connection
  PetscReal :: vdarcy

  grid => patch%grid
    
  ! Internal Flux Terms -----------------------------------
  cur_connection_set => grid%internal_connection_set_list%first
  sum_connection = 0
  do 
    if (.not.associated(cur_connection_set)) exit
    do iconn = 1, cur_connection_set%num_connections
      sum_connection = sum_connection + 1
      vdarcy = dot_product(velocity, &
                           cur_connection_set%dist(1:3,iconn))
      patch%internal_velocities(1,sum_connection) = vdarcy
    enddo
    cur_connection_set => cur_connection_set%next
  enddo    

  ! Boundary Flux Terms -----------------------------------
  boundary_condition => patch%boundary_conditions%first
  sum_connection = 0
  do 
    if (.not.associated(boundary_condition)) exit
    cur_connection_set => boundary_condition%connection_set
    do iconn = 1, cur_connection_set%num_connections
      sum_connection = sum_connection + 1
      vdarcy = dot_product(velocity, &
                           cur_connection_set%dist(1:3,iconn))
      patch%boundary_velocities(1,sum_connection) = vdarcy
    enddo
    boundary_condition => boundary_condition%next
  enddo

end subroutine PatchUpdateUniformVelocity

! ************************************************************************** !
!
! PatchAuxVarsUpToDate: Checks to see if aux vars are up to date
! author: Glenn Hammond
! date: 09/12/08
!
! ************************************************************************** !
function PatchAuxVarsUpToDate(patch)

  use Grid_module
  use Option_module
  use Field_module
  
  use Mphase_Aux_module
  use TH_Aux_module
  use THC_Aux_module
  use THMC_Aux_module
  use Richards_Aux_module
  use Reactive_Transport_Aux_module  
  
  type(patch_type) :: patch
  
  PetscBool :: PatchAuxVarsUpToDate
  PetscBool :: flow_up_to_date
  PetscBool :: transport_up_to_date
  PetscInt :: dummy
  dummy = 1

  if (associated(patch%aux%THC)) then
    flow_up_to_date = patch%aux%THC%aux_vars_up_to_date
  else if (associated(patch%aux%TH)) then
    flow_up_to_date = patch%aux%TH%aux_vars_up_to_date
  else if (associated(patch%aux%THMC)) then
    flow_up_to_date = patch%aux%THMC%aux_vars_up_to_date
  else if (associated(patch%aux%Richards)) then
    flow_up_to_date = patch%aux%Richards%aux_vars_up_to_date
  else if (associated(patch%aux%Mphase)) then
    flow_up_to_date = patch%aux%Mphase%aux_vars_up_to_date
  else if (associated(patch%aux%Flash2)) then
    flow_up_to_date = patch%aux%Flash2%aux_vars_up_to_date
  else if (associated(patch%aux%Immis)) then
    flow_up_to_date = patch%aux%Immis%aux_vars_up_to_date
  endif

  if (associated(patch%aux%RT)) then
    transport_up_to_date = patch%aux%RT%aux_vars_up_to_date
  endif
  
  PatchAuxVarsUpToDate = flow_up_to_date .and. transport_up_to_date
  
end function PatchAuxVarsUpToDate

! ************************************************************************** !
!
! PatchGetDataset: Extracts variables indexed by ivar and isubvar from a patch
! author: Glenn Hammond
! date: 09/12/08
!
! ************************************************************************** !
subroutine PatchGetDataset1(patch,field,reaction,option,output_option,vec,ivar, &
                           isubvar,isubvar1)

  use Grid_module
  use Option_module
  use Field_module
  
  use Immis_Aux_module
  use Miscible_Aux_module
  use Mphase_Aux_module
  use TH_Aux_module
  use THC_Aux_module
  use THMC_Aux_module
  use Richards_Aux_module
  use Mineral_module
  use Reaction_module
  use Reactive_Transport_Aux_module  
  use Surface_Complexation_Aux_module
  use General_Aux_module
  use Output_Aux_module
  use Variables_module
  
  implicit none

#include "finclude/petscvec.h"
#include "finclude/petscvec.h90"

  type(option_type), pointer :: option
  type(reaction_type), pointer :: reaction
  type(output_option_type), pointer :: output_option
  type(field_type), pointer :: field
  type(patch_type), pointer :: patch  
  Vec :: vec
  PetscInt :: ivar
  PetscInt :: isubvar
  PetscInt, optional :: isubvar1
  PetscInt :: iphase

  PetscInt :: local_id, ghosted_id
  type(grid_type), pointer :: grid
  PetscReal, pointer :: vec_ptr(:), vec_ptr2(:)
  PetscReal :: xmass
  PetscReal :: tempreal
  PetscInt :: tempint
  PetscInt :: irate, istate, irxn
  PetscErrorCode :: ierr

  grid => patch%grid

  call GridVecGetArrayF90(grid,vec,vec_ptr,ierr)

  iphase = 1
  select case(ivar)
    case(TEMPERATURE,LIQUID_PRESSURE,GAS_PRESSURE, &
         LIQUID_SATURATION,GAS_SATURATION,ICE_SATURATION, &
         LIQUID_MOLE_FRACTION,GAS_MOLE_FRACTION,LIQUID_ENERGY,GAS_ENERGY, &
         LIQUID_DENSITY,GAS_DENSITY,GAS_DENSITY_MOL,LIQUID_VISCOSITY,GAS_VISCOSITY, &
         LIQUID_MOBILITY,GAS_MOBILITY,SC_FUGA_COEFF,STATE,ICE_DENSITY)
         
      if (associated(patch%aux%THC)) then
        select case(ivar)
          case(TEMPERATURE)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%temp(1)
            enddo
          case(LIQUID_PRESSURE)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%pres(1)
            enddo
          case(LIQUID_SATURATION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%sat(1)
            enddo
          case(LIQUID_DENSITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%den_kg(1)
            enddo
          case(GAS_MOLE_FRACTION,GAS_ENERGY,GAS_DENSITY,GAS_VISCOSITY) ! still needs implementation
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = 0.d0
            enddo
          case(GAS_SATURATION)
            do local_id=1,grid%nlmax
#ifdef ICE
              vec_ptr(local_id) = patch%aux%THC%aux_vars(grid%nL2G(local_id))%sat_gas
#else
              vec_ptr(local_id) = 0.d0
#endif 
            enddo
#ifdef ICE
          case(ICE_SATURATION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%THC%aux_vars(grid%nL2G(local_id))%sat_ice
            enddo
          case(ICE_DENSITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%THC%aux_vars(grid%nL2G(local_id))%den_ice*FMWH2O
            enddo
#endif
          case(LIQUID_VISCOSITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%THC%aux_vars(grid%nL2G(local_id))%vis
            enddo
          case(LIQUID_MOBILITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%THC%aux_vars(grid%nL2G(local_id))%kvr
            enddo
          case(LIQUID_MOLE_FRACTION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%THC%aux_vars(grid%nL2G(local_id))%xmol(isubvar)
            enddo
          case(LIQUID_ENERGY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%THC%aux_vars(grid%nL2G(local_id))%u
            enddo
        end select

      else if (associated(patch%aux%TH)) then
        select case(ivar)
          case(TEMPERATURE)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%temp(1)
            enddo
          case(LIQUID_PRESSURE)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%pres(1)
            enddo
          case(LIQUID_SATURATION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%sat(1)
            enddo
          case(LIQUID_DENSITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%den_kg(1)
            enddo
          case(GAS_MOLE_FRACTION,GAS_ENERGY,GAS_DENSITY,GAS_VISCOSITY) ! still needs implementation
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = 0.d0
            enddo
          case(GAS_SATURATION)
            do local_id=1,grid%nlmax
#ifdef ICE
              vec_ptr(local_id) = patch%aux%TH%aux_vars(grid%nL2G(local_id))%sat_gas
#else
              vec_ptr(local_id) = 0.d0
#endif 
            enddo
#ifdef ICE
          case(ICE_SATURATION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%TH%aux_vars(grid%nL2G(local_id))%sat_ice
            enddo
          case(ICE_DENSITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%TH%aux_vars(grid%nL2G(local_id))%den_ice*FMWH2O
            enddo
#endif
          case(LIQUID_VISCOSITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%TH%aux_vars(grid%nL2G(local_id))%vis
            enddo
          case(LIQUID_MOBILITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%TH%aux_vars(grid%nL2G(local_id))%kvr
            enddo
          case(LIQUID_MOLE_FRACTION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%TH%aux_vars(grid%nL2G(local_id))%xmol(isubvar)
            enddo
          case(LIQUID_ENERGY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%TH%aux_vars(grid%nL2G(local_id))%u
            enddo
        end select
        
      else if (associated(patch%aux%THMC)) then
        select case(ivar)
          case(TEMPERATURE)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%temp(1)
            enddo
          case(LIQUID_PRESSURE)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%pres(1)
            enddo
          case(LIQUID_SATURATION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%sat(1)
            enddo
          case(LIQUID_DENSITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%den_kg(1)
            enddo
          case(GAS_MOLE_FRACTION,GAS_ENERGY,GAS_DENSITY,GAS_VISCOSITY) ! still needs implementation
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = 0.d0
            enddo
          case(GAS_SATURATION)
            do local_id=1,grid%nlmax
#ifdef ICE
              vec_ptr(local_id) = patch%aux%THMC%aux_vars(grid%nL2G(local_id))%sat_gas
#else
              vec_ptr(local_id) = 0.d0
#endif 
            enddo
#ifdef ICE
          case(ICE_SATURATION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%THMC%aux_vars(grid%nL2G(local_id))%sat_ice
            enddo
          case(ICE_DENSITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%THMC%aux_vars(grid%nL2G(local_id))%den_ice*FMWH2O
            enddo
#endif
          case(LIQUID_VISCOSITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%THMC%aux_vars(grid%nL2G(local_id))%vis
            enddo
          case(LIQUID_MOBILITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%THMC%aux_vars(grid%nL2G(local_id))%kvr
            enddo
          case(LIQUID_MOLE_FRACTION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%THMC%aux_vars(grid%nL2G(local_id))%xmol(isubvar)
            enddo
          case(LIQUID_ENERGY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%THMC%aux_vars(grid%nL2G(local_id))%u
            enddo
        end select
        
      else if (associated(patch%aux%Richards)) then
      
        select case(ivar)
          case(TEMPERATURE)
            call printErrMsg(option,'TEMPERATURE not supported by Richards')
          case(GAS_SATURATION)
            call printErrMsg(option,'GAS_SATURATION not supported by Richards')
          case(ICE_SATURATION)
            call printErrMsg(option,'ICE_SATURATION not supported by Richards')
          case(ICE_DENSITY)
            call printErrMsg(option,'ICE_DENSITY not supported by Richards')
          case(GAS_DENSITY)
            call printErrMsg(option,'GAS_DENSITY not supported by Richards')
          case(LIQUID_MOLE_FRACTION)
            call printErrMsg(option,'LIQUID_MOLE_FRACTION not supported by Richards')
          case(GAS_MOLE_FRACTION)
            call printErrMsg(option,'GAS_MOLE_FRACTION not supported by Richards')
          case(LIQUID_ENERGY)
            call printErrMsg(option,'LIQUID_ENERGY not supported by Richards')
          case(GAS_ENERGY)
            call printErrMsg(option,'GAS_ENERGY not supported by Richards')
          case(LIQUID_VISCOSITY)
            call printErrMsg(option,'LIQUID_VISCOSITY not supported by Richards')
          case(GAS_VISCOSITY)
            call printErrMsg(option,'GAS_VISCOSITY not supported by Richards')
          case(LIQUID_MOBILITY)
            call printErrMsg(option,'LIQUID_MOBILITY not supported by Richards')
          case(GAS_MOBILITY)
            call printErrMsg(option,'GAS_MOBILITY not supported by Richards')
          case(LIQUID_PRESSURE)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = &
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%pres(1)
            enddo
          case(LIQUID_SATURATION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = &
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%sat(1)
            enddo
          case(LIQUID_DENSITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = &
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%den_kg(1)
            enddo
        end select
        
      else if (associated(patch%aux%Flash2)) then
      
        select case(ivar)
          case(TEMPERATURE)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%temp(1)
            enddo
          case(LIQUID_PRESSURE)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%pres(2)
            enddo
          case(LIQUID_SATURATION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%sat(1)
            enddo
          case(LIQUID_DENSITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%den_kg(1)
            enddo
          case(GAS_SATURATION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%sat(2)
            enddo
          case(GAS_MOLE_FRACTION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%xmol(2+isubvar)
            enddo
          case(GAS_ENERGY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%u(2)
            enddo
          case(GAS_VISCOSITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%vis(2)
            enddo
          case(GAS_MOBILITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%kvr(2)
            enddo
          case(GAS_DENSITY) 
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%den_kg(2)
            enddo
          case(GAS_DENSITY_MOL) 
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%den(2)
            enddo
          case(SC_FUGA_COEFF)
            if (.not.associated(patch%aux%Global%aux_vars(1)%fugacoeff) .and. &
                OptionPrintToScreen(option))then
               print *,'ERRor, fugacoeff not allocated for ', option%iflowmode, 1
            endif
            do local_id=1,grid%nlmax
             vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%fugacoeff(1)
            enddo 
          case(LIQUID_MOLE_FRACTION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%xmol(isubvar)
            enddo
          case(LIQUID_VISCOSITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%vis(1)
            enddo
          case(LIQUID_MOBILITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%kvr(1)
            enddo
          case(LIQUID_ENERGY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%u(1)
            enddo
        end select
        
      else if (associated(patch%aux%Mphase)) then
        
        select case(ivar)
        
          case(TEMPERATURE)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%temp(1)
            enddo
          case(LIQUID_PRESSURE)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%pres(1)
            enddo
          case(GAS_PRESSURE)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%pres(2)
            enddo
          case(LIQUID_SATURATION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%sat(1)
            enddo
          case(LIQUID_DENSITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%den_kg(1)
            enddo
          case(LIQUID_VISCOSITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Mphase%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%vis(1)
            enddo
          case(LIQUID_MOBILITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Mphase%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%kvr(1)
            enddo
          case(GAS_SATURATION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%sat(2)
            enddo
          case(GAS_MOLE_FRACTION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Mphase%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%xmol(2+isubvar)
            enddo
          case(GAS_ENERGY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Mphase%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%u(2)
            enddo
          case(GAS_VISCOSITY) 
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Mphase%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%vis(2)
            enddo
          case(GAS_MOBILITY) 
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Mphase%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%kvr(2)
            enddo
          case(GAS_DENSITY) 
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%den_kg(2)
            enddo
          case(GAS_DENSITY_MOL) 
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%den(2)
            enddo
          case(SC_FUGA_COEFF)
            if (.not.associated(patch%aux%Global%aux_vars(1)%fugacoeff) .and. &
                OptionPrintToScreen(option))then
               print *,'ERRor, fugacoeff not allocated for ', option%iflowmode, 1
            endif
            do local_id=1,grid%nlmax
             vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%fugacoeff(1)
            enddo 
          case(LIQUID_MOLE_FRACTION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Mphase%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%xmol(isubvar)
            enddo
          case(LIQUID_ENERGY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Mphase%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%u(1)
            enddo
        end select
        
      else if (associated(patch%aux%Miscible)) then
        
        select case(ivar)
        
!         case(TEMPERATURE)
!           do local_id=1,grid%nlmax
!             vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%temp(1)
!           enddo
          case(LIQUID_PRESSURE)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%pres(1)
            enddo
          case(LIQUID_DENSITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%den_kg(1)
            enddo
          case(LIQUID_VISCOSITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Miscible%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%vis(1)
            enddo
          case(LIQUID_MOLE_FRACTION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Miscible%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%xmol(isubvar)
            enddo
        end select
        
      else if (associated(patch%aux%immis)) then
      
        select case(ivar)
          case(TEMPERATURE)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%temp(1)
            enddo
          case(LIQUID_PRESSURE)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%pres(2)
            enddo
          case(LIQUID_SATURATION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%sat(1)
            enddo
          case(LIQUID_DENSITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%den_kg(1)
            enddo
          case(LIQUID_ENERGY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Immis%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%u(1)
            enddo
          case(GAS_SATURATION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%sat(2)
            enddo
          case(GAS_ENERGY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Immis%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%u(2)
            enddo
          case(GAS_DENSITY) 
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%den_kg(2)
            enddo
        end select
      else if (associated(patch%aux%General)) then
        select case(ivar)
          case(TEMPERATURE)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%temp
            enddo
          case(LIQUID_PRESSURE)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%pres(option%liquid_phase)
            enddo
          case(GAS_PRESSURE)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%pres(option%gas_phase)
            enddo
          case(STATE)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%Global%aux_vars(grid%nL2G(local_id))%istate
            enddo
          case(LIQUID_SATURATION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%sat(option%liquid_phase)
            enddo
          case(LIQUID_DENSITY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%den_kg(option%liquid_phase)
            enddo
          case(LIQUID_ENERGY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%U(option%liquid_phase)
            enddo
          case(LIQUID_MOLE_FRACTION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%xmol(isubvar,option%liquid_phase)
            enddo
          case(GAS_SATURATION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%sat(option%gas_phase)
            enddo
          case(GAS_ENERGY)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%U(option%gas_phase)
            enddo
          case(GAS_DENSITY) 
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%den_kg(option%gas_phase)
            enddo
          case(GAS_MOLE_FRACTION)
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%xmol(isubvar,option%gas_phase)
            enddo
        end select         
      endif
      
    case(PH,PRIMARY_MOLALITY,PRIMARY_MOLARITY,SECONDARY_MOLALITY, &
         SECONDARY_MOLARITY,TOTAL_MOLALITY,TOTAL_MOLARITY, &
         MINERAL_RATE,MINERAL_VOLUME_FRACTION,MINERAL_SATURATION_INDEX, &
         SURFACE_CMPLX,SURFACE_CMPLX_FREE,SURFACE_SITE_DENSITY, &
         KIN_SURFACE_CMPLX,KIN_SURFACE_CMPLX_FREE, &
         PRIMARY_ACTIVITY_COEF,SECONDARY_ACTIVITY_COEF,PRIMARY_KD,TOTAL_SORBED, &
         TOTAL_SORBED_MOBILE,COLLOID_MOBILE,COLLOID_IMMOBILE,AGE,TOTAL_BULK, &
         IMMOBILE_SPECIES)
         
      select case(ivar)
        case(PH)
          do local_id=1,grid%nlmax
            ghosted_id = grid%nL2G(local_id)
            if (patch%aux%RT%aux_vars(ghosted_id)%pri_molal(isubvar) > &
                0.d0) then
              vec_ptr(local_id) = &
               -log10(patch%aux%RT%aux_vars(ghosted_id)%pri_act_coef(isubvar)* &
                      patch%aux%RT%aux_vars(ghosted_id)%pri_molal(isubvar))
            else
              vec_ptr(local_id) = 0.d0
            endif
          enddo
        case(PRIMARY_MOLALITY)
          do local_id=1,grid%nlmax
            vec_ptr(local_id) = &
              patch%aux%RT%aux_vars(grid%nL2G(local_id))%pri_molal(isubvar)
          enddo
        case(PRIMARY_MOLARITY)
          do local_id=1,grid%nlmax
            ghosted_id = grid%nL2G(local_id)
            if (associated(patch%aux%Global%aux_vars(ghosted_id)%xmass)) then
              xmass = patch%aux%Global%aux_vars(ghosted_id)%xmass(iphase)
            else
              xmass = 1.d0
            endif
            vec_ptr(local_id) = &
              patch%aux%RT%aux_vars(ghosted_id)%pri_molal(isubvar) * xmass * &
              (patch%aux%Global%aux_vars(ghosted_id)%den_kg(iphase)/1000.d0)
          enddo
        case(SECONDARY_MOLALITY)
          do local_id=1,grid%nlmax
            ghosted_id = grid%nL2G(local_id)
            vec_ptr(local_id) = &
              patch%aux%RT%aux_vars(ghosted_id)%sec_molal(isubvar)
          enddo
        case(SECONDARY_MOLARITY)
          do local_id=1,grid%nlmax
            ghosted_id = grid%nL2G(local_id)
            if (associated(patch%aux%Global%aux_vars(ghosted_id)%xmass)) then
              xmass = patch%aux%Global%aux_vars(ghosted_id)%xmass(iphase)
            else
              xmass = 1.d0
            endif
            vec_ptr(local_id) = &
              patch%aux%RT%aux_vars(ghosted_id)%sec_molal(isubvar) * xmass * &
              (patch%aux%Global%aux_vars(ghosted_id)%den_kg(iphase)/1000.d0)
          enddo
        case(TOTAL_MOLALITY)
          do local_id=1,grid%nlmax
            ghosted_id =grid%nL2G(local_id)
            if (associated(patch%aux%Global%aux_vars(ghosted_id)%xmass)) then
              xmass = patch%aux%Global%aux_vars(ghosted_id)%xmass(iphase)
            else
              xmass = 1.d0
            endif
            if (patch%aux%Global%aux_vars(ghosted_id)%den_kg(iphase) > 0.d0) then
              vec_ptr(local_id) = &
                patch%aux%RT%aux_vars(ghosted_id)%total(isubvar,iphase) / xmass / &
                (patch%aux%Global%aux_vars(ghosted_id)%den_kg(iphase)/1000.d0)
            else
              vec_ptr(local_id) = 0.d0
            endif
          enddo
        case(TOTAL_MOLARITY)
          do local_id=1,grid%nlmax
            vec_ptr(local_id) = &
              patch%aux%RT%aux_vars(grid%nL2G(local_id))%total(isubvar,iphase)
          enddo
        case(TOTAL_BULK) ! mol/m^3 bulk
          ! add in total molarity and convert to mol/m^3 bulk
          call GridVecGetArrayF90(grid,field%porosity_loc,vec_ptr2,ierr)
          do local_id=1,grid%nlmax
            ghosted_id = grid%nL2G(local_id)
            vec_ptr(local_id) = &
              patch%aux%RT%aux_vars(ghosted_id)%total(isubvar,iphase) * &
              vec_ptr2(ghosted_id) * &
              patch%aux%Global%aux_vars(ghosted_id)%sat(iphase) * 1.d-3 ! mol/L -> mol/m^3
          enddo
          call GridVecRestoreArrayF90(grid,field%porosity_loc,vec_ptr2,ierr)
          ! add in total sorbed.  already in mol/m^3 bulk
          if (patch%reaction%nsorb > 0) then
            do local_id=1,grid%nlmax
              ghosted_id = grid%nL2G(local_id)
              if (patch%reaction%surface_complexation%neqsrfcplxrxn > 0) then
                vec_ptr(local_id) = vec_ptr(local_id) + &
                  patch%aux%RT%aux_vars(ghosted_id)%total_sorb_eq(isubvar)
              endif
              if (patch%reaction%surface_complexation%nkinmrsrfcplxrxn > 0) then
                do irxn = 1, &
                   patch%reaction%surface_complexation%nkinmrsrfcplxrxn
                  do irate = 1, &
                     patch%reaction%surface_complexation%kinmr_nrate(irxn)
                    vec_ptr(local_id) = vec_ptr(local_id) + &
                      patch%aux%RT%aux_vars(ghosted_id)% &
                        kinmr_total_sorb(isubvar,irate,irxn)
                  enddo 
                enddo
              endif
            enddo
          endif
        case(MINERAL_VOLUME_FRACTION)
          do local_id=1,grid%nlmax
            vec_ptr(local_id) = &
              patch%aux%RT%aux_vars(grid%nL2G(local_id))%mnrl_volfrac(isubvar)
          enddo
        case(MINERAL_RATE)
          do local_id=1,grid%nlmax
            vec_ptr(local_id) = &
              patch%aux%RT%aux_vars(grid%nL2G(local_id))%mnrl_rate(isubvar)
          enddo
        case(MINERAL_SATURATION_INDEX)
          do local_id = 1, grid%nlmax
            ghosted_id = grid%nL2G(local_id)
            vec_ptr(local_id) = RMineralSaturationIndex(isubvar, &
                                                  patch%aux%RT%aux_vars(ghosted_id), &
                                                  patch%aux%Global%aux_vars(ghosted_id), &
                                                  reaction,option)
          enddo
        case(IMMOBILE_SPECIES)
          do local_id=1,grid%nlmax
            vec_ptr(local_id) = &
              patch%aux%RT%aux_vars(grid%nL2G(local_id))%immobile(isubvar)
          enddo          
        case(SURFACE_CMPLX)
          if (associated(patch%aux%RT%aux_vars(1)%eqsrfcplx_conc)) then
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = patch%aux%RT%aux_vars(grid%nL2G(local_id))% &
                                    eqsrfcplx_conc(isubvar)
            enddo
          else
            vec_ptr = -999.d0
          endif
        case(SURFACE_SITE_DENSITY)
          tempreal = reaction%surface_complexation%srfcplxrxn_site_density(isubvar)
          select case(reaction%surface_complexation%srfcplxrxn_surf_type(isubvar))
            case(MINERAL_SURFACE)
              tempint = reaction%surface_complexation%srfcplxrxn_to_surf(isubvar)
              do local_id=1,grid%nlmax
                vec_ptr(local_id) = tempreal* &
                                    patch%aux%RT%aux_vars(grid%nL2G(local_id))% &
                                      mnrl_volfrac(tempint)
              enddo
            case(COLLOID_SURFACE)
                option%io_buffer = 'Printing of surface site density for colloidal surfaces ' // &
                  'not implemented.'
                call printErrMsg(option)
            case(NULL_SURFACE)
              do local_id=1,grid%nlmax
                vec_ptr(local_id) = tempreal
              enddo
          end select          
        case(SURFACE_CMPLX_FREE)
          do local_id=1,grid%nlmax
            vec_ptr(local_id) = patch%aux%RT%aux_vars(grid%nL2G(local_id))% &
              srfcplxrxn_free_site_conc(isubvar)
          enddo
        case(KIN_SURFACE_CMPLX)
          do local_id=1,grid%nlmax
            vec_ptr(local_id) = patch%aux%RT%aux_vars(grid%nL2G(local_id))% &
              kinsrfcplx_conc(isubvar,1)
          enddo
        case(KIN_SURFACE_CMPLX_FREE)
          do local_id=1,grid%nlmax
            vec_ptr(local_id) = patch%aux%RT%aux_vars(grid%nL2G(local_id))% &
              kinsrfcplx_free_site_conc(isubvar)
          enddo
        case(PRIMARY_ACTIVITY_COEF)
          do local_id=1,grid%nlmax
            ghosted_id = grid%nL2G(local_id)
            vec_ptr(local_id) = &
              patch%aux%RT%aux_vars(ghosted_id)%pri_act_coef(isubvar)
          enddo
        case(SECONDARY_ACTIVITY_COEF)
          do local_id=1,grid%nlmax
            ghosted_id = grid%nL2G(local_id)
            vec_ptr(local_id) = &
              patch%aux%RT%aux_vars(ghosted_id)%sec_act_coef(isubvar)
          enddo
        case(PRIMARY_KD)
          call GridVecGetArrayF90(grid,field%porosity_loc,vec_ptr2,ierr)
          do local_id=1,grid%nlmax
            ghosted_id = grid%nL2G(local_id)
            call ReactionComputeKd(isubvar,vec_ptr(local_id), &
                                   patch%aux%RT%aux_vars(ghosted_id), &
                                   patch%aux%Global%aux_vars(ghosted_id), &
                                   vec_ptr2(ghosted_id),patch%reaction,option)
          enddo
          call GridVecRestoreArrayF90(grid,field%porosity_loc,vec_ptr2,ierr)
        case(TOTAL_SORBED)
          if (patch%reaction%nsorb > 0) then
            if (patch%reaction%neqsorb > 0) then
              do local_id=1,grid%nlmax
                ghosted_id = grid%nL2G(local_id)
                vec_ptr(local_id) = &
                  patch%aux%RT%aux_vars(ghosted_id)%total_sorb_eq(isubvar)
              enddo
            endif
            if (patch%reaction%surface_complexation%nkinmrsrfcplxrxn > 0) then
              do local_id=1,grid%nlmax
                ghosted_id = grid%nL2G(local_id)
                vec_ptr(local_id) = 0.d0
                do irxn = 1, &
                  patch%reaction%surface_complexation%nkinmrsrfcplxrxn
                  do irate = 1, &
                    patch%reaction%surface_complexation%kinmr_nrate(irxn)
                    vec_ptr(local_id) = vec_ptr(local_id) + &
                      patch%aux%RT%aux_vars(ghosted_id)% &
                        kinmr_total_sorb(isubvar,irate,irxn)
                  enddo            
                enddo            
              enddo
            endif
          endif
        case(TOTAL_SORBED_MOBILE)
          if (patch%reaction%nsorb > 0 .and. patch%reaction%ncollcomp > 0) then
            do local_id=1,grid%nlmax
              ghosted_id = grid%nL2G(local_id)
              vec_ptr(local_id) = patch%aux%RT%aux_vars(ghosted_id)%colloid% &
                total_eq_mob(isubvar)
            enddo
          endif
        case(COLLOID_MOBILE)
          if (patch%reaction%print_tot_conc_type == TOTAL_MOLALITY) then
            do local_id=1,grid%nlmax
              ghosted_id =grid%nL2G(local_id)
              if (patch%aux%Global%aux_vars(ghosted_id)%den_kg(iphase) > 0.d0) then
                vec_ptr(local_id) = &
                  patch%aux%RT%aux_vars(grid%nL2G(local_id))%colloid%conc_mob(isubvar) / &
                  (patch%aux%Global%aux_vars(ghosted_id)%den_kg(iphase)/1000.d0)
              else
                vec_ptr(local_id) = 0.d0
              endif
            enddo
          else
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = &
                patch%aux%RT%aux_vars(grid%nL2G(local_id))%colloid%conc_mob(isubvar)
            enddo
          endif      
        case(COLLOID_IMMOBILE)
          if (patch%reaction%print_tot_conc_type == TOTAL_MOLALITY) then
            do local_id=1,grid%nlmax
              ghosted_id =grid%nL2G(local_id)
              if (patch%aux%Global%aux_vars(ghosted_id)%den_kg(iphase) > 0.d0) then
                vec_ptr(local_id) = &
                  patch%aux%RT%aux_vars(grid%nL2G(local_id))%colloid%conc_imb(isubvar) / &
                  (patch%aux%Global%aux_vars(ghosted_id)%den_kg(iphase)/1000.d0)
              else
                vec_ptr(local_id) = 0.d0
              endif
            enddo
          else
            do local_id=1,grid%nlmax
              vec_ptr(local_id) = &
                patch%aux%RT%aux_vars(grid%nL2G(local_id))%colloid%conc_imb(isubvar)
            enddo
          endif
        case(AGE)
          do local_id=1,grid%nlmax
            ghosted_id = grid%nL2G(local_id)
            if (patch%aux%RT%aux_vars(ghosted_id)%pri_molal(isubvar) > &
                0.d0) then
              vec_ptr(local_id) = &
                patch%aux%RT%aux_vars(ghosted_id)%pri_molal(isubvar) / &
                patch%aux%RT%aux_vars(ghosted_id)%pri_molal(isubvar1) / &
                output_option%tconv
            endif
          enddo        
      end select
    case(POROSITY)
      call GridVecGetArrayF90(grid,field%porosity_loc,vec_ptr2,ierr)
      do local_id=1,grid%nlmax
        vec_ptr(local_id) = vec_ptr2(grid%nL2G(local_id))
      enddo
      call GridVecRestoreArrayF90(grid,field%porosity_loc,vec_ptr2,ierr)
    case(PERMEABILITY,PERMEABILITY_X)
      call GridVecGetArrayF90(grid,field%perm_xx_loc,vec_ptr2,ierr)
      do local_id=1,grid%nlmax
        vec_ptr(local_id) = vec_ptr2(grid%nL2G(local_id))
      enddo
      call GridVecRestoreArrayF90(grid,field%perm_xx_loc,vec_ptr2,ierr)
    case(PERMEABILITY_Y)
      call GridVecGetArrayF90(grid,field%perm_yy_loc,vec_ptr2,ierr)
      do local_id=1,grid%nlmax
        vec_ptr(local_id) = vec_ptr2(grid%nL2G(local_id))
      enddo
      call GridVecRestoreArrayF90(grid,field%perm_yy_loc,vec_ptr2,ierr)
    case(PERMEABILITY_Z)
      call GridVecGetArrayF90(grid,field%perm_zz_loc,vec_ptr2,ierr)
      do local_id=1,grid%nlmax
        vec_ptr(local_id) = vec_ptr2(grid%nL2G(local_id))
      enddo
      call GridVecRestoreArrayF90(grid,field%perm_zz_loc,vec_ptr2,ierr)
    case(PHASE)
      call GridVecGetArrayF90(grid,field%iphas_loc,vec_ptr2,ierr)
      do local_id=1,grid%nlmax
        vec_ptr(local_id) = vec_ptr2(grid%nL2G(local_id))
      enddo
      call GridVecRestoreArrayF90(grid,field%iphas_loc,vec_ptr2,ierr)
    case(MATERIAL_ID)
      do local_id=1,grid%nlmax
        vec_ptr(local_id) = patch%imat(grid%nL2G(local_id))
      enddo
    case(PROCESSOR_ID)
      do local_id=1,grid%nlmax
        vec_ptr(local_id) = option%myrank
      enddo
    case default
      write(option%io_buffer, &
            '(''IVAR ('',i3,'') not found in PatchGetDataset'')') ivar
      call printErrMsg(option)
  end select

  call GridVecRestoreArrayF90(grid,vec,vec_ptr,ierr)
  
end subroutine PatchGetDataset1

! ************************************************************************** !
!
! PatchGetDatasetValueAtCell: Returns variables indexed by ivar,
!                             isubvar, local id from Reactive Transport type
! author: Glenn Hammond
! date: 02/11/08
!
! ************************************************************************** !
function PatchGetDatasetValueAtCell(patch,field,reaction,option, &
                                    output_option, &
                                    ivar,isubvar,ghosted_id,isubvar1)

  use Grid_module
  use Option_module
  use Field_module

  use Mphase_Aux_module
  use TH_Aux_module
  use THC_Aux_module
  use THMC_Aux_module
  use Richards_Aux_module
  use Miscible_Aux_module
  use Reactive_Transport_Aux_module  
  use Mineral_module
  use Reaction_module
  use Mineral_Aux_module
  use Surface_Complexation_Aux_module
  use Output_Aux_module
  use Variables_module
  use General_Aux_module  

  implicit none

#include "finclude/petscvec.h"
#include "finclude/petscvec.h90"

  PetscReal :: PatchGetDatasetValueAtCell
  type(option_type), pointer :: option
  type(reaction_type), pointer :: reaction
  type(output_option_type), pointer :: output_option
  type(field_type), pointer :: field
  type(patch_type), pointer :: patch  
  PetscInt :: ivar
  PetscInt :: isubvar
  PetscInt, optional :: isubvar1
  PetscInt :: iphase
  PetscInt :: ghosted_id

  PetscReal :: value, xmass
  PetscInt :: irate, istate, irxn
  type(grid_type), pointer :: grid
  PetscReal, pointer :: vec_ptr2(:)  
  PetscErrorCode :: ierr

  grid => patch%grid
  
  value = -999.99d0

  ! inactive grid cell
  if (patch%imat(ghosted_id) <= 0) then
    PatchGetDatasetValueAtCell = 0.d0
    return
  endif

  iphase = 1
  xmass = 1.d0
  if (associated(patch%aux%Global%aux_vars(ghosted_id)%xmass)) &
    xmass = patch%aux%Global%aux_vars(ghosted_id)%xmass(iphase)
             
  select case(ivar)
    case(TEMPERATURE,LIQUID_PRESSURE,GAS_PRESSURE, &
         LIQUID_SATURATION,GAS_SATURATION,ICE_SATURATION, &
         LIQUID_MOLE_FRACTION,GAS_MOLE_FRACTION,LIQUID_ENERGY,GAS_ENERGY, &
         LIQUID_DENSITY,GAS_DENSITY,GAS_DENSITY_MOL,LIQUID_VISCOSITY,GAS_VISCOSITY, &
         LIQUID_MOBILITY,GAS_MOBILITY,SC_FUGA_COEFF,STATE,ICE_DENSITY, &
         SECONDARY_TEMPERATURE)
         
      if (associated(patch%aux%THC)) then
        select case(ivar)
          case(TEMPERATURE)
            value = patch%aux%Global%aux_vars(ghosted_id)%temp(1)
          case(LIQUID_PRESSURE)
            value = patch%aux%Global%aux_vars(ghosted_id)%pres(1)
          case(LIQUID_SATURATION)
            value = patch%aux%Global%aux_vars(ghosted_id)%sat(1)
          case(LIQUID_DENSITY)
            value = patch%aux%Global%aux_vars(ghosted_id)%den_kg(1)
          case(LIQUID_VISCOSITY)
            value = patch%aux%THC%aux_vars(ghosted_id)%vis
          case(LIQUID_MOBILITY)
            value = patch%aux%THC%aux_vars(ghosted_id)%kvr
          case(GAS_MOLE_FRACTION,GAS_ENERGY,GAS_DENSITY) ! still need implementation
            value = 0.d0
          case(GAS_SATURATION)
#ifdef ICE
            value = patch%aux%THC%aux_vars(ghosted_id)%sat_gas
#else
            value = 0.d0
#endif
#ifdef ICE
          case(ICE_SATURATION)
            value = patch%aux%THC%aux_vars(ghosted_id)%sat_ice
          case(ICE_DENSITY)
            value = patch%aux%THC%aux_vars(ghosted_id)%den_ice*FMWH2O
#endif
          case(LIQUID_MOLE_FRACTION)
            value = patch%aux%THC%aux_vars(ghosted_id)%xmol(isubvar)
          case(LIQUID_ENERGY)
            value = patch%aux%THC%aux_vars(ghosted_id)%u
          case(SECONDARY_TEMPERATURE)
            value = patch%aux%SC_heat%sec_heat_vars(ghosted_id)%sec_temp(isubvar)
        end select
     else if (associated(patch%aux%TH)) then
        select case(ivar)
          case(TEMPERATURE)
            value = patch%aux%Global%aux_vars(ghosted_id)%temp(1)
          case(LIQUID_PRESSURE)
            value = patch%aux%Global%aux_vars(ghosted_id)%pres(1)
          case(LIQUID_SATURATION)
            value = patch%aux%Global%aux_vars(ghosted_id)%sat(1)
          case(LIQUID_DENSITY)
            value = patch%aux%Global%aux_vars(ghosted_id)%den_kg(1)
          case(LIQUID_VISCOSITY)
            value = patch%aux%TH%aux_vars(ghosted_id)%vis
          case(LIQUID_MOBILITY)
            value = patch%aux%TH%aux_vars(ghosted_id)%kvr
          case(GAS_MOLE_FRACTION,GAS_ENERGY,GAS_DENSITY) ! still need implementation
            value = 0.d0
          case(GAS_SATURATION)
#ifdef ICE
            value = patch%aux%TH%aux_vars(ghosted_id)%sat_gas
#else
            value = 0.d0
#endif
#ifdef ICE
          case(ICE_SATURATION)
            value = patch%aux%TH%aux_vars(ghosted_id)%sat_ice
          case(ICE_DENSITY)
            value = patch%aux%TH%aux_vars(ghosted_id)%den_ice*FMWH2O
#endif
          case(LIQUID_MOLE_FRACTION)
            value = patch%aux%TH%aux_vars(ghosted_id)%xmol(isubvar)
          case(LIQUID_ENERGY)
            value = patch%aux%TH%aux_vars(ghosted_id)%u
          case(SECONDARY_TEMPERATURE)
            value = patch%aux%SC_heat%sec_heat_vars(ghosted_id)%sec_temp(isubvar)
        end select
     else if (associated(patch%aux%THMC)) then
        select case(ivar)
          case(TEMPERATURE)
            value = patch%aux%Global%aux_vars(ghosted_id)%temp(1)
          case(LIQUID_PRESSURE)
            value = patch%aux%Global%aux_vars(ghosted_id)%pres(1)
          case(LIQUID_SATURATION)
            value = patch%aux%Global%aux_vars(ghosted_id)%sat(1)
          case(LIQUID_DENSITY)
            value = patch%aux%Global%aux_vars(ghosted_id)%den_kg(1)
          case(LIQUID_VISCOSITY)
            value = patch%aux%THMC%aux_vars(ghosted_id)%vis
          case(LIQUID_MOBILITY)
            value = patch%aux%THMC%aux_vars(ghosted_id)%kvr
          case(GAS_MOLE_FRACTION,GAS_ENERGY,GAS_DENSITY) ! still need implementation
            value = 0.d0
          case(GAS_SATURATION)
#ifdef ICE
            value = patch%aux%THMC%aux_vars(ghosted_id)%sat_gas
#else
            value = 0.d0
#endif
#ifdef ICE
          case(ICE_SATURATION)
            value = patch%aux%THMC%aux_vars(ghosted_id)%sat_ice
          case(ICE_DENSITY)
            value = patch%aux%THMC%aux_vars(ghosted_id)%den_ice*FMWH2O
#endif
          case(LIQUID_MOLE_FRACTION)
            value = patch%aux%THMC%aux_vars(ghosted_id)%xmol(isubvar)
          case(LIQUID_ENERGY)
            value = patch%aux%THMC%aux_vars(ghosted_id)%u
        end select
      else if (associated(patch%aux%Richards)) then
        select case(ivar)
          case(TEMPERATURE)
            call printErrMsg(option,'TEMPERATURE not supported by Richards')
          case(GAS_SATURATION)
            call printErrMsg(option,'GAS_SATURATION not supported by Richards')
          case(GAS_DENSITY)
            call printErrMsg(option,'GAS_DENSITY not supported by Richards')
          case(LIQUID_MOLE_FRACTION)
            call printErrMsg(option,'LIQUID_MOLE_FRACTION not supported by Richards')
          case(GAS_MOLE_FRACTION)
            call printErrMsg(option,'GAS_MOLE_FRACTION not supported by Richards')
          case(LIQUID_ENERGY)
            call printErrMsg(option,'LIQUID_ENERGY not supported by Richards')
          case(GAS_ENERGY)
            call printErrMsg(option,'GAS_ENERGY not supported by Richards')
          case(LIQUID_PRESSURE)
            value = patch%aux%Global%aux_vars(ghosted_id)%pres(1)
          case(LIQUID_SATURATION)
            value = patch%aux%Global%aux_vars(ghosted_id)%sat(1)
          case(LIQUID_DENSITY)
            value = patch%aux%Global%aux_vars(ghosted_id)%den_kg(1)
        end select
      else if (associated(patch%aux%Flash2)) then
        select case(ivar)
          case(TEMPERATURE)
            value = patch%aux%Global%aux_vars(ghosted_id)%temp(1)
          case(LIQUID_PRESSURE)
            value = patch%aux%Global%aux_vars(ghosted_id)%pres(2)
          case(LIQUID_SATURATION)
            value = patch%aux%Global%aux_vars(ghosted_id)%sat(1)
          case(LIQUID_DENSITY)
            value = patch%aux%Global%aux_vars(ghosted_id)%den_kg(1)
          case(LIQUID_VISCOSITY)
            value = patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%vis(1)
          case(LIQUID_MOBILITY)
            value = patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%kvr(1)
          case(GAS_SATURATION)
            value = patch%aux%Global%aux_vars(ghosted_id)%sat(2)
          case(GAS_MOLE_FRACTION)
            value = patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%xmol(2+isubvar)
          case(GAS_ENERGY)
            value = patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%u(2)
          case(GAS_DENSITY) 
            value = patch%aux%Global%aux_vars(ghosted_id)%den_kg(2)
          case(GAS_DENSITY_MOL) 
            value = patch%aux%Global%aux_vars(ghosted_id)%den(2)
          case(GAS_VISCOSITY) 
            value = patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%vis(2)
          case(GAS_MOBILITY) 
            value = patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%kvr(2)
          case(SC_FUGA_COEFF)
            value = patch%aux%Global%aux_vars(ghosted_id)%fugacoeff(1)   
          case(LIQUID_MOLE_FRACTION)
            value = patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%xmol(isubvar)
          case(LIQUID_ENERGY)
            value = patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%u(1)
        end select
      else if (associated(patch%aux%Mphase)) then
        select case(ivar)
          case(TEMPERATURE)
            value = patch%aux%Global%aux_vars(ghosted_id)%temp(1)
          case(LIQUID_PRESSURE)
            value = patch%aux%Global%aux_vars(ghosted_id)%pres(1)
          case(GAS_PRESSURE)
            value = patch%aux%Global%aux_vars(ghosted_id)%pres(2)
          case(LIQUID_SATURATION)
            value = patch%aux%Global%aux_vars(ghosted_id)%sat(1)
          case(LIQUID_MOLE_FRACTION)
            value = patch%aux%Mphase%aux_vars(ghosted_id)%aux_var_elem(0)%xmol(isubvar)
          case(LIQUID_ENERGY)
            value = patch%aux%Mphase%aux_vars(ghosted_id)%aux_var_elem(0)%u(1)
          case(LIQUID_DENSITY)
            value = patch%aux%Global%aux_vars(ghosted_id)%den_kg(1)
          case(LIQUID_VISCOSITY)
            value = patch%aux%Mphase%aux_vars(ghosted_id)%aux_var_elem(0)%vis(1)
          case(LIQUID_MOBILITY)
            value = patch%aux%Mphase%aux_vars(ghosted_id)%aux_var_elem(0)%kvr(1)
          case(GAS_SATURATION)
            value = patch%aux%Global%aux_vars(ghosted_id)%sat(2)
          case(GAS_MOLE_FRACTION)
            value = patch%aux%Mphase%aux_vars(ghosted_id)%aux_var_elem(0)%xmol(2+isubvar)
          case(GAS_ENERGY)
            value = patch%aux%Mphase%aux_vars(ghosted_id)%aux_var_elem(0)%u(2)
          case(GAS_DENSITY) 
            value = patch%aux%Global%aux_vars(ghosted_id)%den_kg(2)
          case(GAS_VISCOSITY) 
            value = patch%aux%Mphase%aux_vars(ghosted_id)%aux_var_elem(0)%vis(2)
          case(GAS_MOBILITY) 
            value = patch%aux%Mphase%aux_vars(ghosted_id)%aux_var_elem(0)%kvr(2)
          case(GAS_DENSITY_MOL) 
            value = patch%aux%Global%aux_vars(ghosted_id)%den(2)
          case(SC_FUGA_COEFF)
            value = patch%aux%Global%aux_vars(ghosted_id)%fugacoeff(1)   
          case(SECONDARY_TEMPERATURE)
            value = patch%aux%SC_heat%sec_heat_vars(ghosted_id)%sec_temp(isubvar)
        end select
      else if (associated(patch%aux%Immis)) then
        select case(ivar)
          case(TEMPERATURE)
            value = patch%aux%Global%aux_vars(ghosted_id)%temp(1)
          case(LIQUID_PRESSURE)
            value = patch%aux%Global%aux_vars(ghosted_id)%pres(2)
          case(LIQUID_SATURATION)
            value = patch%aux%Global%aux_vars(ghosted_id)%sat(1)
          case(LIQUID_DENSITY)
            value = patch%aux%Global%aux_vars(ghosted_id)%den_kg(1)
          case(LIQUID_ENERGY)
            value = patch%aux%Immis%aux_vars(ghosted_id)%aux_var_elem(0)%u(1)
          case(LIQUID_VISCOSITY)
            value = patch%aux%Immis%aux_vars(ghosted_id)%aux_var_elem(0)%vis(1)
          case(LIQUID_MOBILITY)
            value = patch%aux%Immis%aux_vars(ghosted_id)%aux_var_elem(0)%kvr(1)
          case(GAS_SATURATION)
            value = patch%aux%Global%aux_vars(ghosted_id)%sat(2)
          case(GAS_ENERGY)
            value = patch%aux%Immis%aux_vars(ghosted_id)%aux_var_elem(0)%u(2)
          case(GAS_DENSITY) 
            value = patch%aux%Global%aux_vars(ghosted_id)%den_kg(2)
          case(GAS_DENSITY_MOL) 
            value = patch%aux%Global%aux_vars(ghosted_id)%den(2)
          case(GAS_VISCOSITY)
            value = patch%aux%Immis%aux_vars(ghosted_id)%aux_var_elem(0)%vis(2)
          case(GAS_MOBILITY)
            value = patch%aux%Immis%aux_vars(ghosted_id)%aux_var_elem(0)%kvr(2)
        end select
      else if (associated(patch%aux%Miscible)) then
        select case(ivar)
!         case(TEMPERATURE)
!           value = patch%aux%Global%aux_vars(ghosted_id)%temp(1)
          case(LIQUID_PRESSURE)
            value = patch%aux%Global%aux_vars(ghosted_id)%pres(1)
!         case(LIQUID_SATURATION)
!           value = patch%aux%Global%aux_vars(ghosted_id)%sat(1)
          case(LIQUID_DENSITY)
            value = patch%aux%Global%aux_vars(ghosted_id)%den_kg(1)
!         case(LIQUID_ENERGY)
!           value = patch%aux%Miscible%aux_vars(ghosted_id)%aux_var_elem(0)%u(1)
          case(LIQUID_VISCOSITY)
            value = patch%aux%Miscible%aux_vars(ghosted_id)%aux_var_elem(0)%vis(1)
!         case(LIQUID_MOBILITY)
!           value = patch%aux%Miscible%aux_vars(ghosted_id)%aux_var_elem(0)%kvr(1)
          case(LIQUID_MOLE_FRACTION)
            value = patch%aux%Miscible%aux_vars(ghosted_id)%aux_var_elem(0)%xmol(isubvar)
        end select
      else if (associated(patch%aux%General)) then
        select case(ivar)
          case(TEMPERATURE)
            value = patch%aux%General%aux_vars(ZERO_INTEGER,ghosted_id)%temp
          case(LIQUID_PRESSURE)
            value = patch%aux%General%aux_vars(ZERO_INTEGER,ghosted_id)%pres(option%liquid_phase)
          case(GAS_PRESSURE)
            value = patch%aux%General%aux_vars(ZERO_INTEGER,ghosted_id)%pres(option%gas_phase)
          case(STATE)
            value = patch%aux%Global%aux_vars(ghosted_id)%istate
          case(LIQUID_SATURATION)
            value = patch%aux%General%aux_vars(ZERO_INTEGER,ghosted_id)%sat(option%liquid_phase)
          case(LIQUID_DENSITY)
            value = patch%aux%General%aux_vars(ZERO_INTEGER,ghosted_id)%den_kg(option%liquid_phase)
          case(LIQUID_ENERGY)
            value = patch%aux%General%aux_vars(ZERO_INTEGER,ghosted_id)%U(option%liquid_phase)
          case(LIQUID_MOLE_FRACTION)
            value = patch%aux%General%aux_vars(ZERO_INTEGER,ghosted_id)%xmol(isubvar,option%liquid_phase)
          case(GAS_SATURATION)
            value = patch%aux%General%aux_vars(ZERO_INTEGER,ghosted_id)%sat(option%gas_phase)
          case(GAS_DENSITY) 
            value = patch%aux%General%aux_vars(ZERO_INTEGER,ghosted_id)%den_kg(option%gas_phase)
          case(GAS_ENERGY)
            value = patch%aux%General%aux_vars(ZERO_INTEGER,ghosted_id)%U(option%gas_phase)
          case(GAS_MOLE_FRACTION)
            value = patch%aux%General%aux_vars(ZERO_INTEGER,ghosted_id)%xmol(isubvar,option%gas_phase)
        end select        
      endif
      
    case(PH,PRIMARY_MOLALITY,PRIMARY_MOLARITY,SECONDARY_MOLALITY,SECONDARY_MOLARITY, &
         TOTAL_MOLALITY,TOTAL_MOLARITY, &
         MINERAL_VOLUME_FRACTION,MINERAL_RATE,MINERAL_SATURATION_INDEX, &
         SURFACE_CMPLX,SURFACE_CMPLX_FREE,SURFACE_SITE_DENSITY, &
         KIN_SURFACE_CMPLX,KIN_SURFACE_CMPLX_FREE, &
         PRIMARY_ACTIVITY_COEF,SECONDARY_ACTIVITY_COEF,PRIMARY_KD,TOTAL_SORBED, &
         TOTAL_SORBED_MOBILE,COLLOID_MOBILE,COLLOID_IMMOBILE,AGE,TOTAL_BULK, &
         IMMOBILE_SPECIES)
         
      select case(ivar)
        case(PH)
          value = -log10(patch%aux%RT%aux_vars(ghosted_id)% &
                         pri_act_coef(isubvar)* &
                         patch%aux%RT%aux_vars(ghosted_id)%pri_molal(isubvar))
        case(PRIMARY_MOLALITY)
          value = patch%aux%RT%aux_vars(ghosted_id)%pri_molal(isubvar)
        case(PRIMARY_MOLARITY)
          value = patch%aux%RT%aux_vars(ghosted_id)%pri_molal(isubvar) * xmass * &
                  patch%aux%Global%aux_vars(ghosted_id)%den_kg(iphase) / 1000.d0
        case(SECONDARY_MOLALITY)
          value = patch%aux%RT%aux_vars(ghosted_id)%sec_molal(isubvar)
        case(SECONDARY_MOLARITY)
          value = patch%aux%RT%aux_vars(ghosted_id)%sec_molal(isubvar) * xmass * &
                  patch%aux%Global%aux_vars(ghosted_id)%den_kg(iphase) / 1000.d0
        case(TOTAL_MOLALITY)
          value = patch%aux%RT%aux_vars(ghosted_id)%total(isubvar,iphase) / xmass / &
                  patch%aux%Global%aux_vars(ghosted_id)%den_kg(iphase)*1000.d0
        case(TOTAL_MOLARITY)
          value = patch%aux%RT%aux_vars(ghosted_id)%total(isubvar,iphase)
        case(TOTAL_BULK) ! mol/m^3 bulk
          ! add in total molarity and convert to mol/m^3 bulk
          call GridVecGetArrayF90(grid,field%porosity_loc,vec_ptr2,ierr)
          value = &
              patch%aux%RT%aux_vars(ghosted_id)%total(isubvar,iphase) * &
              vec_ptr2(ghosted_id) * &
              patch%aux%Global%aux_vars(ghosted_id)%sat(iphase) * 1.d-3 ! mol/L -> mol/m^3
          call GridVecRestoreArrayF90(grid,field%porosity_loc,vec_ptr2,ierr)
          ! add in total sorbed.  already in mol/m^3 bulk
          if (patch%reaction%nsorb > 0) then
            if (patch%reaction%surface_complexation%neqsrfcplxrxn > 0) then
              value = value + &
                patch%aux%RT%aux_vars(ghosted_id)%total_sorb_eq(isubvar)
            endif
            if (patch%reaction%surface_complexation%nkinmrsrfcplxrxn > 0) then
              do irxn = 1, patch%reaction%surface_complexation%nkinmrsrfcplxrxn
                do irate = 1, &
                  patch%reaction%surface_complexation%kinmr_nrate(irxn)
                  value = value + &
                      patch%aux%RT%aux_vars(ghosted_id)% &
                        kinmr_total_sorb(isubvar,irate,irxn)
                enddo
              enddo            
            endif
          endif          
        case(MINERAL_VOLUME_FRACTION)
          value = patch%aux%RT%aux_vars(ghosted_id)%mnrl_volfrac(isubvar)
        case(MINERAL_RATE)
          value = patch%aux%RT%aux_vars(ghosted_id)%mnrl_rate(isubvar)
        case(MINERAL_SATURATION_INDEX)
          value = RMineralSaturationIndex(isubvar,patch%aux%RT%aux_vars(ghosted_id), &
                                          patch%aux%Global%aux_vars(ghosted_id), &
                                          reaction,option)
        case(IMMOBILE_SPECIES)
          value = patch%aux%RT%aux_vars(ghosted_id)%immobile(isubvar)
        case(SURFACE_CMPLX)
          if (associated(patch%aux%RT%aux_vars(ghosted_id)%eqsrfcplx_conc)) then
            value = patch%aux%RT%aux_vars(ghosted_id)%eqsrfcplx_conc(isubvar)
          else
            value = -999.d0
          endif
        case(SURFACE_CMPLX_FREE)
          value = patch%aux%RT%aux_vars(ghosted_id)%srfcplxrxn_free_site_conc(isubvar)
        case(SURFACE_SITE_DENSITY)
          select case(reaction%surface_complexation%srfcplxrxn_surf_type(isubvar))
            case(MINERAL_SURFACE)
              value = reaction%surface_complexation%srfcplxrxn_site_density(isubvar)* &
                      patch%aux%RT%aux_vars(ghosted_id)% &
                        mnrl_volfrac(reaction%surface_complexation%srfcplxrxn_to_surf(isubvar))
            case(COLLOID_SURFACE)
                option%io_buffer = 'Printing of surface site density for colloidal surfaces ' // &
                  'not implemented.'
                call printErrMsg(option)
            case(NULL_SURFACE)
              value = reaction%surface_complexation%srfcplxrxn_site_density(isubvar)
          end select
        case(KIN_SURFACE_CMPLX)
          value = patch%aux%RT%aux_vars(ghosted_id)%kinsrfcplx_conc(isubvar,1)
        case(KIN_SURFACE_CMPLX_FREE)
          value = patch%aux%RT%aux_vars(ghosted_id)%kinsrfcplx_free_site_conc(isubvar)
        case(PRIMARY_ACTIVITY_COEF)
          value = patch%aux%RT%aux_vars(ghosted_id)%pri_act_coef(isubvar)
        case(SECONDARY_ACTIVITY_COEF)
          value = patch%aux%RT%aux_vars(ghosted_id)%sec_act_coef(isubvar)
        case(PRIMARY_KD)
          call GridVecGetArrayF90(grid,field%porosity_loc,vec_ptr2,ierr)
          call ReactionComputeKd(isubvar,value, &
                                 patch%aux%RT%aux_vars(ghosted_id), &
                                 patch%aux%Global%aux_vars(ghosted_id), &
                                 vec_ptr2(ghosted_id),patch%reaction,option)
          call GridVecRestoreArrayF90(grid,field%porosity_loc,vec_ptr2,ierr)
        case(TOTAL_SORBED)
          if (patch%reaction%nsorb > 0) then
            if (patch%reaction%neqsorb > 0) then
              value = patch%aux%RT%aux_vars(ghosted_id)%total_sorb_eq(isubvar)
            endif
            if (patch%reaction%surface_complexation%nkinmrsrfcplxrxn > 0) then
              value = 0.d0
              do irxn = 1, patch%reaction%surface_complexation%nkinmrsrfcplxrxn
                do irate = 1, &
                  patch%reaction%surface_complexation%kinmr_nrate(irxn)
                  value = value + &
                    patch%aux%RT%aux_vars(ghosted_id)% &
                      kinmr_total_sorb(isubvar,irate,irxn)
                enddo
              enddo            
            endif
          endif          
        case(TOTAL_SORBED_MOBILE)
          if (patch%reaction%nsorb > 0 .and. patch%reaction%ncollcomp > 0) then
            value = &
              patch%aux%RT%aux_vars(ghosted_id)%colloid%total_eq_mob(isubvar)
          endif
        case(COLLOID_MOBILE)
          if (patch%reaction%print_tot_conc_type == TOTAL_MOLALITY) then
            value = patch%aux%RT%aux_vars(ghosted_id)%colloid%conc_mob(isubvar) / &
                    patch%aux%Global%aux_vars(ghosted_id)%den_kg(iphase)*1000.d0
          else
            value = patch%aux%RT%aux_vars(ghosted_id)%colloid%conc_mob(isubvar)
          endif
        case(COLLOID_IMMOBILE)
          if (patch%reaction%print_tot_conc_type == TOTAL_MOLALITY) then
            value = patch%aux%RT%aux_vars(ghosted_id)%colloid%conc_imb(isubvar) / &
                    patch%aux%Global%aux_vars(ghosted_id)%den_kg(iphase)*1000.d0
          else
            value = patch%aux%RT%aux_vars(ghosted_id)%colloid%conc_imb(isubvar)
          endif
        case(AGE)
          if (patch%aux%RT%aux_vars(ghosted_id)%pri_molal(isubvar) > &
              0.d0) then
            value = patch%aux%RT%aux_vars(ghosted_id)%pri_molal(isubvar) / &
            patch%aux%RT%aux_vars(ghosted_id)%pri_molal(isubvar1) / &
            output_option%tconv
          endif
      end select
    case(POROSITY)
      call GridVecGetArrayF90(grid,field%porosity_loc,vec_ptr2,ierr)
      value = vec_ptr2(ghosted_id)
      call GridVecRestoreArrayF90(grid,field%porosity_loc,vec_ptr2,ierr)
    case(PERMEABILITY,PERMEABILITY_X)
      call GridVecGetArrayF90(grid,field%perm_xx_loc,vec_ptr2,ierr)
      value = vec_ptr2(ghosted_id)
      call GridVecRestoreArrayF90(grid,field%perm_xx_loc,vec_ptr2,ierr)
    case(PERMEABILITY_Y)
      call GridVecGetArrayF90(grid,field%perm_yy_loc,vec_ptr2,ierr)
      value = vec_ptr2(ghosted_id)
      call GridVecRestoreArrayF90(grid,field%perm_yy_loc,vec_ptr2,ierr)
    case(PERMEABILITY_Z)
      call GridVecGetArrayF90(grid,field%perm_zz_loc,vec_ptr2,ierr)
      value = vec_ptr2(ghosted_id)
      call GridVecRestoreArrayF90(grid,field%perm_zz_loc,vec_ptr2,ierr)
    case(PHASE)
      call GridVecGetArrayF90(grid,field%iphas_loc,vec_ptr2,ierr)
      value = vec_ptr2(ghosted_id)
      call GridVecRestoreArrayF90(grid,field%iphas_loc,vec_ptr2,ierr)
    case(MATERIAL_ID)
      value = patch%imat(ghosted_id)
    case(PROCESSOR_ID)
      value = option%myrank
    ! Need to fix the below two cases (they assume only one component) -- SK 02/06/13  
    case(SECONDARY_CONCENTRATION)
      ! Note that the units are in mol/kg
      value = patch%aux%SC_RT%sec_transport_vars(ghosted_id)% &
              sec_rt_auxvar(isubvar)%pri_molal(isubvar1)
    case(SEC_MIN_VOLFRAC)
      value = patch%aux%SC_RT%sec_transport_vars(ghosted_id)% &
              sec_rt_auxvar(isubvar)%mnrl_volfrac(isubvar1)
     case default
      write(option%io_buffer, &
            '(''IVAR ('',i3,'') not found in PatchGetDatasetValueAtCell'')') &
            ivar
      call printErrMsg(option)
  end select

  PatchGetDatasetValueAtCell = value
 
end function PatchGetDatasetValueAtCell

! ************************************************************************** !
!
! PatchSetDataset: Sets variables indexed by ivar and isubvar within a patch
! author: Glenn Hammond
! date: 09/12/08
!
! ************************************************************************** !
subroutine PatchSetDataset(patch,field,option,vec,vec_format,ivar,isubvar)

  use Grid_module
  use Option_module
  use Field_module
  use Variables_module
  use General_Aux_module  

  implicit none

#include "finclude/petscvec.h"
#include "finclude/petscvec.h90"

  type(option_type), pointer :: option
  type(field_type), pointer :: field
  type(patch_type), pointer :: patch  
  Vec :: vec
  PetscInt :: vec_format
  PetscInt :: ivar
  PetscInt :: isubvar
  PetscInt :: iphase, istate

  PetscInt :: local_id, ghosted_id
  type(grid_type), pointer :: grid
  PetscReal, pointer :: vec_ptr(:), vec_ptr2(:)
  PetscErrorCode :: ierr

  grid => patch%grid

  call GridVecGetArrayF90(grid,vec,vec_ptr,ierr)

  if (vec_format == NATURAL) then
    call printErrMsg(option,&
                     'NATURAL vector format not supported by PatchSetDataset')
  endif

  iphase = 1
  select case(ivar)
    case(TEMPERATURE,LIQUID_PRESSURE,GAS_PRESSURE,LIQUID_SATURATION,GAS_SATURATION, &
         LIQUID_MOLE_FRACTION,GAS_MOLE_FRACTION,LIQUID_ENERGY,GAS_ENERGY, &
         LIQUID_DENSITY,GAS_DENSITY,GAS_DENSITY_MOL,LIQUID_VISCOSITY,GAS_VISCOSITY, &
         LIQUID_MOBILITY,GAS_MOBILITY,STATE)
      if (associated(patch%aux%THC)) then
        select case(ivar)
          case(TEMPERATURE)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%temp = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Global%aux_vars(ghosted_id)%temp = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_PRESSURE)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%pres = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Global%aux_vars(ghosted_id)%pres = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_SATURATION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%sat = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Global%aux_vars(ghosted_id)%sat = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_DENSITY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%den_kg = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Global%aux_vars(ghosted_id)%den_kg = vec_ptr(ghosted_id)
              enddo
            endif
          case(GAS_MOLE_FRACTION,GAS_ENERGY,GAS_DENSITY) ! still need implementation
          case(GAS_SATURATION)
#ifdef ICE
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%THC%aux_vars(grid%nL2G(local_id))%sat_gas = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%THC%aux_vars(ghosted_id)%sat_gas = vec_ptr(ghosted_id)
              enddo
            endif
#else
#endif
#ifdef ICE
          case(ICE_SATURATION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%THC%aux_vars(grid%nL2G(local_id))%sat_ice = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%THC%aux_vars(ghosted_id)%sat_ice = vec_ptr(ghosted_id)
              enddo
            endif
          case(ICE_DENSITY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%THC%aux_vars(grid%nL2G(local_id))%den_ice = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%THC%aux_vars(ghosted_id)%den_ice = vec_ptr(ghosted_id)
              enddo
            endif
#endif
          case(LIQUID_VISCOSITY)
          case(GAS_VISCOSITY)
          case(LIQUID_MOLE_FRACTION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%THC%aux_vars(grid%nL2G(local_id))%xmol(isubvar) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%THC%aux_vars(ghosted_id)%xmol(isubvar) = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_ENERGY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%THC%aux_vars(grid%nL2G(local_id))%u = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%THC%aux_vars(ghosted_id)%u = vec_ptr(ghosted_id)
              enddo
            endif
        end select
      else if (associated(patch%aux%TH)) then
        select case(ivar)
          case(TEMPERATURE)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%temp = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Global%aux_vars(ghosted_id)%temp = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_PRESSURE)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%pres = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Global%aux_vars(ghosted_id)%pres = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_SATURATION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%sat = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Global%aux_vars(ghosted_id)%sat = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_DENSITY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%den_kg = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Global%aux_vars(ghosted_id)%den_kg = vec_ptr(ghosted_id)
              enddo
            endif
          case(GAS_MOLE_FRACTION,GAS_ENERGY,GAS_DENSITY) ! still need implementation
          case(GAS_SATURATION)
#ifdef ICE
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%TH%aux_vars(grid%nL2G(local_id))%sat_gas = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%TH%aux_vars(ghosted_id)%sat_gas = vec_ptr(ghosted_id)
              enddo
            endif
#else
#endif
#ifdef ICE
          case(ICE_SATURATION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%TH%aux_vars(grid%nL2G(local_id))%sat_ice = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%TH%aux_vars(ghosted_id)%sat_ice = vec_ptr(ghosted_id)
              enddo
            endif
          case(ICE_DENSITY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%TH%aux_vars(grid%nL2G(local_id))%den_ice = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%TH%aux_vars(ghosted_id)%den_ice = vec_ptr(ghosted_id)
              enddo
            endif
#endif
          case(LIQUID_VISCOSITY)
          case(GAS_VISCOSITY)
          case(LIQUID_MOLE_FRACTION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%TH%aux_vars(grid%nL2G(local_id))%xmol(isubvar) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%TH%aux_vars(ghosted_id)%xmol(isubvar) = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_ENERGY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%TH%aux_vars(grid%nL2G(local_id))%u = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%TH%aux_vars(ghosted_id)%u = vec_ptr(ghosted_id)
              enddo
            endif
        end select
      else if (associated(patch%aux%THMC)) then
        select case(ivar)
          case(TEMPERATURE)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%temp = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Global%aux_vars(ghosted_id)%temp = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_PRESSURE)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%pres = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Global%aux_vars(ghosted_id)%pres = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_SATURATION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%sat = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Global%aux_vars(ghosted_id)%sat = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_DENSITY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%den_kg = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Global%aux_vars(ghosted_id)%den_kg = vec_ptr(ghosted_id)
              enddo
            endif
          case(GAS_MOLE_FRACTION,GAS_ENERGY,GAS_DENSITY) ! still need implementation
          case(GAS_SATURATION)
#ifdef ICE
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%THMC%aux_vars(grid%nL2G(local_id))%sat_gas = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%THMC%aux_vars(ghosted_id)%sat_gas = vec_ptr(ghosted_id)
              enddo
            endif
#else
#endif
#ifdef ICE
          case(ICE_SATURATION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%THMC%aux_vars(grid%nL2G(local_id))%sat_ice = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%THMC%aux_vars(ghosted_id)%sat_ice = vec_ptr(ghosted_id)
              enddo
            endif
          case(ICE_DENSITY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%THMC%aux_vars(grid%nL2G(local_id))%den_ice = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%THMC%aux_vars(ghosted_id)%den_ice = vec_ptr(ghosted_id)
              enddo
            endif
#endif
          case(LIQUID_VISCOSITY)
          case(GAS_VISCOSITY)
          case(LIQUID_MOLE_FRACTION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%THMC%aux_vars(grid%nL2G(local_id))%xmol(isubvar) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%THMC%aux_vars(ghosted_id)%xmol(isubvar) = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_ENERGY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%THMC%aux_vars(grid%nL2G(local_id))%u = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%THMC%aux_vars(ghosted_id)%u = vec_ptr(ghosted_id)
              enddo
            endif
        end select
      else if (associated(patch%aux%Richards)) then
        select case(ivar)
          case(TEMPERATURE)
            call printErrMsg(option,'TEMPERATURE not supported by Richards')
          case(GAS_SATURATION)
            call printErrMsg(option,'GAS_SATURATION not supported by Richards')
          case(GAS_DENSITY)
            call printErrMsg(option,'GAS_DENSITY not supported by Richards')
          case(LIQUID_MOLE_FRACTION)
            call printErrMsg(option,'LIQUID_MOLE_FRACTION not supported by Richards')
          case(GAS_MOLE_FRACTION)
            call printErrMsg(option,'GAS_MOLE_FRACTION not supported by Richards')
          case(LIQUID_VISCOSITY)
            call printErrMsg(option,'LIQUID_VISCOSITY not supported by Richards')
          case(GAS_VISCOSITY)
            call printErrMsg(option,'GAS_VISCOSITY not supported by Richards')
          case(LIQUID_MOBILITY)
            call printErrMsg(option,'LIQUID_MOBILITY not supported by Richards')
          case(GAS_MOBILITY)
            call printErrMsg(option,'GAS_MOBILITY not supported by Richards')
          case(LIQUID_ENERGY)
            call printErrMsg(option,'LIQUID_ENERGY not supported by Richards')
          case(GAS_ENERGY)
            call printErrMsg(option,'GAS_ENERGY not supported by Richards')
          case(LIQUID_PRESSURE)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%pres(1) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Global%aux_vars(ghosted_id)%pres(1) = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_SATURATION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%sat(1) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Global%aux_vars(ghosted_id)%sat(1) = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_DENSITY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%den_kg(1) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Global%aux_vars(ghosted_id)%den_kg(1) = vec_ptr(ghosted_id)
              enddo
            endif
        end select
      else if (associated(patch%aux%Flash2)) then
        select case(ivar)
          case(TEMPERATURE)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%temp = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%temp = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_PRESSURE)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%pres = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%pres = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_SATURATION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%sat(1) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%sat(1) = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_DENSITY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%den(1) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%den(1) = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_VISCOSITY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%vis(1) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%vis(1) = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_MOBILITY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%kvr(1) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%kvr(1) = vec_ptr(ghosted_id)
              enddo
            endif
          case(GAS_SATURATION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%sat(2) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%sat(2) = vec_ptr(ghosted_id)
              enddo
            endif
          case(GAS_MOLE_FRACTION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%xmol(2+isubvar) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%xmol(2+isubvar) = vec_ptr(ghosted_id)
              enddo
            endif
          case(GAS_ENERGY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%u(2) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%u(2) = vec_ptr(ghosted_id)
              enddo
            endif
          case(GAS_DENSITY, GAS_DENSITY_MOL) 
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%den(2) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%den(2) = vec_ptr(ghosted_id)
              enddo
            endif
          case(GAS_VISCOSITY) 
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%vis(2) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%vis(2) = vec_ptr(ghosted_id)
              enddo
            endif
          case(GAS_MOBILITY) 
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%kvr(2) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%kvr(2) = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_MOLE_FRACTION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%xmol(isubvar) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%xmol(isubvar) = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_ENERGY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Flash2%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%u(1) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Flash2%aux_vars(ghosted_id)%aux_var_elem(0)%u(1) = vec_ptr(ghosted_id)
              enddo
            endif
        end select
      else if (associated(patch%aux%Mphase)) then
        select case(ivar)
          case(TEMPERATURE)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Mphase%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%temp = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Mphase%aux_vars(ghosted_id)%aux_var_elem(0)%temp = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_PRESSURE)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%pres(1) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Global%aux_vars(grid%nL2G(ghosted_id))%pres(1) = vec_ptr(ghosted_id)
              enddo
            endif
          case(GAS_PRESSURE)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Global%aux_vars(grid%nL2G(local_id))%pres(2) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Global%aux_vars(grid%nL2G(ghosted_id))%pres(2) = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_SATURATION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Mphase%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%sat(1) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Mphase%aux_vars(ghosted_id)%aux_var_elem(0)%sat(1) = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_DENSITY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Mphase%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%den(1) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Mphase%aux_vars(ghosted_id)%aux_var_elem(0)%den(1) = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_VISCOSITY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Mphase%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%vis(1) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Mphase%aux_vars(ghosted_id)%aux_var_elem(0)%vis(1) = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_MOBILITY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Mphase%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%kvr(1) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Mphase%aux_vars(ghosted_id)%aux_var_elem(0)%kvr(1) = vec_ptr(ghosted_id)
              enddo
            endif
          case(GAS_SATURATION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Mphase%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%sat(2) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Mphase%aux_vars(ghosted_id)%aux_var_elem(0)%sat(2) = vec_ptr(ghosted_id)
              enddo
            endif
          case(GAS_MOLE_FRACTION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Mphase%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%xmol(2+isubvar) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Mphase%aux_vars(ghosted_id)%aux_var_elem(0)%xmol(2+isubvar) = vec_ptr(ghosted_id)
              enddo
            endif
          case(GAS_ENERGY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Mphase%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%u(2) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Mphase%aux_vars(ghosted_id)%aux_var_elem(0)%u(2) = vec_ptr(ghosted_id)
              enddo
            endif
          case(GAS_DENSITY, GAS_DENSITY_MOL) 
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Mphase%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%den(2) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Mphase%aux_vars(ghosted_id)%aux_var_elem(0)%den(2) = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_MOLE_FRACTION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Mphase%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%xmol(isubvar) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Mphase%aux_vars(ghosted_id)%aux_var_elem(0)%xmol(isubvar) = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_ENERGY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Mphase%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%u(1) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Mphase%aux_vars(ghosted_id)%aux_var_elem(0)%u(1) = vec_ptr(ghosted_id)
              enddo
            endif
        end select
      else if (associated(patch%aux%Immis)) then
        select case(ivar)
          case(TEMPERATURE)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Immis%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%temp = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Immis%aux_vars(ghosted_id)%aux_var_elem(0)%temp = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_PRESSURE)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Immis%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%pres = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Immis%aux_vars(ghosted_id)%aux_var_elem(0)%pres = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_SATURATION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Immis%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%sat(1) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Immis%aux_vars(ghosted_id)%aux_var_elem(0)%sat(1) = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_DENSITY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Immis%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%den(1) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Immis%aux_vars(ghosted_id)%aux_var_elem(0)%den(1) = vec_ptr(ghosted_id)
              enddo
            endif
          case(GAS_SATURATION)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Immis%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%sat(2) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Immis%aux_vars(ghosted_id)%aux_var_elem(0)%sat(2) = vec_ptr(ghosted_id)
              enddo
            endif
          case(GAS_ENERGY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Immis%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%u(2) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Immis%aux_vars(ghosted_id)%aux_var_elem(0)%u(2) = vec_ptr(ghosted_id)
              enddo
            endif
          case(LIQUID_ENERGY)
            if (vec_format == GLOBAL) then
              do local_id=1,grid%nlmax
                patch%aux%Immis%aux_vars(grid%nL2G(local_id))%aux_var_elem(0)%u(1) = vec_ptr(local_id)
              enddo
            else if (vec_format == LOCAL) then
              do ghosted_id=1,grid%ngmax
                patch%aux%Immis%aux_vars(ghosted_id)%aux_var_elem(0)%u(1) = vec_ptr(ghosted_id)
              enddo
            endif
        end select
      else if (associated(patch%aux%General)) then
        select case(ivar)
          case(TEMPERATURE)
            do local_id=1,grid%nlmax
              patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%temp = vec_ptr(local_id)
            enddo
          case(LIQUID_PRESSURE)
            do local_id=1,grid%nlmax
              patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%pres(option%liquid_phase) = vec_ptr(local_id)
            enddo
          case(GAS_PRESSURE)
            do local_id=1,grid%nlmax
              patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%pres(option%gas_phase) = vec_ptr(local_id)
            enddo
          case(STATE)
            do local_id=1,grid%nlmax
              patch%aux%Global%aux_vars(grid%nL2G(local_id))%istate = int(vec_ptr(local_id)+1.d-10)
            enddo
          case(LIQUID_SATURATION)
            do local_id=1,grid%nlmax
              patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%sat(option%liquid_phase) = vec_ptr(local_id)
            enddo
          case(LIQUID_DENSITY)
            do local_id=1,grid%nlmax
              patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%den_kg(option%liquid_phase) = vec_ptr(local_id)
            enddo
          case(LIQUID_ENERGY)
            do local_id=1,grid%nlmax
              patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%U(option%liquid_phase) = vec_ptr(local_id)
            enddo
          case(LIQUID_MOLE_FRACTION)
            do local_id=1,grid%nlmax
              patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%xmol(isubvar,option%liquid_phase) = vec_ptr(local_id)
            enddo
          case(GAS_SATURATION)
            do local_id=1,grid%nlmax
              patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%sat(option%gas_phase) = vec_ptr(local_id)
            enddo
          case(GAS_DENSITY) 
            do local_id=1,grid%nlmax
              patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%den_kg(option%gas_phase) = vec_ptr(local_id)
            enddo
          case(GAS_ENERGY)
            do local_id=1,grid%nlmax
              patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%U(option%gas_phase) = vec_ptr(local_id)
            enddo
          case(GAS_MOLE_FRACTION)
            do local_id=1,grid%nlmax
              patch%aux%General%aux_vars(ZERO_INTEGER,grid%nL2G(local_id))%xmol(isubvar,option%gas_phase) = vec_ptr(local_id)
            enddo
        end select         
      endif
    case(PRIMARY_MOLALITY,TOTAL_MOLARITY,MINERAL_VOLUME_FRACTION, &
         PRIMARY_ACTIVITY_COEF,SECONDARY_ACTIVITY_COEF,IMMOBILE_SPECIES)
      select case(ivar)
        case(PRIMARY_MOLALITY)
          if (vec_format == GLOBAL) then
            do local_id=1,grid%nlmax
              patch%aux%RT%aux_vars(grid%nL2G(local_id))%pri_molal(isubvar) = vec_ptr(local_id)
            enddo
          else if (vec_format == LOCAL) then
            do ghosted_id=1,grid%ngmax
              patch%aux%RT%aux_vars(ghosted_id)%pri_molal(isubvar) = vec_ptr(ghosted_id)
            enddo
          endif
        case(TOTAL_MOLARITY)
          if (vec_format == GLOBAL) then
            do local_id=1,grid%nlmax
              patch%aux%RT%aux_vars(grid%nL2G(local_id))%total(isubvar,iphase) = vec_ptr(local_id)
            enddo
          else if (vec_format == LOCAL) then
            do ghosted_id=1,grid%ngmax
              patch%aux%RT%aux_vars(ghosted_id)%total(isubvar,iphase) = vec_ptr(ghosted_id)
            enddo
          endif
        case(MINERAL_VOLUME_FRACTION)
          if (vec_format == GLOBAL) then
            do local_id=1,grid%nlmax
              patch%aux%RT%aux_vars(grid%nL2G(local_id))%mnrl_volfrac(isubvar) = vec_ptr(local_id)
            enddo
          else if (vec_format == LOCAL) then
            do ghosted_id=1,grid%ngmax
              patch%aux%RT%aux_vars(ghosted_id)%mnrl_volfrac(isubvar) = vec_ptr(ghosted_id)
            enddo
          endif
        case(IMMOBILE_SPECIES)
          if (vec_format == GLOBAL) then
            do local_id=1,grid%nlmax
              patch%aux%RT%aux_vars(grid%nL2G(local_id))%immobile(isubvar) = vec_ptr(local_id)
            enddo
          else if (vec_format == LOCAL) then
            do ghosted_id=1,grid%ngmax
              patch%aux%RT%aux_vars(ghosted_id)%immobile(isubvar) = vec_ptr(ghosted_id)
            enddo
          endif
        case(PRIMARY_ACTIVITY_COEF)
          if (vec_format == GLOBAL) then
            do local_id=1,grid%nlmax
              patch%aux%RT%aux_vars(grid%nL2G(local_id))%pri_act_coef(isubvar) = vec_ptr(local_id)
            enddo
          else if (vec_format == LOCAL) then
            do ghosted_id=1,grid%ngmax
              patch%aux%RT%aux_vars(ghosted_id)%pri_act_coef(isubvar) = vec_ptr(ghosted_id)
            enddo
          endif
        case(SECONDARY_ACTIVITY_COEF)
          if (vec_format == GLOBAL) then
            do local_id=1,grid%nlmax
              patch%aux%RT%aux_vars(grid%nL2G(local_id))%sec_act_coef(isubvar) = vec_ptr(local_id)
            enddo
          else if (vec_format == LOCAL) then
            do ghosted_id=1,grid%ngmax
              patch%aux%RT%aux_vars(ghosted_id)%sec_act_coef(isubvar) = vec_ptr(ghosted_id)
            enddo
          endif
      end select
    case(PRIMARY_MOLARITY,SECONDARY_MOLALITY,SECONDARY_MOLARITY,TOTAL_MOLALITY, &
         COLLOID_MOBILE,COLLOID_IMMOBILE)
      select case(ivar)
        case(PRIMARY_MOLARITY)
          call printErrMsg(option,'Setting of primary molarity at grid cell not supported.')
        case(SECONDARY_MOLALITY)
          call printErrMsg(option,'Setting of secondary molality at grid cell not supported.')
        case(SECONDARY_MOLARITY)
          call printErrMsg(option,'Setting of secondary molarity at grid cell not supported.')
        case(TOTAL_MOLALITY)
          call printErrMsg(option,'Setting of total molality at grid cell not supported.')
        case(COLLOID_MOBILE)
          call printErrMsg(option,'Setting of mobile colloid concentration at grid cell not supported.')
        case(COLLOID_IMMOBILE)
          call printErrMsg(option,'Setting of immobile colloid concentration at grid cell not supported.')
      end select
    case(POROSITY)
      if (vec_format == GLOBAL) then
        call GridVecGetArrayF90(grid,field%porosity_loc,vec_ptr2,ierr)
        do local_id=1,grid%nlmax
          vec_ptr2(grid%nL2G(local_id)) = vec_ptr(local_id)
        enddo
        call GridVecRestoreArrayF90(grid,field%porosity_loc,vec_ptr2,ierr)
      else if (vec_format == LOCAL) then
        call GridVecGetArrayF90(grid,field%porosity_loc,vec_ptr2,ierr)
        vec_ptr2(1:grid%ngmax) = vec_ptr(1:grid%ngmax)
        call GridVecRestoreArrayF90(grid,field%porosity_loc,vec_ptr2,ierr)
      endif
    case(PERMEABILITY,PERMEABILITY_X,PERMEABILITY_Y,PERMEABILITY_Z)
      option%io_buffer = 'Setting of permeability in "PatchSetDataset"' // &
        ' not supported.'
      call printErrMsg(option)
    case(PHASE)
      if (vec_format == GLOBAL) then
        call GridVecGetArrayF90(grid,field%iphas_loc,vec_ptr2,ierr)
        do local_id=1,grid%nlmax
          vec_ptr2(grid%nL2G(local_id)) = vec_ptr(local_id)
        enddo
        call GridVecRestoreArrayF90(grid,field%iphas_loc,vec_ptr2,ierr)
      else if (vec_format == LOCAL) then
        call GridVecGetArrayF90(grid,field%iphas_loc,vec_ptr2,ierr)
        vec_ptr2(1:grid%ngmax) = vec_ptr(1:grid%ngmax)
        call GridVecRestoreArrayF90(grid,field%iphas_loc,vec_ptr2,ierr)
      endif
    case(MATERIAL_ID)
      if (vec_format == GLOBAL) then
        do local_id=1,grid%nlmax
          patch%imat(grid%nL2G(local_id)) = int(vec_ptr(local_id))
        enddo
      else if (vec_format == LOCAL) then
        patch%imat(1:grid%ngmax) = int(vec_ptr(1:grid%ngmax))
      endif
    case(PROCESSOR_ID)
      call printErrMsg(option, &
                       'Cannot set PROCESSOR_ID through PatchSetDataset()')
  end select

  call GridVecRestoreArrayF90(grid,vec,vec_ptr,ierr)
  
end subroutine PatchSetDataset

! ************************************************************************** !
!
! PatchCountCells: Counts # of active and inactive grid cells 
! author: Glenn Hammond
! date: 06/01/10
!
! ************************************************************************** !
subroutine PatchCountCells(patch,total_count,active_count)

  use Option_module

  implicit none
  
  type(patch_type) :: patch
  PetscInt :: total_count
  PetscInt :: active_count
  
  type(grid_type), pointer :: grid
  PetscInt :: local_id
  
  grid => patch%grid
  
  total_count = grid%nlmax
  
  active_count = 0
  do local_id = 1, grid%nlmax
    if (patch%imat(grid%nL2G(local_id)) <= 0) cycle
    active_count = active_count + 1
  enddo

end subroutine PatchCountCells

! ************************************************************************** !
!
! PatchCalculateCFL1Timestep: Calculates largest time step to preserves a 
!                                CFL # of 1 in a patch
! author: Glenn Hammond
! date: 10/06/11
!
! ************************************************************************** !
subroutine PatchCalculateCFL1Timestep(patch,option,max_dt_cfl_1)

  use Option_module
  use Connection_module
  use Coupler_module
  use Field_module
  use Global_Aux_module
  
  implicit none
  
  type(patch_type) :: patch
  type(option_type) :: option
  PetscReal :: max_dt_cfl_1
  
  type(grid_type), pointer :: grid
  type(field_type), pointer :: field
  type(coupler_type), pointer :: boundary_condition
  type(global_auxvar_type), pointer :: global_aux_vars(:)
  type(connection_set_list_type), pointer :: connection_set_list
  type(connection_set_type), pointer :: cur_connection_set
  PetscInt :: iconn
  PetscInt :: sum_connection
  PetscReal :: distance, fraction_upwind
  PetscReal :: por_sat_ave, por_sat_min, v_darcy, v_pore_ave, v_pore_max
  PetscInt :: local_id_up, local_id_dn
  PetscInt :: ghosted_id_up, ghosted_id_dn
  PetscInt :: iphase

  PetscReal, pointer :: porosity_loc_p(:)
  PetscReal :: dt_cfl_1
  PetscErrorCode :: ierr

  field => patch%field
  global_aux_vars => patch%aux%Global%aux_vars
  grid => patch%grid

  call GridVecGetArrayF90(grid,field%porosity_loc, porosity_loc_p, ierr)

  max_dt_cfl_1 = 1.d20
  
  connection_set_list => grid%internal_connection_set_list
  cur_connection_set => connection_set_list%first
  sum_connection = 0  
  do 
    if (.not.associated(cur_connection_set)) exit
    do iconn = 1, cur_connection_set%num_connections
      sum_connection = sum_connection + 1
      ghosted_id_up = cur_connection_set%id_up(iconn)
      ghosted_id_dn = cur_connection_set%id_dn(iconn)
      local_id_up = grid%nG2L(ghosted_id_up) ! = zero for ghost nodes
      local_id_dn = grid%nG2L(ghosted_id_dn) ! Ghost to local mapping   
      if (patch%imat(ghosted_id_up) <= 0 .or.  &
          patch%imat(ghosted_id_dn) <= 0) cycle
      distance = cur_connection_set%dist(0,iconn)
      fraction_upwind = cur_connection_set%dist(-1,iconn)
      do iphase = 1, option%nphase
        por_sat_min = min(porosity_loc_p(ghosted_id_up)* &
                          global_aux_vars(ghosted_id_up)%sat(iphase), &
                          porosity_loc_p(ghosted_id_dn)* &
                          global_aux_vars(ghosted_id_dn)%sat(iphase))
        por_sat_ave = (fraction_upwind*porosity_loc_p(ghosted_id_up)* &
                       global_aux_vars(ghosted_id_up)%sat(iphase) + &
                      (1.d0-fraction_upwind)*porosity_loc_p(ghosted_id_dn)* &
                      global_aux_vars(ghosted_id_dn)%sat(iphase))
        v_darcy = patch%internal_velocities(iphase,sum_connection)
        v_pore_max = v_darcy / por_sat_min
        v_pore_ave = v_darcy / por_sat_ave
        !geh: I use v_por_max to ensure that we limit the cfl based on the
        !     highest velocity through the face.  If porosity*saturation
        !     varies, the pore water velocity will be highest on the side
        !     of the face with the smalled value of porosity*saturation.
        dt_cfl_1 = distance / dabs(v_pore_max)
        max_dt_cfl_1 = min(dt_cfl_1,max_dt_cfl_1)
      enddo
    enddo
    cur_connection_set => cur_connection_set%next
  enddo

  boundary_condition => patch%boundary_conditions%first
  sum_connection = 0    
  do 
    if (.not.associated(boundary_condition)) exit
    cur_connection_set => boundary_condition%connection_set
    do iconn = 1, cur_connection_set%num_connections
      sum_connection = sum_connection + 1
      local_id_dn = cur_connection_set%id_dn(iconn)
      ghosted_id_dn = grid%nL2G(local_id_dn)
      if (patch%imat(ghosted_id_dn) <= 0) cycle
      !geh: since on boundary, dist must be scaled by 2.d0
      distance = 2.d0*cur_connection_set%dist(0,iconn)
      do iphase = 1, option%nphase
        por_sat_ave = porosity_loc_p(ghosted_id_dn)* &
                      global_aux_vars(ghosted_id_dn)%sat(iphase)
        v_darcy = patch%boundary_velocities(iphase,sum_connection)
        v_pore_ave = v_darcy / por_sat_ave
        dt_cfl_1 = distance / dabs(v_pore_ave)
        max_dt_cfl_1 = min(dt_cfl_1,max_dt_cfl_1)
      enddo
    enddo
    boundary_condition => boundary_condition%next
  enddo

  call GridVecRestoreArrayF90(grid,field%porosity_loc, porosity_loc_p, ierr)

end subroutine PatchCalculateCFL1Timestep

! ************************************************************************** !
!
! PatchGetVarNameFromKeyword: Returns the name of variable defined by keyword
! author: Glenn Hammond
! date: 07/28/11
!
! ************************************************************************** !
function PatchGetVarNameFromKeyword(keyword,option)
 
  use Option_module

  implicit none

  character(len=MAXWORDLENGTH) :: keyword
  type(option_type) :: option

  character(len=MAXSTRINGLENGTH) :: PatchGetVarNameFromKeyword
  character(len=MAXSTRINGLENGTH) :: var_name

  select case(keyword)
    case('PROCESSOR_ID')
      var_name = 'Processor ID'
    case default
      option%io_buffer = 'Keyword "' // trim(keyword) // '" not ' // &
                         'recognized in PatchGetIvarsFromKeyword()'
      call printErrMsg(option)
  end select

  PatchGetVarNameFromKeyword = var_name

end function PatchGetVarNameFromKeyword

! ************************************************************************** !
!
! PatchGetIvarsFromKeyword: Returns the ivar and isubvars for extracting
!                            datasets using PatchGet/PatchSet routines
! author: Glenn Hammond
! date: 07/28/11
!
! ************************************************************************** !
subroutine PatchGetIvarsFromKeyword(keyword,ivar,isubvar,var_type,option)
 
  use Option_module
  use Variables_module

  implicit none

  character(len=MAXWORDLENGTH) :: keyword
  PetscInt :: ivar
  PetscInt :: isubvar
  PetscInt :: var_type
  type(option_type) :: option

  select case(keyword)
    case('PROCESSOR_ID')
      ivar = PROCESSOR_ID
      isubvar = ZERO_INTEGER
      var_type = INT_VAR
    case default
      option%io_buffer = 'Keyword "' // trim(keyword) // '" not ' // &
                         'recognized in PatchGetIvarsFromKeyword()'
      call printErrMsg(option)
  end select

end subroutine

! ************************************************************************** !
!
! PatchDestroyList: Deallocates a patch list and array of patches
! author: Glenn Hammond
! date: 10/15/07
!
! ************************************************************************** !
subroutine PatchDestroyList(patch_list)

  implicit none
  
  type(patch_list_type), pointer :: patch_list
    
  type(patch_type), pointer :: cur_patch, prev_patch
  
  if (.not.associated(patch_list)) return
  
  if (associated(patch_list%array)) deallocate(patch_list%array)
  nullify(patch_list%array)
  
  cur_patch => patch_list%first
  do 
    if (.not.associated(cur_patch)) exit
    prev_patch => cur_patch
    cur_patch => cur_patch%next
    call PatchDestroy(prev_patch)
  enddo
  
  nullify(patch_list%first)
  nullify(patch_list%last)
  patch_list%num_patch_objects = 0
  
  deallocate(patch_list)
  nullify(patch_list)

end subroutine PatchDestroyList

! ************************************************************************** !
!
! PatchDestroy: Deallocates a patch object
! author: Glenn Hammond
! date: 02/22/08
!
! ************************************************************************** !
subroutine PatchDestroy(patch)

  implicit none
  
  type(patch_type), pointer :: patch
  
  if (associated(patch%imat)) deallocate(patch%imat)
  nullify(patch%imat)
  if (associated(patch%sat_func_id)) deallocate(patch%sat_func_id)
  nullify(patch%sat_func_id)
  if (associated(patch%internal_velocities)) deallocate(patch%internal_velocities)
  nullify(patch%internal_velocities)
  if (associated(patch%boundary_velocities)) deallocate(patch%boundary_velocities)
  nullify(patch%boundary_velocities)
  if (associated(patch%internal_fluxes)) deallocate(patch%internal_fluxes)
  nullify(patch%internal_fluxes)
  if (associated(patch%boundary_fluxes)) deallocate(patch%boundary_fluxes)
  nullify(patch%boundary_fluxes)
  if (associated(patch%internal_tran_coefs)) deallocate(patch%internal_tran_coefs)
  nullify(patch%internal_tran_coefs)
  if (associated(patch%boundary_tran_coefs)) deallocate(patch%boundary_tran_coefs)
  nullify(patch%boundary_tran_coefs)
  if (associated(patch%ss_fluid_fluxes)) deallocate(patch%ss_fluid_fluxes)
  nullify(patch%ss_fluid_fluxes)

  if (associated(patch%material_property_array)) &
    deallocate(patch%material_property_array)
  nullify(patch%material_property_array)
  ! Since this linked list will be destroyed by realization, just nullify here
  nullify(patch%material_properties)
  if (associated(patch%saturation_function_array)) &
    deallocate(patch%saturation_function_array)
  nullify(patch%saturation_function_array)
  ! Since this linked list will be destroyed by realization, just nullify here
  nullify(patch%saturation_functions)

#ifdef SURFACE_FLOW
  nullify(patch%surf_field)
  if (associated(patch%surf_material_property_array)) &
    deallocate(patch%surf_material_property_array)
  nullify(patch%surf_material_property_array)
  nullify(patch%surf_material_properties)
  if (associated(patch%surf_internal_fluxes)) deallocate(patch%surf_internal_fluxes)
  if (associated(patch%surf_boundary_fluxes)) deallocate(patch%surf_boundary_fluxes)
  nullify(patch%surf_internal_fluxes)
  nullify(patch%surf_boundary_fluxes)
#endif

  call GridDestroy(patch%grid)
  call RegionDestroyList(patch%regions)
  call CouplerDestroyList(patch%boundary_conditions)
  call CouplerDestroyList(patch%initial_conditions)
  call CouplerDestroyList(patch%source_sinks)
  
  
  call ObservationDestroyList(patch%observation)
  call StrataDestroyList(patch%strata)
  
  call AuxDestroy(patch%aux)
  
  call ObservationDestroyList(patch%observation)
  
  ! these are solely pointers, must not destroy.
  nullify(patch%reaction)
  nullify(patch%datasets)
  nullify(patch%field)
  
  deallocate(patch)
  nullify(patch)
  
end subroutine PatchDestroy

#ifdef SURFACE_FLOW
! ************************************************************************** !
!
! PatchGetDataset: Extracts variables indexed by ivar and isubvar from a patch
! author: Glenn Hammond
! date: 09/12/08
!
! ************************************************************************** !
subroutine PatchGetDataset2(patch,surf_field,option,output_option,vec,ivar, &
                           isubvar,isubvar1)

  use Grid_module
  use Option_module
  use Output_Aux_module
  use Surface_Field_module
  use Variables_module

  implicit none

#include "finclude/petscvec.h"
#include "finclude/petscvec.h90"

  type(option_type), pointer :: option
  !type(reaction_type), pointer :: reaction
  type(output_option_type), pointer :: output_option
  type(surface_field_type), pointer :: surf_field
  type(patch_type), pointer :: patch  
  Vec :: vec
  PetscInt :: ivar
  PetscInt :: isubvar
  PetscInt, optional :: isubvar1
  PetscInt :: iphase

  PetscInt :: local_id, ghosted_id
  type(grid_type), pointer :: grid
  PetscReal, pointer :: vec_ptr(:), vec_ptr2(:)
  PetscReal :: xmass
  PetscReal :: tempreal
  PetscInt :: tempint
  PetscInt :: irate, istate, irxn
  PetscErrorCode :: ierr

  grid => patch%grid

  call GridVecGetArrayF90(grid,vec,vec_ptr,ierr)
  
  iphase = 1
  
  select case(ivar)
    case(SURFACE_LIQUID_HEAD)
      do local_id=1,grid%nlmax
        vec_ptr(local_id) = patch%surf_aux%SurfaceGlobal%aux_vars(grid%nL2G(local_id))%head(1)
      enddo
    case(SURFACE_LIQUID_TEMPERATURE)
      do local_id=1,grid%nlmax
        vec_ptr(local_id) = patch%surf_aux%SurfaceGlobal%aux_vars(grid%nL2G(local_id))%temp(1)
      enddo
    case(MATERIAL_ID)
      do local_id=1,grid%nlmax
        vec_ptr(local_id) = patch%imat(grid%nL2G(local_id))
      enddo
    case default
      write(option%io_buffer, &
            '(''IVAR ('',i3,'') not found in PatchGetDataset'')') ivar
      call printErrMsg(option)
  end select

end subroutine PatchGetDataset2

#endif
! SURFACE_FLOW

end module Patch_module