File: piv.c

package info (click to toggle)
libgpiv 0.6.1-7.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 4,404 kB
  • sloc: ansic: 17,832; sh: 10,248; makefile: 114
file content (3864 lines) | stat: -rw-r--r-- 117,558 bytes parent folder | download | duplicates (6)
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
/* -*- Mode: C; indent-tabs-mode: nil; c-basic-offset: 4 c-style: "K&R" -*- */

/*
   libgpiv - library for Particle Image Velocimetry

   Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008
   Gerber van der Graaf

   This file is part of libgpiv.

   Libgpiv is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software Foundation,
   Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.



------------------------------------------------------------------------------
FILENAME:                piv.c
LIBRARY:                 libgpiv
EXTERNAL FUNCTIONS:
                         gpiv_piv_count_pivdata_fromimage
			 gpiv_piv_select_int_point
                         gpiv_piv_interrogate_img
                         gpiv_piv_interrogate_ia
                         gpiv_piv_isizadapt
                         gpiv_piv_write_deformed_image
			 gpiv_piv_weight_kernel_1
			 gpiv_piv_weight_kernel_lin
			 gpiv_fread_fftw_wisdom
			 gpiv_fwrite_fftw_wisdom


LAST MODIFICATION DATE:  $Id: piv.c,v 1.5 2008-09-25 13:19:53 gerber Exp $
---------------------------------------------------------------------------- */

#include <gpiv.h>
#undef USE_MTRACE
#ifdef USE_MTRACE
#include <mcheck.h>
#endif
#include "my_utils.h"

#define FFTWISDOM "gpiv_fftwis"	/* filename containg a string of wisdom for fft */
#define FFTWISDOM_INV "gpiv_fftwis_inv"	/* filename containg a string of wisdom for inverse fft */



/*-------------------------------------------------------------------------
 Levenbergh-Margardt parameter estimation constants */
/* #define MA 4 */			/* Number of parameters to be estimated by
				   marquardt fit of cov peak */
/* #define NPT 9 */			/* Numbers of points to be fitted by mrqmin */
/* #define SPREAD 0.001 */		/* multiplication factor for individual
				   variances in measuremnts, i.e. covariance
				   peak values */
/* #undef NPT */
/* #undef SPREAD */



#define NMIN_TO_INTERPOLATE 2

enum Position {
    LOWER,
    NEXT_LOWER,
    HIGHER,
    NEXT_HIGHER
};

enum HorizontalPosition {
    WEST,
    WEST_WEST,
    EAST,
    EAST_EAST
};

enum VerticalPosition {
    NORTH,
    NORTH_NORTH,
    SOUTH, 
    SOUTH_SOUTH, 
};



/*
 * Local functions prototypes
 */

static GpivPivData *
alloc_pivdata_gridgen (const GpivImagePar *image_par, 
                       const GpivPivPar *piv_par
                       );

static void 
report_progress (gint *progress_old,
                 gint index_y,
                 gint index_x,
                 GpivPivData *piv_data,
                 GpivPivPar *piv_par,
                 gint sweep,
                 gfloat cum_residu
                 );

static gboolean
assign_img2intarr (gint ipoint_x,
                   gint ipoint_y,
                   guint16 **img_1,
                   guint16 **img_2,
                   gint int_size_f,
                   gint int_size_i,
                   gfloat **int_area_1,
                   gfloat **int_area_2,
                   gint pre_shift_row,
                   gint pre_shift_col,
                   gint nrows,
                   gint ncolumns,
                   gint int_size_0
                   );

static gboolean
assign_img2intarr_central (gint ipoint_x,
                           gint ipoint_y,
                           guint16 **img_1,
                           guint16 **img_2,
                           gint int_size_f,
                           gint int_size_i,
                           gfloat **int_area_1,
                           gfloat **int_area_2,
                           gint pre_shift_row,
                           gint pre_shift_col,
                           gint nrows,
                           gint ncolumns,
                           gint int_size_0
                           );

static gboolean
assign_img2intarr_forward (gint ipoint_x,
                           gint  ipoint_y,
                           guint16 **img_1,
                           guint16 **img_2,
                           gint int_size_f,
                           gint int_size_i,
                           gfloat **int_area_1,
                           gfloat **int_area_2,
                           gint pre_shift_row,
                           gint pre_shift_col,
                           gint nrows,
                           gint ncolumns,
                           gint int_size_0
                           );

static float
int_mean_old (guint16 **img,
              int int_size,
              int int_size_i,
              int ipoint_x,
              int ipoint_y
              );

static gfloat
int_mean (gfloat **int_area,
          gint int_size
          );

static gfloat
int_range (gfloat **int_area,
           gint int_size
           );

static gboolean
int_const (gfloat **int_area,
           const guint int_size
           );

static void
cov_min_max (GpivCov *cov
             );

static void
search_top (GpivCov *cov,
            gint peak_act,
            gint x_corr,
            gint sweep,
            gint i_skip_act,
            gint j_skip_act,
            float *z_max,
            long *i_max,
            long *j_max
            );

static char *
cov_subtop (float **z,
            long *i_max,
            long *j_max,
            float *epsi_x,
            float *epsi_y,
            int ifit,
            int peak_act
            );

static int
cov_top (GpivPivPar piv_par,
         GpivPivData * piv_data,
         int index_y,
         int index_x,
         GpivCov *cov,
         int x_corr,
         int ifit,
         int sweep,
         int last_sweep,
         int peak,
         int peak_act,
         int pre_shift_row_act,
         int pre_shift_col_act,
         int i_skip_act,
         int j_skip_act,
         gboolean *flag_subtop
         );

static
void pack_cov (float **covariance,
               GpivCov *cov,
               int int_size_0
               );

static void
piv_weight_kernel_lin (const guint int_size_0,
                       GpivCov *w_k
                       );

static void
weight_cov (GpivCov *cov,
            GpivCov *w_k
            );

static gchar *
filter_cov_spof (fftw_complex *a, 
                 fftw_complex *b,
                 gint m,
                 gint n
                 );

static gchar *
cova (int int_size,
      float **int_area_1,
      float **int_area_2,
      GpivCov *cov,
      gboolean spof_filter
      );

static gchar *
ia_weight_gauss (gint int_size, 
                 float **int_area
                 );

/*
 * Origined from piv_speed
 */
static void
nearest_point (gint i,
               gfloat x, 
               gfloat point_x, 
               gfloat *min, 
               gint *index, 
               gboolean *exist
               );

static gboolean
nearest_index (enum Position pos,
               gint vlength,
               gfloat *src_point, 
               gfloat dest_point,
               gint *index
               );

static gdouble
bilinear_interpol (gdouble alpha_hor,
                   gdouble alpha_vert,
                   gdouble src_dx_nw,
                   gdouble src_dx_ne,
                   gdouble src_dx_sw,
                   gdouble src_dx_se
                   );

static void *
intpol_facts (gfloat *src_point, 
              gfloat *dest_point, 
              gint src_vlength,
              gint dest_vlength,
              gint *index_l,
              gint *index_h,
              gint *index_ll,
              gint *index_hh,
              double *alpha
              );

static void
dxdy_at_new_grid_block (const GpivPivData *piv_data_src, 
                        GpivPivData *piv_data_dest,
                        gint expansion_factor,
                        gint smooth_window
                        );

static gchar *
update_pivdata_imgdeform_zoff (const GpivImage *image, 
                               GpivImage *lo_image, 
                               const GpivPivPar *piv_par, 
                               const GpivValidPar *valid_par, 
                               GpivPivData *piv_data, 
                               GpivPivData *lo_piv_data, 
                               gfloat *cum_residu, 
                               gboolean *cum_residu_reached,
                               gfloat *sum_dxdy, 
                               gfloat *sum_dxdy_old,
                               gboolean isi_last,
                               gboolean grid_last,
                               gboolean sweep_last,
                               gboolean verbose
                               );

/*
 * Some MPI routines
 */
#ifdef ENABLE_MPI
static GpivPivData *
piv_interrogate_img__scatterv_pivdata (GpivPivData *piv_data);

static GpivPivData *
piv_interrogate_img__gatherv_pivdata(GpivPivData *lo_piv_data, 
                                     GpivPivData *piv_data);

guint
substr_noremain(guint n, 
                guint m);

#endif /* ENABLE_MPI */

/*
 * Public functions
 */

gchar *
gpiv_piv_count_pivdata_fromimage (const GpivImagePar *image_par,
                                  const GpivPivPar *piv_par,
                                  guint *nx,
                                  guint *ny
                                  )
/*-----------------------------------------------------------------------------
 *     Calculates the number of interrogation areas from the image sizes,
 *     pre-shift and area of interest
 *     NULL on success or error message on failure
 *---------------------------------------------------------------------------*/
{
    gchar *err_msg = NULL;
    int row, column, row_1, column_1,
	pre_shift_row_max, pre_shift_col_max, count_x = 0, count_y = 0;
    int row_max, row_min, column_max, column_min;

    int ncolumns = image_par->ncolumns;
    int nrows = image_par->nrows;

    int int_geo = piv_par->int_geo;
    int row_start = piv_par->row_start;
    int row_end = piv_par->row_end;
    int col_start = piv_par->col_start;
    int col_end = piv_par->col_end;
    int int_line_col = piv_par->int_line_col;
    int int_line_col_start = piv_par->int_line_col_start;
    int int_line_col_end = piv_par->int_line_col_end;
    int int_line_row = piv_par->int_line_row;
    int int_line_row_start = piv_par->int_line_row_start;
    int int_line_row_end = piv_par->int_line_row_end;
    int int_point_col = piv_par->int_point_col;
    int int_point_row = piv_par->int_point_row;
    int int_size_f = piv_par->int_size_f;
    int int_size_i = piv_par->int_size_i;
    int int_shift = piv_par->int_shift;
    int pre_shift_row = piv_par->pre_shift_row;
    int pre_shift_col = piv_par->pre_shift_col;


    *nx = 0;
    *ny = 0;


    row_min = gpiv_min(-int_size_f / 2 + 1,
                       pre_shift_row - int_size_i / 2 + 1);
    column_min = gpiv_max(-int_size_f / 2 + 1,
                          pre_shift_col - int_size_i / 2 + 1);
    row_max = gpiv_max(int_size_f / 2, pre_shift_row + int_size_i / 2);
    column_max = gpiv_max(int_size_f / 2, pre_shift_col + int_size_i / 2);


    if (int_geo == GPIV_POINT) {
        *nx = 1;
        *ny = 1;


/*
 * Counts number of Interrrogation Area for a single row
 */
    } else if (int_geo == GPIV_LINE_R) {
        if ((int_size_f - int_size_i) / 2 + pre_shift_col < 0) {
            column_1 = int_line_col_start -
                ((int_size_f - int_size_i) / 2 +
                 pre_shift_col) + int_size_f / 2 - 1;
        } else {
                column_1 = int_line_col_start + int_size_f / 2 - 1;
        }

        for (column = column_1; column <= int_line_col_end - column_max;
             column += int_shift) {
            count_x++;
        }

        *nx = count_x;
        *ny = 1;

/*
 * Counts number of Interrrogation Area for a single column
 */
    } else if (int_geo == GPIV_LINE_C) {
        if ((int_size_f - int_size_i) / 2 + pre_shift_row < 0) {
            row_1 = int_line_row_start -
                ((int_size_f - int_size_i) / 2 +
                     pre_shift_row) + int_size_f / 2 - 1;
        } else {
            row_1 = int_line_row_start + int_size_f / 2 - 1;
        }

        for (row = row_1; row <= int_line_row_end - row_max;
             row += int_shift) {
            count_y++;
        }

        *ny = count_y;
        *nx = 1;


/*
 * Counts number of Interrrogation Area for a Area Of Interest
 */
    } else if (int_geo == GPIV_AOI) {
	if ((int_size_f - int_size_i) / 2 + pre_shift_row < 0) {
	    row_1 =
		row_start - ((int_size_f - int_size_i) / 2 +
			     pre_shift_row) + int_size_f / 2 - 1;
	} else {
	    row_1 = row_start + int_size_f / 2 - 1;
	}
	if ((int_size_f - int_size_i) / 2 + pre_shift_col < 0) {
	    column_1 =
		col_start - ((int_size_f - int_size_i) / 2 +
			     pre_shift_col) + int_size_f / 2 - 1;
	} else {
	    column_1 = col_start + int_size_f / 2 - 1;
	}


	pre_shift_col_max = gpiv_max (pre_shift_col, 0);
	column_max =
	    gpiv_max(int_size_f / 2, pre_shift_col + int_size_i / 2);
	pre_shift_row_max = gpiv_max (pre_shift_row, 0);
	row_max = gpiv_max (int_size_f / 2, pre_shift_row + int_size_i / 2);


	for (row = row_1; row + row_max <= row_end; row += int_shift) {
	    for (column = column_1; column + column_max <= col_end;
		 column += int_shift) {
		count_x++;
	    }
	    if (count_x > *nx)
		*nx = count_x;
	    count_x = 0;
	    count_y++;
	}
	if (count_y > *ny)
	  *ny = count_y;
    } else {
        err_msg = "gpiv_piv_count_pivdata_fromimage: should not arrive here";
        gpiv_warning ("%s", err_msg);
        return err_msg;
    }

    if (*nx == 0 || *ny == 0) {
        err_msg = "gpiv_piv_count_pivdata_fromimage: line or AOI too small: nx=0 ny=0";
        gpiv_warning("gpiv_piv_count_pivdata_fromimage: line or AOI too small: nx = %d ny = %d\n", 
                     *nx, *ny);
        return err_msg;
    }

#ifdef DEBUG
    g_message ("gpiv_piv_count_pivdata_fromimage:: 2 nx = %d, ny = %d", *nx, *ny);
#endif
    return err_msg;
}



GpivPivData *
gpiv_piv_interrogate_img (const GpivImage *image,
                          const GpivPivPar *piv_par,
                          const GpivValidPar *valid_par,
                          const gboolean verbose
                          )
/* ----------------------------------------------------------------------------
 * PIV interrogation of an image pair at an entire grid or single point
 *
 *     @param[in] image           image containing data and header info
 *     @param[in] piv_par         image evaluation parameters
 *     @param[in] valid_par       structure of PIV data validation parameters
 *     @param[out] verbose        prints progress of interrogation to stdout
 *     @return                    GpivPivData containing PIV estimators on succes
 *                                or NULL on failure
 */
/*---------------------------------------------------------------------------*/
{
    GpivPivData *piv_data = NULL;       /* piv data to be returned */
    gchar *err_msg = NULL;              /* error message */
    guint index_x = 0, index_y = 0;     /* array indices */

    /*
     * Local variables with prefix lo_ to distinguish from global or from 
     * parameter list
     */
    GpivImage *lo_image = NULL;         /* local image that might be deformed */
    GpivPivData *lo_piv_data = NULL;    /* local piv data */
    GpivPivPar *lo_piv_par = NULL;      /* local piv parameters */
    
    gfloat **intreg1;                   /* first interrogation area */
    gfloat **intreg2;                   /* second interrogation area */
    guint int_size_0;                   /* zero-padded interrogation area size */

    GpivCov *cov = NULL;                /* covariance */
    guint sweep = 1;                    /* itaration counter */
    gboolean grid_last = FALSE;         /* flag if final grid refinement has been
                                           reached */
    gboolean isi_last = FALSE;          /* flag if final interrogation area shift
                                           has been reached */
    gboolean cum_residu_reached = FALSE;/* flag if max. cumulative residu has 
                                           been reached */
    gboolean sweep_last = FALSE;        /* perform the last iteration sweep */
    gboolean sweep_stop = FALSE;        /* stop the current iteration at the end */
    gfloat sum_dxdy = 0.0, sum_dxdy_old = 0.0;  /* */
    gfloat cum_residu = 914.6;          /* initial, large, arbitrary cumulative 
                                           residu */
    guint progress_old = 0;             /* for monitoring calculation progress */

#ifdef ENABLE_MPI
    GpivPivData *mpi_piv_data = NULL;  /* received / gathered piv data to be used for 
                                          parallel processing */
    gint nprocs, rank, count = 0;
    gboolean scatter;
    gint i, *counts = NULL, *displs = NULL;
#endif

    /*     initvars_interrogate_img(); */
    if (verbose) printf ("\n");

    /*
     * Testing parameters on consistency and initializing derived 
     * parameters/variables
     */
    if ((err_msg = 
         gpiv_piv_testonly_parameters (image->header, piv_par))
        != NULL) {
        gpiv_warning ("gpiv_piv_interrogate_img: %s", err_msg);
        return NULL;
    }

    if ((err_msg = 
         gpiv_valid_testonly_parameters (valid_par))
        != NULL) {
        gpiv_warning ("gpiv_piv_interrogate_img: %s", err_msg);
        return NULL;
    }

    /*
     * Local (actualized) parameters
     * Setting initial parameters and variables for adaptive grid and 
     * Interrogation Area dimensions
     */
    lo_piv_par = gpiv_piv_cp_parameters (piv_par);

    if (lo_piv_par->int_scheme == GPIV_ZERO_OFF_FORWARD
        || lo_piv_par->int_scheme == GPIV_ZERO_OFF_CENTRAL
	|| lo_piv_par->int_scheme == GPIV_IMG_DEFORM
        || lo_piv_par->int_size_i > lo_piv_par->int_size_f) {
        lo_piv_par->int_size_f = lo_piv_par->int_size_i;
        sweep_last = FALSE;
    } else {
        sweep_last = TRUE;
    }
    
    if (lo_piv_par->int_shift < lo_piv_par->int_size_i / GPIV_SHIFT_FACTOR) {
        lo_piv_par->int_shift = lo_piv_par->int_size_i / GPIV_SHIFT_FACTOR;
    }
    
    /*
     * A copy of the image and PIV data are needed when image deformation is used.
     * To keep the algorithm simple (well, what's in the name :), copies are made 
     * unconditionally.
     */
    lo_image = gpiv_cp_img (image);
    piv_data = alloc_pivdata_gridgen (image->header, lo_piv_par);

#ifdef ENABLE_MPI
    MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#endif /* ENABLE_MPI */

    lo_piv_data = gpiv_cp_pivdata (piv_data);

#ifdef DEBUG
    gpiv_write_pivdata(NULL, lo_piv_data, FALSE);
    fflush(stdout);
#endif /* DEBUG */

    gpiv_0_pivdata (lo_piv_data);
    
    /*
     * Reads eventually existing fftw wisdom
     */
    gpiv_fread_fftw_wisdom (1);
    gpiv_fread_fftw_wisdom (-1);

#ifdef _OPENMP
    fftw_init_threads();
#endif

    while (sweep <= GPIV_MAX_PIV_SWEEP 
           && !sweep_stop) {

        /*
         * Memory allocation of interrogation area's and covariance. 
         * These memory chunks are allocated here to optimize calculation 
         * speed and for eventually monitoring their contents.
         */
        int_size_0 = GPIV_ZEROPAD_FACT * lo_piv_par->int_size_i;
	intreg1 = gpiv_matrix (int_size_0, int_size_0);
	intreg2 = gpiv_matrix (int_size_0, int_size_0);
        cov = gpiv_alloc_cov (int_size_0, image->header->x_corr);
        
        /*
         * Interrogates a single interrogation area
         */
	if (lo_piv_par->int_geo == GPIV_POINT) {

            if ((err_msg = 
                 gpiv_piv_interrogate_ia (0, 
                                          0, 
                                          lo_image, 
                                          lo_piv_par,
                                          sweep, 
                                          sweep_last, 
                                          intreg1,
                                          intreg2,
                                          cov,
                                          lo_piv_data
                                          ))
                != NULL) {
                gpiv_free_img (lo_image);
                gpiv_free_pivdata (lo_piv_data);
                gpiv_free_pivdata (piv_data);
 	        gpiv_free_matrix (intreg1);
	        gpiv_free_matrix (intreg2);
                gpiv_free_cov (cov);
                gpiv_warning ("gpiv_piv_interrogate_img: %s", err_msg);
                return NULL;
            }

	} else {
            /*
             * Interrogates at a rectangular grid of points within the Area Of
             * Interest of the image
             */

#ifdef ENABLE_MPI
            /*
             * Scatter the PIV data over the rows to the different nodes.
             */
            lo_piv_data = piv_interrogate_img__scatterv_pivdata(lo_piv_data);
#endif /* ENABLE_MPI */

            for (index_y = 0; index_y < lo_piv_data->ny; index_y++) {
                for (index_x = 0; index_x < lo_piv_data->nx; index_x++) {

                    /*                     if (rank==0) g_message ("gpiv_piv_interrogate_img:: 0e rank=%d i_x=%d i_y=%d",  */
                    /*                                                   rank, index_x, index_y); */
                    /*
                     * Interrogates a single interrogation area.
                     */
                        if ((err_msg = 
                             gpiv_piv_interrogate_ia (index_y, 
                                                      index_x, 
                                                      lo_image,
                                                      lo_piv_par,
                                                      sweep, 
                                                      sweep_last,
                                                      intreg1,
                                                      intreg2,
                                                      cov,
                                                      lo_piv_data
                                                      ))
                            != NULL) {
                            gpiv_free_img (lo_image);
                            gpiv_free_pivdata (lo_piv_data);
                            gpiv_free_pivdata (piv_data);
                            gpiv_free_matrix (intreg1);
                            gpiv_free_matrix (intreg2);
                            gpiv_free_cov (cov);
                            gpiv_warning ("gpiv_piv_interrogate_img: %s", err_msg);
#ifdef ENABLE_MPI
                            MPI_Finalize();
#endif
                            return NULL;
                        }

                        /*
                         * Printing the progress of processing
                         */
                        if (verbose ) {
                            report_progress (&progress_old,
                                             index_y,
                                             index_x, 
                                             lo_piv_data, 
                                             lo_piv_par,
                                             sweep,
                                             cum_residu);
                        }


                    }
                }
#ifdef ENABLE_MPI
            /*
             * Gather the scattered PIV data 
             * and broadcasts the entire array to all nodes.
             */
            lo_piv_data = piv_interrogate_img__gatherv_pivdata(lo_piv_data, 
                                                               piv_data);
            gpiv_piv_mpi_bcast_pivdata (lo_piv_data);
#endif
        }

        /*
         * De-allocating memory: other (smaller) sizes are eventually needed 
         * for a next iteration sweep
         */
        gpiv_free_matrix (intreg1);
        gpiv_free_matrix (intreg2);
        gpiv_free_cov (cov);

        if (sweep_last) {
            sweep_stop = TRUE;
        }

        if (lo_piv_par->int_scheme == GPIV_IMG_DEFORM
            || lo_piv_par->int_scheme == GPIV_ZERO_OFF_FORWARD
            || lo_piv_par->int_scheme == GPIV_ZERO_OFF_CENTRAL) {

            if ((err_msg = 
                 update_pivdata_imgdeform_zoff (image, lo_image, lo_piv_par, 
                                                valid_par, piv_data, lo_piv_data, 
                                                &cum_residu, &cum_residu_reached,
                                                &sum_dxdy, &sum_dxdy_old,
                                                isi_last, grid_last, 
                                                sweep_last, verbose))
                != NULL) {
                g_warning ("gpiv_piv_interrogate_img: %s", err_msg);
                gpiv_free_img (lo_image);
                gpiv_free_pivdata (lo_piv_data);
                gpiv_free_pivdata (piv_data);
                return NULL;
            }

        } else {

            /*
             * Apply results to output piv_data
             */
            gpiv_free_pivdata (piv_data);
            piv_data = gpiv_cp_pivdata (lo_piv_data);
            cum_residu_reached = TRUE;
        }

        /*
         * Adapt grid. 
         * If final grid has been reached, grid_last will be set.
         */
        if (lo_piv_par->int_shift > piv_par->int_shift
            && !sweep_stop) {
            GpivPivData *pd = NULL;

            pd = gpiv_piv_gridadapt (image->header,
                                     piv_par, 
                                     lo_piv_par,
                                     piv_data, 
                                     sweep, 
                                     &grid_last);
            gpiv_free_pivdata (piv_data);
            piv_data = gpiv_cp_pivdata (pd);
            gpiv_free_pivdata (pd);

            gpiv_free_pivdata (lo_piv_data);
            lo_piv_data = gpiv_cp_pivdata (piv_data);

            if (lo_piv_par->int_scheme == GPIV_IMG_DEFORM) {
                gpiv_0_pivdata (lo_piv_data);
            }

        } else {
            grid_last = TRUE;
        }

        /*
         *  Adapt interrogation area size. 
         *  If final size has been reached, isi_last will be set.
         */
        gpiv_piv_isizadapt (piv_par, 
                            lo_piv_par, 
                            &isi_last);
        
        /*
         * Test if all conditions have been reached
         */
        if (cum_residu_reached && isi_last && grid_last) {
            sweep_last = TRUE;
        }

        sweep++;
    }


    /*
     * Writes existing fftw wisdom
     * Cleans up allocated memory
     * and returns resulting PIV data to caller
     */
    gpiv_fwrite_fftw_wisdom (1);
    gpiv_fwrite_fftw_wisdom (-1);
    fftw_forget_wisdom();
#ifdef _OPENMP
    fftw_cleanup_threads();
#else
    fftw_cleanup ();
#endif
    gpiv_free_img (lo_image);
    gpiv_free_pivdata (lo_piv_data);


    if (verbose) printf ("\n");
    return piv_data;
}



gchar *
gpiv_piv_interrogate_ia (const guint index_y,
                         const guint index_x,
                         const GpivImage *image,
                         const GpivPivPar *piv_par,
                         const guint sweep,
                         const guint last_sweep,
                         gfloat **int_area_1,
                         gfloat **int_area_2,
                         GpivCov *cov,
                         GpivPivData *piv_data
                         )
/**----------------------------------------------------------------------------
 *     Interrogates a single Interrogation Area
 */
{
    gchar *err_msg = NULL;

    guint ncolumns = image->header->ncolumns;
    guint nrows = image->header->nrows;
    gboolean x_corr = image->header->x_corr;

    guint ifit = piv_par->ifit;
    guint int_size_f = piv_par->int_size_f;
    guint int_size_i = piv_par->int_size_i;
    gint peak = piv_par->peak;
    int pre_shift_row = piv_par->pre_shift_row;
    int pre_shift_col = piv_par->pre_shift_col;
    enum GpivIntScheme int_scheme = piv_par->int_scheme;

    int return_val;
    int idum = gpiv_max((int_size_i - int_size_f) / 2, 0);
    int m = 0, n = 0;
    float int_area_1_mean = 0.0, int_area_2_mean = 0.0;
/*     BUGFIX: gpiv_piv_interrogate_ia: disabled normalization I.A */
#ifdef NORM_AI
    float int_area_1_range = 0.0, int_area_2_range = 0.0;
    float norm_fact = 0.0;
   guint img_top = (1 << image->header->depth) - 1;
#endif
    int ipoint_x;
    int ipoint_y;

    int pre_shift_row_act = 0, pre_shift_col_act = 0;
    int peak_act = 0, i_skip_act = 0, j_skip_act = 0;

    gboolean flag_subtop = FALSE, flag_intar0 = FALSE, flag_accept = FALSE;
/*
 * Interrogation area with zero padding
 */
    GpivCov *w_k = NULL;                /* covariance weighting kernel */
    int int_size_0 = GPIV_ZEROPAD_FACT * int_size_i;


/*
 * Checking for memory allocation of input variables
 */
    g_return_val_if_fail (image->frame1[0] != NULL, "image->frame1[0] != NULL");
    g_return_val_if_fail (image->frame2[0] != NULL, "image->frame2[0] != NULL");
    g_return_val_if_fail (int_area_1[0] != NULL, "int_area_1[0] != NULL");
    g_return_val_if_fail (int_area_2[0] != NULL, "int_area_2[0] != NULL");
    g_return_val_if_fail (cov != NULL, "cov != NULL");
    g_return_val_if_fail (piv_data->point_x != NULL, "piv_data->point_x != NULL");
    g_return_val_if_fail (piv_data->point_y != NULL, "piv_data->point_y != NULL");
    g_return_val_if_fail (piv_data->dx != NULL, "piv_data->dx != NULL");
    g_return_val_if_fail (piv_data->dy != NULL, "piv_data->dy != NULL");
    g_return_val_if_fail (piv_data->snr != NULL, "piv_data->snr != NULL");
    g_return_val_if_fail (piv_data->peak_no != NULL, "piv_data->peak_no != NULL");

    ipoint_x = (int) piv_data->point_x[index_y][index_x];
    ipoint_y = (int) piv_data->point_y[index_y][index_x];
/*
 * uses  piv values from previous estimation as pre-shifts and
 * searches closest Int. Area
 */
    if (int_scheme == GPIV_ZERO_OFF_FORWARD
        || int_scheme == GPIV_ZERO_OFF_CENTRAL) {
	pre_shift_col_act = piv_data->dx[index_y][index_x] + pre_shift_col;
	pre_shift_row_act = piv_data->dy[index_y][index_x] + pre_shift_row;
        piv_data->dx[index_y][index_x] = 0.0;
        piv_data->dy[index_y][index_x] = 0.0;
    } else {
	pre_shift_col_act = pre_shift_col;
	pre_shift_row_act = pre_shift_row;
    }

    peak_act = peak;


/*     gpiv_warning ("gpiv_piv_interrogate_ia:: 0"); */
/*
 * Assigning image data to the interrogation area's
 */
    if (int_scheme == GPIV_ZERO_OFF_CENTRAL ) {
        flag_accept = assign_img2intarr_central(ipoint_x, ipoint_y,
                                                image->frame1, image->frame2,
                                                int_size_f, int_size_i,
                                                int_area_1, int_area_2,
                                                pre_shift_row_act,
                                                pre_shift_col_act,
                                                nrows,
                                                ncolumns,
                                                int_size_0);

    } else if (int_scheme == GPIV_ZERO_OFF_FORWARD) {
        flag_accept = assign_img2intarr_central(ipoint_x, ipoint_y,
                                                image->frame1, image->frame2,
                                                int_size_f, int_size_i,
                                                int_area_1, int_area_2,
                                                pre_shift_row_act,
                                                pre_shift_col_act,
                                                nrows,
                                                ncolumns,
                                                int_size_0);
    } else {
        flag_accept = assign_img2intarr(ipoint_x, ipoint_y,
                                        image->frame1, image->frame2,
                                        int_size_f, int_size_i,
                                        int_area_1, int_area_2,
                                        pre_shift_row_act,
                                        pre_shift_col_act,
                                        nrows,
                                        ncolumns,
                                        int_size_0);
    }

    if (flag_accept) {

/*
 * Weighting Interrogation Area with Gaussian function
 */
       if (piv_par->gauss_weight_ia) {
            if ((err_msg = ia_weight_gauss (int_size_f, int_area_1))
                != NULL) {
                return (err_msg);
            }

            if ((err_msg = ia_weight_gauss (int_size_i, int_area_2))
                != NULL) {
                return (err_msg);
            }
        }

/*
 * The mean value of the image data within an interrogation area will be
 * subtracted from the data
 * BUXFIX: test on differences in estimator!
 */
/*         int_area_1_meand = int_mean_old(image->frame1, int_size_f, int_size_i,  */
/*                                    ipoint_x, ipoint_y); */
/*         int_area_2_meand = int_mean_old(image->frame2, int_size_i, int_size_i,  */
/*                                    ipoint_x, ipoint_y); */

        int_area_1_mean = int_mean (int_area_1, int_size_f);
        int_area_2_mean = int_mean (int_area_2, int_size_i);
#ifdef NORM_AI
        int_area_1_range = int_range (int_area_1, int_size_f);
        int_area_2_range = int_range (int_area_2, int_size_i);
#endif
/*         g_message(":: sweep = %d int_area_1_mean[%d][%d] = %f int_area_2_mean[%d][%d] = %f", */
/*                   sweep, */
/*                   ipoint_y, ipoint_x, int_area_1_meand,  */
/*                   ipoint_y, ipoint_x, int_area_2_meand); */
/*         g_message(":: sweep = %d int_area_1_mean[%d][%d] = %f int_area_2_mean[%d][%d] = %f", */
/*                   sweep, */
/*                   ipoint_y, ipoint_x, int_area_1_mean,  */
/*                   ipoint_y, ipoint_x, int_area_2_mean); */


/*
 * BUGFIX: this might be substituted by counting the number of particles within
 * Int. Area, as done in PTV
 */
        if (int_area_1_mean == 0.0 || int_area_2_mean == 0.0
            || int_const (int_area_1, int_size_f)
            || int_const (int_area_2, int_size_i)
            ) {
/*             err_msg = "gpiv_piv_interrogate_ia: int_area_1/2_mean = 0.0"; */
            flag_intar0 = TRUE;
/*             return err_msg; */

            }

#ifdef NORM_AI
        norm_fact = (gfloat) img_top / int_area_1_range;
/*         g_message(":: top = %d range = %f ==> fact = %f", */
/*                   img_top, */
/*                   int_area_1_range, */
/*                   norm_fact); */
#endif
#pragma omp parallel for
        for (m = 0; m < int_size_f; m++) {
            for (n = 0; n < int_size_f; n++) {
                int_area_1[m + idum ][n + idum ] -= int_area_1_mean;
#ifdef NORM_AI
                int_area_1[m + idum ][n + idum ] *= norm_fact;
#endif
            }
        }

#ifdef NORM_AI
        norm_fact = (gfloat) img_top / int_area_2_range;
#endif
#pragma omp parallel for
        for (m = 0; m < int_size_i; m++) {
            for (n = 0; n < int_size_i; n++) {
                int_area_2[m][n] -= int_area_2_mean;
#ifdef NORM_AI
                int_area_2[m][n] *= norm_fact;
#endif
            }
        }

/*
 * Calculate covariance function
 */
        if (!flag_intar0) {
            if ((err_msg = cova (int_size_i, int_area_1, int_area_2,
                                 cov, piv_par->spof_filter))
                != NULL) {
                gpiv_warning("%s", err_msg);
                return err_msg;
            }

/*
 * Weighting covariance data with weight kernel
 */
            if (piv_par->int_scheme == GPIV_LK_WEIGHT) {
                w_k = gpiv_alloc_cov (int_size_0, image->header->x_corr);
                piv_weight_kernel_lin (int_size_0, w_k);
                weight_cov (cov, w_k);
                gpiv_free_cov (w_k);
            }

/*
 * Searching maximum peak in covariance function
 */
            if ((return_val = cov_top (*piv_par, piv_data, index_y, index_x,
                                       cov, x_corr, ifit, sweep, last_sweep,
                                       peak, peak_act, pre_shift_row_act,
                                       pre_shift_col_act,
                                       i_skip_act, j_skip_act,
                                       &flag_subtop)) != 0) {
                err_msg = "gpiv_piv_interrogate_ia: Unable to call cov_top";
                gpiv_warning("%s", err_msg);
                return err_msg;
            }

/*
 * Writing values to piv_data
 */
            piv_data->dx[index_y][index_x] =
                (double) pre_shift_col_act + 
                (double) cov->top_x + cov->subtop_x;

            piv_data->dy[index_y][index_x] =
                (double) pre_shift_row_act + 
                (double) cov->top_y + cov->subtop_y;

/*
 * Disabled as outliers are tested after each iteration
 */
/*             if (last_sweep == 1) { */
                piv_data->snr[index_y][index_x] = cov->snr;
                piv_data->peak_no[index_y][index_x] = peak_act;
/*             } */

        }
/*
 * Check on validity of data
 */
        if (isnan(piv_data->dx[index_y][index_x]) != 0
            || isnan(piv_data->dy[index_y][index_x]) != 0
            || isnan(piv_data->snr[index_y][index_x]) != 0
            || flag_subtop
            || flag_intar0
            ) {
            piv_data->dx[index_y][index_x] = 0.0;
            piv_data->dy[index_y][index_x] = 0.0;
            piv_data->snr[index_y][index_x] = GPIV_SNR_NAN;
            piv_data->peak_no[index_y][index_x] = -1;
        }

/*
 * Uses old piv data and sets flag peak_no to -1 if:
 * for zero offsetting: 2nd Interrogation Area is out of image boundaries
 * for zero offsetting with central diff: one of the Interrogation Area's
 * is out of image  boundaries
 */
    } else {
        piv_data->dx[index_y][index_x] = piv_data->dx[index_y][index_x];
        piv_data->dy[index_y][index_x] = piv_data->dy[index_y][index_x];
        piv_data->snr[index_y][index_x] = piv_data->snr[index_y][index_x];
        piv_data->peak_no[index_y][index_x] = -1;

    }

    return err_msg;
}



void
gpiv_piv_isizadapt (const GpivPivPar *piv_par_src,
                    GpivPivPar *piv_par_dest,
                    gboolean *isiz_last
                    )
/*---------------------------------------------------------------------------*/
/**
 *     Adjusts interrogation area sizes. For each interrogation sweep,
 *     (dest) int_size_i is halved, until it reaches (src)
 *     int_size_f. Then, isiz_last is set TRUE, which will avoid
 *     changing the interrogation sizes in next calls.
 *
 *     @param[in] piv_par_src        original parameters
 *     @param[out] piv_par_dest       actual parameters, to be modified during sweeps
 *     @param[out] isiz_last               flag for last interrogation sweep
 *     @return void
 */
/*---------------------------------------------------------------------------*/

{

/*     if (piv_par_dest->int_size_i == piv_par_src->int_size_i) */
/*         piv_par_dest->ad_int = 0; */

/*     if (piv_par_dest->ad_int == 1) { */
    if ((piv_par_dest->int_size_i) / 2 <= piv_par_src->int_size_f) {
        *isiz_last = TRUE;
        piv_par_dest->int_size_f = 
            (piv_par_src->int_size_f - GPIV_DIFF_ISI);
        piv_par_dest->int_size_i = 
            piv_par_src->int_size_f;
    } else {
        piv_par_dest->int_size_f = piv_par_dest->int_size_i / 2;
        piv_par_dest->int_size_i = piv_par_dest->int_size_i / 2;
    }

/*     } else if (piv_par_src->int_scheme == GPIV_ZERO_OFF_FORWARD */
/*                || piv_par_src->int_scheme == GPIV_ZERO_OFF_CENTRAL */
/*                || piv_par_src->int_scheme == GPIV_IMG_DEFORM */
/*                ) { */
/*         *isiz_last = TRUE; */
/*         piv_par_dest->ifit = piv_par_src->ifit; */
/*         piv_par_dest->int_size_f = (piv_par_src->int_size_f -  */
/*                                          GPIV_DIFF_ISI); */
/*         piv_par_dest->int_size_i = piv_par_src->int_size_f; */
/*     } */

}



/* #define SAVE_TMP */

gchar *
gpiv_piv_write_deformed_image (GpivImage *image
                               )
/*-----------------------------------------------------------------------------
 * DESCRIPTION:
 *     Stores deformed image to file system with pre defined name to TMPDIR
 *     and prints message to stdout
 *
 * INPUTS:
 *     img1:                   first image of PIV image pair
 *     img2:                   second image of PIV image pair
 *     image_par:              image parameters to be stored in header
 *     verbose:                prints the storing to stdout
 *
 * OUTPUTS:
 *
 * RETURNS:
 *     char * to NULL on success or *err_msg on failure
 *---------------------------------------------------------------------------*/
{
    gchar *err_msg = NULL;
    gchar *def_img;
    FILE *fp;


    def_img =  g_strdup_printf ("%s%s",  GPIV_DEFORMED_IMG_NAME, 
                                GPIV_EXT_PNG_IMAGE);

#ifdef SAVE_TMP
    if ((fp = my_utils_fopen_tmp (def_img, "wb")) == NULL) {
        err_msg = "gpiv_piv_write_deformed_image: Failure opening for output";
        return err_msg;
    }

    g_message ("gpiv_piv_write_deformed_image: Writing deformed image to: %s",
               g_strdup_printf ("%s/%s/%s", tmp_dir, user_name, def_img));
#else
    fp = fopen (def_img, "wb");
    g_message ("gpiv_piv_write_deformed_image: Writing deformed image to: %s",
               def_img);
#endif
    if ((err_msg = 
         gpiv_write_png_image (fp, image, FALSE)) != NULL) {
        fclose (fp);
        return err_msg;
    }

    fclose(fp);
    g_free (def_img);
    return err_msg;
}

#ifdef SAVE_TMP
#undef SAVE_TMP
#endif



static void
piv_weight_kernel_lin (const guint int_size_0,
                       GpivCov *w_k
                       )
/*-----------------------------------------------------------------------------
 * DESCRIPTION:
 *      Calculate linear weight kernel values for covariance data
 *
 * INPUTS:
 *
 * OUTPUTS:
 *	w_k:            Structure containing weighting data
 *      int_size_0:     zero-padded interrogation size
 *
 * RETURNS:
 *
 *---------------------------------------------------------------------------*/
{
    int i, j;
    int z_rnl = w_k->z_rnl, z_rnh = w_k->z_rnh, z_rpl = w_k->z_rpl,
        z_rph = w_k->z_rph;
    int z_cnl = w_k->z_cnl, z_cnh = w_k->z_cnh, z_cpl = w_k->z_cpl,
        z_cph = w_k->z_rph;


    g_return_if_fail (w_k != NULL);

    for (i = z_rnl; i < z_rnh; i++) {
	for (j = z_cnl; j < z_cnh; j++) {
	    w_k->z[i - int_size_0][j - int_size_0] =
		(1 - abs(z_rnh - i) / (int_size_0 / 2.0)) 
                * (1 - abs(z_cnh - j) / (int_size_0 / 2.0));
	}

	for (j = z_cpl; j < z_cph; j++) {
	    w_k->z[i - int_size_0][j] =
		(1 - abs(z_rnh - i) / (int_size_0 / 2.0)) 
                * (1 - abs(z_cpl - j) / (int_size_0 / 2.0));
	}
    }


    for (i = z_rpl; i < z_rph; i++) {
	for (j = z_cnl; j < z_cnh; j++) {
	    w_k->z[i][j - int_size_0] =
		(1 - abs(z_rpl - i) / (int_size_0 / 2.0)) 
                * (1 - abs(z_cnh - j) / (int_size_0 / 2.0));
	}

	for (j = z_cpl; j < z_cph; j++) {
	    w_k->z[i][j] = (1 - abs(z_rpl - i) / (int_size_0 / 2.0))
		* (1 - abs(z_cpl - j) / (int_size_0 / 2.0));
	}
    }
}



void
write_cov (int int_x,
           int int_y,
           int int_size,
           float **cov_area,
           int weight
           )
/*-----------------------------------------------------------------------------
 * DESCRIPTION:
 *   Prints covariance data
 *
 * INPUTS:
 *   int_x:
 *   int_y
 *   cov_area:
 *   int_size,
 *
 * SOME MNENOSYNTACTICS OF LOCAL VARIABLES:
 *   cov_area:         name of array
 *   r:                row
 *   c:                column
 *   n:                negative displacements ; from 3/4 to 1 of int_size_0
 *   p:                positive displacements; from 0 to 1/4 of int_size_0
 *   l:                lowest index
 *   h:                highest index
 *---------------------------------------------------------------------------*/
{
    int i, j;
    int cov_area_rnl, cov_area_rnh, cov_area_rpl, cov_area_rph,
	cov_area_cnl, cov_area_cnh, cov_area_cpl, cov_area_cph;
    float weight_kernel;
    int int_size_0 = GPIV_ZEROPAD_FACT * int_size;


    cov_area_rnl = 3.0 * (int_size_0) / 4 + 1;
    cov_area_rnh = int_size_0;
    cov_area_rpl = 0;
    cov_area_rph = int_size_0 / 4;

    cov_area_cnl = 3.0 * (int_size_0) / 4 + 1;
    cov_area_cnh = int_size_0;
    cov_area_cpl = 0;
    cov_area_cph = int_size_0 / 4;


    for (i = cov_area_rnl; i < cov_area_rnh; i++) {
	for (j = cov_area_cnl; j < cov_area_cnh; j++) {
	    if (weight == 1) {
		weight_kernel =
		    (1 - abs(cov_area_rnh - i) / (int_size_0 / 2.0)) * 
		  (1 - abs(cov_area_cnh - j) / (int_size_0 / 2.0));
	    }
	}
	for (j = cov_area_cpl; j < cov_area_cph; j++) {
	    if (weight == 1) {
		weight_kernel =
		    (1 - abs(cov_area_rnh - i) / (int_size_0 / 2.0)) * 
		  (1 - abs(cov_area_cpl - j) / (int_size_0 / 2.0));
	    }
	}
    }


    for (i = cov_area_rpl; i < cov_area_rph; i++) {
	for (j = cov_area_cnl; j < cov_area_cnh; j++) {
	    if (weight == 1) {
		weight_kernel =
		    (1 - abs(cov_area_rpl - i) / (int_size_0 / 2.0)) * 
		  (1 - abs(cov_area_cnh - j) / (int_size_0 / 2.0));
	    }
	}
	for (j = cov_area_cpl; j < cov_area_cph; j++) {
	    if (weight == 1) {
		weight_kernel =
		    (1 - abs(cov_area_rpl - i) / (int_size_0 / 2.0)) * 
		  (1 - abs(cov_area_cpl - j) / (int_size_0 / 2.0));
	    }
	}
    }
}



void
gpiv_fread_fftw_wisdom (const gint dir
                        )
/*-----------------------------------------------------------------------------
 * DESCRIPTION:
 *     Reads fftw wisdoms from file and stores into a string
 *
 * INPUTS:
 *     dir:            direction of fft; forward (+1) or inverse (-1)
 *
 * OUTPUTS:
 *
 * RETURNS:
 *     fftw_wisdom
 *---------------------------------------------------------------------------*/
{
    gchar *fftw_filename;
    FILE *fp;


    g_return_if_fail ( dir == 1 || dir == -1);

/*
 * Forward FFT or inverse FFT
 */
    if (dir == 1) {
	fftw_filename = g_strdup_printf ("%s", FFTWISDOM);
    } else {
	fftw_filename = g_strdup_printf ("%s", FFTWISDOM_INV);
    }

    if ((fp = my_utils_fopen_tmp (fftw_filename, "r")) != NULL) {
	fftw_import_wisdom_from_file(fp);
        fclose(fp);
    }

    g_free (fftw_filename);
}



void
gpiv_fwrite_fftw_wisdom (const gint dir
                         )
/*-----------------------------------------------------------------------------
 * DESCRIPTION:
 *      Writes fftw wisdoms to a file
 *
 * INPUTS:
 *      dir:            direction of fft; forward (+1) or inverse (-1)
 *
 * OUTPUTS:
 *
 * RETURNS:
 *
 *---------------------------------------------------------------------------*/
{
    gchar *fftw_filename;
    FILE *fp;
 
    g_return_if_fail ( dir == 1 || dir == -1);

/*
 * Forward FFT or inverse FFT
 */
    if (dir == 1) {
	fftw_filename = g_strdup_printf ("%s", FFTWISDOM);
    } else {
	fftw_filename = g_strdup_printf ("%s", FFTWISDOM_INV);
    }

    if ((fp = my_utils_fopen_tmp (fftw_filename, "w")) != NULL) {
	fftw_export_wisdom_to_file(fp);
	fclose(fp);
    }

    fftw_forget_wisdom();
    g_free (fftw_filename);
}


/*
 * Public functions, original from piv_speed
 */

gchar *
gpiv_piv_dxdy_at_new_grid (const GpivPivData *piv_data_src,
                           GpivPivData *piv_data_dest
                           )
/*---------------------------------------------------------------------------*/
/**
 * calculates dx, dy of piv_data_dest from piv_data_src
 * by bi-linear interpolation of inner points with shifted knots
 * or extrapolation of outer lying points
 *
 *   dist_:      distance
 *   _n:         NORTH
 *   _s:         SOUTH
 *   _e:         EAST
 *   _w:         WEST
 *   _nn:        at NORTH of NORTH, etc.
 *
 *     @param[in] piv_data_src       input piv data
 *     @param[out] piv_data_dest      output piv data
 *     @return NULL on success or *err_msg on failure
 */
/*---------------------------------------------------------------------------*/
{
    char c_line[GPIV_MAX_LINES_C][GPIV_MAX_CHARS];
    char *err_msg = NULL;

    gint *index_n, *index_s, *index_e, *index_w;
    gint *index_nn, *index_ss, *index_ee, *index_ww;

    float *src_point_x = NULL, *dest_point_x = NULL;
    float *src_point_y = NULL, *dest_point_y = NULL;
    double *alpha_hor, *alpha_vert;

    double epsi = 0.01;
    enum VerticalPosition vert_pos;
    enum HorizontalPosition hor_pos;
    gint i = 0, j = 0;

    GpivPivData *gpd = NULL;


/*
 * shift the knots of the grid for higher accuracies.
 * in order not to affect piv_data_src, a new PIV dataset will be copied
 */
#ifdef DEBUG
    g_message ("gpiv_piv_dxdy_at_new_grid:: 0, src_nx = %d src_ny = %d dest_nx = %d dest_ny = %d",
               piv_data_src->nx, piv_data_src->ny,
               piv_data_dest->nx, piv_data_dest->ny);
#endif
    gpd = gpiv_cp_pivdata (piv_data_src);
 

    if ((err_msg = gpiv_piv_shift_grid (gpd)) != NULL) {
        err_msg = "gpiv_piv_dxdy_at_new_grid: failing  gpiv_piv_shift_grid";
        g_warning ("%s", err_msg);
        return err_msg;
    }


    index_n = gpiv_ivector (piv_data_dest->ny);
    index_s = gpiv_ivector (piv_data_dest->ny);
    index_e = gpiv_ivector (piv_data_dest->nx);
    index_w = gpiv_ivector (piv_data_dest->nx);
    index_nn = gpiv_ivector (piv_data_dest->ny);
    index_ss = gpiv_ivector (piv_data_dest->ny);
    index_ee = gpiv_ivector (piv_data_dest->nx);
    index_ww = gpiv_ivector (piv_data_dest->nx);

    alpha_vert = gpiv_dvector (piv_data_dest->ny);
    alpha_hor = gpiv_dvector (piv_data_dest->nx);

    src_point_x = gpiv_vector (gpd->nx);
    src_point_y = gpiv_vector (gpd->ny);
    dest_point_x = gpiv_vector (piv_data_dest->nx);
    dest_point_y = gpiv_vector (piv_data_dest->ny);

/*
 * Calculate interpolation factors
 * in Horizontal direction
 */
#ifdef DEBUG
    g_message ("gpiv_piv_dxdy_at_new_grid:: 1a, gpd_nx = %d gpd_ny = %d _ny",
               gpd->nx, gpd->ny);
#endif
    if (gpd->nx >= NMIN_TO_INTERPOLATE) {
        for (i = 0, j = 0; j < gpd->nx; j++) {
            src_point_x[j] = gpd->point_x[i][j];
       }

        for (i = 0, j = 0; j < piv_data_dest->nx; j++) {
            dest_point_x[j] = piv_data_dest->point_x[i][j];
        }

        intpol_facts (src_point_x, 
                      dest_point_x, 
                      gpd->nx,
                      piv_data_dest->nx,
                      index_w,
                      index_e,
                      index_ww,
                      index_ee,
                      alpha_hor);
    } else {
        err_msg = "gpiv_piv_dxdy_at_new_grid: Not enough points in horizontal direction";
        return err_msg;
    }

/*
 * Calculate interpolation factors
 * in Vertical direction
 */
    if (gpd->ny >= NMIN_TO_INTERPOLATE) {
        for (i = 0, j = 0; i < gpd->ny; i++) {
            src_point_y[i] = gpd->point_y[i][j];
        }

        for (i = 0, j = 0; i < piv_data_dest->ny; i++) {
            dest_point_y[i] = piv_data_dest->point_y[i][j];
        }

        intpol_facts (src_point_y, 
                      dest_point_y, 
                      gpd->ny,
                      piv_data_dest->ny,
                      index_n,
                      index_s,
                      index_nn,
                      index_ss,
                      alpha_vert);
    } else {
        err_msg = "gpiv_piv_dxdy_at_new_grid: Not enough points in horizontal direction";
        return err_msg;
    }

/*
 * Calculate new displacements by bi-lineair interpolation
 */
    for (i = 0; i < piv_data_dest->ny; i++) {
        for (j = 0; j < piv_data_dest->nx; j++) {
            piv_data_dest->dx[i][j] = bilinear_interpol
                (alpha_hor[j],
                 alpha_vert[i],
                 gpd->dx[index_n[i]][index_w[j]],
                 gpd->dx[index_n[i]][index_e[j]],
                 gpd->dx[index_s[i]][index_w[j]],
                 gpd->dx[index_s[i]][index_e[j]]);

#ifdef DEBUG2
g_message ("piv_dxdy_at_new_grid:: alpha_hor[%d]=%f alpha_vert[%d]=%f dx_nw=%f dx_ne=%f dx_sw=%f dx_se=%f => dx=%f",
              j, alpha_hor[j], i, alpha_vert[i],
              gpd->dx[index_n[i]][index_w[j]],
              gpd->dx[index_n[i]][index_e[j]],
              gpd->dx[index_s[i]][index_w[j]],
              gpd->dx[index_s[i]][index_e[j]],
              piv_data_dest->dx[i][j]
              );
#endif

            piv_data_dest->dy[i][j] = bilinear_interpol
                (alpha_hor[j],
                 alpha_vert[i],
                 gpd->dy[index_n[i]][index_w[j]],
                 gpd->dy[index_n[i]][index_e[j]],
                 gpd->dy[index_s[i]][index_w[j]],
                 gpd->dy[index_s[i]][index_e[j]]);

#ifdef DEBUG2
            g_message ("piv_dxdy_at_new_grid:: alpha_hor[%d]=%f alpha_vert[%d]=%f dy_nw=%f dy_ne=%f dy_sw=%f dy_se=%f => dy=%f",
              j, alpha_hor[j], i, alpha_vert[i],
              gpd->dy[index_n[i]][index_w[j]],
              gpd->dy[index_n[i]][index_e[j]],
              gpd->dy[index_s[i]][index_w[j]],
              gpd->dy[index_s[i]][index_e[j]],
              piv_data_dest->dy[i][j]
              );
#endif

        }
    }
    

    gpiv_free_ivector (index_n);
    gpiv_free_ivector (index_s);
    gpiv_free_ivector (index_e);
    gpiv_free_ivector (index_w);
    gpiv_free_ivector (index_nn);
    gpiv_free_ivector (index_ss);
    gpiv_free_ivector (index_ee);
    gpiv_free_ivector (index_ww);

    gpiv_free_dvector (alpha_vert);
    gpiv_free_dvector (alpha_hor);

    gpiv_free_vector (src_point_x);
    gpiv_free_vector (src_point_y);
    gpiv_free_vector (dest_point_x);
    gpiv_free_vector (dest_point_y);

    gpiv_free_pivdata (gpd);

    return err_msg;
}


gchar *
gpiv_piv_shift_grid (GpivPivData *gpd_src
                     )
/*---------------------------------------------------------------------------*/
/**
 * shifts the knots of a 2-dimensional grid containing PIV data for improved 
 * (bi-linear) interpolation
 *
 * See: T. Blu, P. Thevenaz, "Linear Interpolation Revitalized",
 * IEEE Trans. in Image Processing, vol13, no 5, May 2004
 *
 *     @param[in] piv_data_src   input piv data
 *     @return NULL on success or *err_msg on failure
 */
/*---------------------------------------------------------------------------*/
{
#define SHIFT 0.2

    char *err_msg = NULL;
    GpivPivData *h_gpd = NULL;
    GpivPivData *v_gpd = NULL;
    gfloat fact1 = -SHIFT / (1.0 - SHIFT);
    gfloat fact2 = 1.0 / (1 - SHIFT);
    gfloat **cx, **cy;
    gfloat delta = 0.0;
    gint i, j;


    delta = gpd_src->point_x[0][1] - gpd_src->point_x[0][0];

/*
 * Shift in horizontal (column-wise) direction
 */
    h_gpd = gpiv_alloc_pivdata (gpd_src->nx, gpd_src->ny);


    for (i = 0; i < gpd_src->ny; i++) {
        for (j = 0; j < gpd_src->nx; j++) {
/*
 * Shift the knot (sample points)
 */
            h_gpd->point_x[i][j] = gpd_src->point_x[i][j] + SHIFT * delta;
            h_gpd->point_y[i][j] = gpd_src->point_y[i][j];
            if (j == 0) {
                h_gpd->dx[i][j] = gpd_src->dx[i][j];
                h_gpd->dy[i][j] = gpd_src->dy[i][j];
            } else {
/*
 * Calculate value at shifted knot
 */
                h_gpd->dx[i][j] = fact1 * h_gpd->dx[i][j-1] + fact2 * 
                    gpd_src->dx[i][j];
                h_gpd->dy[i][j] = fact1 * h_gpd->dy[i][j-1] + fact2 * 
                    gpd_src->dy[i][j];
            }
        }
    }
    

/*
 * Shift in vertical (row-wise) direction by using the horizontal shifted nodes
 */
    v_gpd = gpiv_alloc_pivdata (gpd_src->nx, gpd_src->ny);


    for (i = 0; i < gpd_src->ny; i++) {
        for (j = 0; j < gpd_src->nx; j++) {
            v_gpd->point_x[i][j] = h_gpd->point_x[i][j];
            v_gpd->point_y[i][j] = h_gpd->point_y[i][j] + SHIFT * delta;
            if (i == 0) {
                v_gpd->dx[i][j] = h_gpd->dx[i][j];
                v_gpd->dy[i][j] = h_gpd->dy[i][j];
            } else {
                v_gpd->dx[i][j] = fact1 * v_gpd->dx[i-1][j] + fact2 * 
                    h_gpd->dx[i][j];
                v_gpd->dy[i][j] = fact1 * v_gpd->dy[i-1][j] + fact2 * 
                    h_gpd->dy[i][j];
            }
        }
    }
    

/*     gpiv_free_pivdata (gpd_src); */
/*     gpd_src = gpiv_cp_pivdata (v_gpd); */

    for (i = 0; i < gpd_src->ny; i++) {
        for (j = 0; j < gpd_src->nx; j++) {
            gpd_src->point_x[i][j] = v_gpd->point_x[i][j];
            gpd_src->point_y[i][j] = v_gpd->point_y[i][j];
            gpd_src->dx[i][j] = v_gpd->dx[i][j];
            gpd_src->dy[i][j] = v_gpd->dy[i][j];
            gpd_src->snr[i][j] = v_gpd->snr[i][j];
            gpd_src->peak_no[i][j] = v_gpd->peak_no[i][j];
        }
    }

/*     gpiv_write_pivdata (NULL, gpd_src, FALSE); */


    gpiv_free_pivdata (h_gpd);
    gpiv_free_pivdata (v_gpd);
    return err_msg;
#undef SHIFT
}



GpivPivData *
gpiv_piv_gridgen (const guint nx,
                  const guint ny,
                  const GpivImagePar *image_par,
                  const GpivPivPar *piv_par
                  )
/*-----------------------------------------------------------------------------
 * DESCRIPTION:
 *     Generates grid by Calculating the positions of interrogation areas
 *     Substitutes gpiv_piv_select_int_point
 *
 * INPUTS:
 *     nx               number of columns
 *     ny               number of rows
 *     @image_par:      structure of image parameters
 *     @piv_par:   structure of piv pivuation parameters
 *
 * OUTPUTS:
 *     @out_data:       output piv data from image analysis
 *
 * RETURNS:
 *     %char * NULL on success or *err_msg on failure
 *---------------------------------------------------------------------------*/
{
    GpivPivData *piv_data = NULL;
    gchar *err_msg = NULL;
    int row, column, row_1, column_1, i, j;
    int row_max, row_min, column_max, column_min;

    int ncolumns = image_par->ncolumns;
    int nrows = image_par->nrows;

    int int_geo = piv_par->int_geo;
    int row_start = piv_par->row_start;
    int row_end = piv_par->row_end;
    int col_start = piv_par->col_start;
    int col_end= piv_par->col_end;
    int int_line_col = piv_par->int_line_col;
    int int_line_col_start = piv_par->int_line_col_start;
    int int_line_col_end = piv_par->int_line_col_end;
    int int_line_row = piv_par->int_line_row;
    int int_line_row_start = piv_par->int_line_row_start;
    int int_line_row_end = piv_par->int_line_row_end;
    int int_point_col = piv_par->int_point_col;
    int int_point_row = piv_par->int_point_row;
    int int_size_f = piv_par->int_size_f;
    int int_size_i = piv_par->int_size_i;
    int int_shift = piv_par->int_shift;
    int pre_shift_row = piv_par->pre_shift_row;
    int pre_shift_col = piv_par->pre_shift_col;
				 

/*     g_return_val_if_fail (piv_data->point_x != NULL, "piv_data->point_x != NULL"); */
/*     g_return_val_if_fail (piv_data->point_y != NULL, "piv_data->point_y != NULL"); */

    row_min = gpiv_min (-int_size_f / 2 + 1, 
                        pre_shift_row - int_size_i / 2 + 1);
    column_min = gpiv_max (-int_size_f / 2 + 1, 
                           pre_shift_col - int_size_i / 2 + 1);
    row_max = gpiv_max (int_size_f / 2, pre_shift_row + int_size_i / 2);
    column_max = gpiv_max (int_size_f / 2, pre_shift_col + int_size_i / 2);


/*
 * Creates piv_data and centre points for one single interrogation area
 */
    piv_data = gpiv_alloc_pivdata (nx, ny);

    if (int_geo == GPIV_POINT) {
        piv_data->point_y[0][0] = int_point_row;
        piv_data->point_x[0][0] = int_point_col;
            

/*
 * Creates centre points for one single row
 */
    } else if (int_geo == GPIV_LINE_R) {
        if ((int_size_f - int_size_i) / 2 + pre_shift_col < 0) {
            column_1 = int_line_col_start - 
                ((int_size_f - int_size_i) / 2 +
                 pre_shift_col) + int_size_f / 2 - 1;
        } else {
            column_1 = int_line_col_start + int_size_f / 2 - 1;
        }

        for (i = 0, j = 0, row = int_line_row, column = column_1;
             j < piv_data->nx; j++, column += int_shift) {
            piv_data->point_y[i][j] = row;
            piv_data->point_x[i][j] = column;
        }


/*
 * Creates centre points for one single column
 */
    } else  if (int_geo == GPIV_LINE_C) {
        if ((int_size_f - int_size_i) / 2 + pre_shift_row < 0) {
            row_1 = int_line_row_start - 
                ((int_size_f - int_size_i) / 2 +
                 pre_shift_row) + int_size_f / 2 - 1;
        } else {
            row_1 = int_line_row_start + int_size_f / 2 - 1;
        }

        for (i = 0, j = 0, column = int_line_col, row = row_1; 
             i < piv_data->ny; i++, row += int_shift) {
            piv_data->point_y[i][j] = row;
            piv_data->point_x[i][j] = column;
        }


/*
 * Creates an array of  centre points of the Interrrogation Area's: 
 * int_ar_x and int_ar_y within the defined region of the image
 */
    } else if (int_geo == GPIV_AOI) {
	if ((int_size_f - int_size_i) / 2 + pre_shift_row < 0) {
	    row_1 =
		row_start - ((int_size_f - int_size_i) / 2 +
			     pre_shift_row) + int_size_f / 2 - 1;
	} else {
	    row_1 = row_start + int_size_f / 2 - 1;
	}

	if ((int_size_f - int_size_i) / 2 + pre_shift_col < 0) {
	    column_1 =
		col_start - ((int_size_f - int_size_i) / 2 +
			     pre_shift_col) + int_size_f / 2 - 1;
	} else {
	    column_1 = col_start + int_size_f / 2 - 1;
	}

	for (i = 0, row = row_1; i < ny; i++, row += int_shift) {
	    for (j = 0, column = column_1; j < nx;
		 j++, column += int_shift) {
		piv_data->point_y[i][j] = row;
		piv_data->point_x[i][j] = column;
	    }
	}
    } else {
        err_msg = "gpiv_piv_gridgen: should not arrive here";
        gpiv_warning ("%s", err_msg);
        return NULL;
    }


    return piv_data;
}



GpivPivData *
gpiv_piv_gridadapt (const GpivImagePar *image_par, 
                    const GpivPivPar *piv_par_src,
                    GpivPivPar *piv_par_dest,
                    const GpivPivData *piv_data,
                    const guint sweep, 
                    gboolean *grid_last
                    )
/*-----------------------------------------------------------------------------
 * DESCRIPTION:
 *     Adjust grid nodes if zero_off or adaptive interrogation 
 *     area has been used. This is performed by modifying int_shift equal 
 *     to int_shift / GPIV_SHIFT_FACTOR , until it reaches (src)
 *     int_shift. Then, grid_last is set TRUE, which will avoid
 *     changing the interrogation shift in next calls and signal the
 *     (while loop in) the calling function.
 *     
 * INPUTS:
 *     @image_par:                 image parameters
 *     @piv_par_src:               piv parameters
 *     @piv_data:                  input PIV data
 *     @sweep:                     interrogation sweep step
 *
 * OUTPUTS:
 *     @image_par:                image parameters
 *     @piv_par_dest:             modified piv parameters
 *     @grid_last:                flag if final grid refinement has been 
 *                                reached
 *
 * RETURNS:
 *     piv_data:                 modified PIV data
 *---------------------------------------------------------------------------*/
{
    GpivPivData *pd = NULL;
    gint local_int_shift, local_int_size_f, local_int_size_i;
    gint LOCAL_SHIFT_FACTOR = 2;

    guint nx, ny;


    local_int_shift = piv_par_dest->int_shift / LOCAL_SHIFT_FACTOR;
    if (local_int_shift <= piv_par_src->int_shift) {
        *grid_last = TRUE;
    }

    if (*grid_last == FALSE) {
/*
 * - renew grid of PIV dataset 
 * - calculate displacements at new grid points
 */
        piv_par_dest->int_shift = piv_par_dest->int_shift / 
            LOCAL_SHIFT_FACTOR;
        gpiv_piv_count_pivdata_fromimage (image_par, piv_par_dest, &nx, &ny);
        pd = gpiv_piv_gridgen (nx, ny, image_par, piv_par_dest);
        gpiv_piv_dxdy_at_new_grid (piv_data, pd);

    } else {
/*
 * reset int_shift (and data positions) to the originally defined 
 * parameter value.
 * For the last grid adaption, the number of interrogation area's may 
 * not have been doubled perse, as int_size may be of 
 * arbitrary quantity. 
 */

        piv_par_dest->int_shift =  piv_par_src->int_shift;
/*
 * Set int_size_f and int_size_i of piv_par_dest temporarly to the
 * original settings, so that an identic grid will be constructued as
 * during the gpiv_gridgen call.
 */
        local_int_size_f =  piv_par_dest->int_size_f;
        local_int_size_i =  piv_par_dest->int_size_i;
        piv_par_dest->int_size_f = piv_par_src->int_size_f;
        piv_par_dest->int_size_i = piv_par_src->int_size_i;
        gpiv_piv_count_pivdata_fromimage (image_par, piv_par_dest, &nx, &ny);
        pd = gpiv_piv_gridgen (nx, ny, image_par, piv_par_dest);
        piv_par_dest->int_size_f = local_int_size_f;
        piv_par_dest->int_size_i = local_int_size_i;

        gpiv_piv_dxdy_at_new_grid (piv_data, pd);
    }


    return pd;    
}


/*
 * Local functions
 */

static GpivPivData *
alloc_pivdata_gridgen (const GpivImagePar *image_par, 
                       const GpivPivPar *piv_par
                       )
/*-----------------------------------------------------------------------------
 * Determines the number of grid points, allocating memory for output 
 * data and generates the grid
 */
{
    GpivPivData *piv_data = NULL;
    gchar *err_msg = NULL;
    GpivPivPar *lo_piv_par = NULL;
    guint nx, ny;

    if ((lo_piv_par = gpiv_piv_cp_parameters (piv_par)) == NULL) {
        gpiv_error ("LIBGPIV internal error: alloc_pivdata_gridgen: failing gpiv_piv_cp_parameters");
    }

    if (piv_par->int_size_i > piv_par->int_size_f
        && piv_par->int_shift < piv_par->int_size_i / GPIV_SHIFT_FACTOR) { 
        lo_piv_par->int_shift = lo_piv_par->int_size_i / GPIV_SHIFT_FACTOR;
    }

    if ((err_msg = 
         gpiv_piv_count_pivdata_fromimage (image_par, lo_piv_par, &nx, &ny))
        != NULL) {
        g_message ("LIBGPIV internal error: alloc_pivdata_gridgen: %s", err_msg);
        return NULL;
    }

    
    if ((piv_data = 
         gpiv_piv_gridgen (nx, ny, image_par, lo_piv_par))
        == NULL) {
        g_message ("LIBGPIV internal error: alloc_pivdata_gridgen: failing gpiv_piv_gridgen");
        return NULL;
    }
    

    return piv_data;
}



static void 
report_progress (gint *progress_old,
                 gint index_y,
                 gint index_x,
                 GpivPivData *piv_data,
                 GpivPivPar *piv_par,
                 gint sweep,
                 gfloat cum_residu
                 )
/*-----------------------------------------------------------------------------
 * Printing the progress (between 0 and 100) of piv interrogation to stdout
 */
{
    gint progress  = 100 * (index_y * piv_data->nx + index_x + 1) / 
        (piv_data->nx * piv_data->ny); 

#ifdef ENABLE_MPI
    gint rank, size;
#endif


    if (progress != *progress_old) {
        *progress_old = progress;
                            
        if (index_y > 0 || index_x > 0)
            printf ("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b");

        if (piv_par->int_scheme == GPIV_ZERO_OFF_FORWARD
            || piv_par->int_scheme == GPIV_ZERO_OFF_CENTRAL
            || piv_par->int_scheme == GPIV_ZERO_OFF_CENTRAL
            || piv_par->int_scheme == GPIV_IMG_DEFORM
            || piv_par->int_size_i > piv_par->int_size_f) {
            printf
                ("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b"
                 "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b"
                 "\b\b\b\b\b\b\b\b\b\b\b"
                 "\b\b\b\b\b\b\b\b\b\b\b\b\b\b"
                 );
#ifdef ENABLE_MPI
            MPI_Comm_rank(MPI_COMM_WORLD, &rank);
            MPI_Comm_size(MPI_COMM_WORLD, &size); 
            printf ("\b\b\b\b\b\b\b\b\b\b\b\b");
            printf ("rank %2d/%2d, ", rank,size);
#endif
            printf ("sweep #%2d, int_size = %d int_shift = %d residu = %.3f: ", 
                    sweep, piv_par->int_size_f, piv_par->int_shift, 
                    cum_residu);
        }

        printf ("%3d %%", progress);
        fflush (stdout);
    }
}



static gboolean
assign_img2intarr (gint ipoint_x,
                   gint ipoint_y,
                   guint16 **img_1,
                   guint16 **img_2,
                   gint int_size_f,
                   gint int_size_i,
                   gfloat **int_area_1,
                   gfloat **int_area_2,
                   gint pre_shift_row,
                   gint pre_shift_col,
                   gint nrows,
                   gint ncolumns,
                   gint int_size_0
                   )
/*-----------------------------------------------------------------------------
 * Assigns image data to the interrogation area arrays in a straightforward way
 */
{
    gint m, n;
    gint arg_int1_r = ipoint_y  - int_size_f / 2 + 1;
    gint arg_int1_c = ipoint_x  - int_size_f / 2 + 1;
    gint arg_int2_r = ipoint_y  - int_size_i / 2 + 1;
    gint arg_int2_c = ipoint_x  - int_size_i / 2 + 1;

    gboolean flag_valid;


    assert (img_1[0] != NULL);
    assert (img_2[0] != NULL);
    assert (int_area_1[0] != NULL);
    assert (int_area_2[0] != NULL);

/*
 * Check if Interrogation Areas are within the image boundaries.
 * Principally arg_int1_r,c don't have to be tested as 
 * int_size_i >= int_size_f, but has been kept to maintain generallity with the
 * other assign_img2intarr* functions
 */
    if ((arg_int1_r) >= 0
         && (arg_int1_r + int_size_f - 1) < nrows
         && (arg_int1_c) >= 0
         && (arg_int1_c + int_size_f - 1) < ncolumns

         && (arg_int2_r) >= 0
         && (arg_int2_r + int_size_i - 1) < nrows
         && (arg_int2_c) >= 0
         && (arg_int2_c + int_size_i - 1) < ncolumns) {
        flag_valid = TRUE;

    } else {
        flag_valid = FALSE;
    }


    if (flag_valid == TRUE) {
/*
 * reset int_area_1, int_area_2 values
 */
        memset(int_area_1[0], 0.0, (sizeof(gfloat)) * int_size_0 * int_size_0);
        memset(int_area_2[0], 0.0, (sizeof(gfloat)) * int_size_0 * int_size_0);

        for (m = 0; m < int_size_f; m++) {
            for (n = 0; n < int_size_f; n++) {
                int_area_1[m][n] =
                    (float) img_1[m + arg_int1_r][n + arg_int1_c];
            }
        }

        for (m = 0; m < int_size_i; m++) {
            for (n = 0; n < int_size_i; n++) {
                int_area_2[m][n] =
                    (float) img_2[m + arg_int2_r][n + arg_int2_c];
            }
        }
    }


    return flag_valid;
}



static gboolean
assign_img2intarr_central (gint ipoint_x,
                           gint ipoint_y,
                           guint16 **img_1,
                           guint16 **img_2,
                           gint int_size_f,
                           gint int_size_i,
                           gfloat **int_area_1,
                           gfloat **int_area_2,
                           gint pre_shift_row,
                           gint pre_shift_col,
                           gint nrows,
                           gint ncolumns,
                           gint int_size_0
                           )
/*-----------------------------------------------------------------------------
 * Assigns image data to the interrogation area arrays using the central 
 * differential scheme
 */
{
    gint m, n;
    gint idum = gpiv_max((int_size_i - int_size_f) / 2, 0);
    gint arg_int1_r = ipoint_y - int_size_f / 2 + 1 - pre_shift_row / 2 -
        pre_shift_row % 2;
    gint arg_int1_c = ipoint_x - int_size_f / 2 + 1 - pre_shift_col / 2 -
        pre_shift_col % 2;
    gint arg_int2_r = ipoint_y - int_size_i / 2 + 1 + pre_shift_row / 2;
    gint arg_int2_c = ipoint_x - int_size_i / 2 + 1 + pre_shift_col / 2;
    gboolean flag_valid;


    assert (img_1[0] != NULL);
    assert (img_2[0] != NULL);
    assert (int_area_1[0] != NULL);
    assert (int_area_2[0] != NULL);
/*
 * Check if Interrogation Areas are within the image boundaries.
 */
     if ((arg_int1_r) >= 0
         && (arg_int1_r + int_size_f - 1) < nrows
         && (arg_int1_c) >= 0
         && (arg_int1_c + int_size_f - 1) < ncolumns

         && (arg_int2_r) >= 0
         && (arg_int2_r + int_size_i - 1) < nrows
         && (arg_int2_c) >= 0
         && (arg_int2_c + int_size_i - 1) < ncolumns) {
         flag_valid = TRUE;
     } else {
         flag_valid = FALSE;
     }


    if (flag_valid == TRUE) {
/*
 * reset int_area_1, int_area_2 values
 */
        memset(int_area_1[0], 0.0, (sizeof(gfloat)) * int_size_0 * int_size_0);
        memset(int_area_2[0], 0.0, (sizeof(gfloat)) * int_size_0 * int_size_0);

        for (m = 0; m < int_size_f; m++) {
            for (n = 0; n < int_size_f; n++) {
                int_area_1[m + idum][n + idum] =
                    (float) img_1[m + arg_int1_r][n + arg_int1_c];
            }
        }


        for (m = 0; m < int_size_i; m++) {
            for (n = 0; n < int_size_i; n++) {
                int_area_2[m][n] =
                    (float) img_2[m + arg_int2_r][n + arg_int2_c];
            }
        }

    }


    return flag_valid;
}



static gboolean
assign_img2intarr_forward (gint ipoint_x,
                           gint  ipoint_y,
                           guint16 **img_1,
                           guint16 **img_2,
                           gint int_size_f,
                           gint int_size_i,
                           gfloat **int_area_1,
                           gfloat **int_area_2,
                           gint pre_shift_row,
                           gint pre_shift_col,
                           gint nrows,
                           gint ncolumns,
                           gint int_size_0
                           )
/*-----------------------------------------------------------------------------
 * Assigns image data to the interrogation area arrays for forward differential
 * scheme
 */
{
    gint m, n;
    gint idum = gpiv_max((int_size_i - int_size_f) / 2, 0);
    gint arg_int1_r = ipoint_y - int_size_f / 2 + 1 + pre_shift_row + idum;
    gint arg_int1_c = ipoint_x - int_size_f / 2 + 1 + pre_shift_col + idum;
    gint arg_int2_r = ipoint_y - int_size_i / 2 + 1 + pre_shift_row;
    gint arg_int2_c = ipoint_x - int_size_i / 2 + 1 + pre_shift_col;
    gboolean flag_valid;


    assert (img_1[0] != NULL);
    assert (img_2[0] != NULL);
    assert (int_area_1[0] != NULL);
    assert (int_area_2[0] != NULL);
/*
 * Check if Interrogation Areas are within the image boundaries.
 */
    if ((arg_int1_r) >= 0
        && (arg_int1_r + int_size_f - 1) < nrows
        && (arg_int1_c) >= 0
        && (arg_int1_c  + int_size_f - 1) < ncolumns

        && (arg_int2_r) >= 0
        && (arg_int2_r + int_size_i - 1) < nrows
        && (arg_int2_c) >= 0
        && (arg_int2_c  + int_size_i - 1) < ncolumns) {
        flag_valid = TRUE;
    } else {
        flag_valid = FALSE;
    }


    if (flag_valid == TRUE) {
/*
 * reset int_area_1, int_area_2 values
 */
        memset(int_area_1[0], 0.0,
               (sizeof(float)) * int_size_0 * int_size_0);
        memset(int_area_2[0], 0.0,
               (sizeof(float)) * int_size_0 * int_size_0);

        for (m = 0; m < int_size_f; m++) {
            for (n = 0; n < int_size_f; n++) {
                int_area_1[m + idum][n + idum] =
                    (float) img_1[m + arg_int1_r][n + arg_int1_c];
            }
        }


        for (m = 0; m < int_size_i; m++) {
            for (n = 0; n < int_size_i; n++) {
                int_area_2[m][n] =
                    (float) img_2[m + arg_int2_r][n + arg_int2_c];
            }
        }

    }


    return flag_valid;
}



static float
int_mean_old (guint16 **img,
              int int_size,
              int int_size_i,
              int ipoint_x,
              int ipoint_y
              )
/* ----------------------------------------------------------------------------
 * calculates mean image value from which image data are taken
 */
{
    int m = 0, n = 0, idum = gpiv_max((int_size_i - int_size) / 2, 0);
    int int_area_sum = 0;
    float mean;


    assert (img[0] != NULL);

    for (m = 0; m < int_size; m++) {
        for (n = 0; n < int_size; n++) {
            int_area_sum +=
                img[m + ipoint_y - int_size_i / 2 + 1 + idum]
                [n + ipoint_x - int_size_i / 2 + 1 + idum];
        }
    }

    mean = int_area_sum / (int_size * int_size);


    return mean;
}



static gfloat
int_mean (gfloat **int_area,
          gint int_size
          )
/* ----------------------------------------------------------------------------
 * calculates mean value from interrogation area intensities
 */
{
    int m = 0, n = 0;
    gfloat int_area_sum = 0;
    gfloat mean = 0.0;


    assert (int_area[0] != NULL);

    for (m = 0; m < int_size; m++) {
        for (n = 0; n < int_size; n++) {
            int_area_sum += int_area[m][n];
        }
    }

    mean = int_area_sum / (int_size * int_size);


    return mean;
}



static gfloat
int_range (gfloat **int_area,
          gint int_size
          )
/* ----------------------------------------------------------------------------
 * calculates range of values from interrogation area intensities
 */
{
    int m = 0, n = 0;
    gfloat int_area_sum = 0;
    gfloat min = 10.0e9, max = -10.0e9, range = 0.0;


    assert (int_area[0] != NULL);

    for (m = 0; m < int_size; m++) {
        for (n = 0; n < int_size; n++) {
            if (int_area[m][n] > max) max = int_area[m][n];
            if (int_area[m][n] < min) min = int_area[m][n];
        }
    }

    range = max - min;


    return range;
}



static gboolean
int_const (gfloat **int_area,
           const guint int_size
           )
/* ----------------------------------------------------------------------------
 * Tests if all intesities values with an interrogation area are equal
 */
{
    int m = 0, n = 0;
    gboolean flag = TRUE;
    gfloat val;


    assert (int_area[0] != NULL);

    val = int_area[0][0];
    for (m = 1; m < int_size; m++) {
        for (n = 1; n < int_size; n++) {
            if (int_area[m][n] != val) flag = FALSE;
        }
    }


    return flag;
}



static void
cov_min_max (GpivCov *cov
             )
/* ----------------------------------------------------------------------------
 * calculates minimum and maximum in cov
 */
{
    gfloat max = -10.0e+9, min = 10.0e+9;
    gint z_rl = cov->z_rl, z_rh = cov->z_rh, z_cl = cov->z_cl,
        z_ch = cov->z_ch;
    gint i, j;


    for (i = z_rl + 1; i < z_rh - 1; i++) {
        for (j = z_cl + 1; j < z_ch - 1; j++) {
	    if (cov->z[i][j] > max) max = cov->z[i][j];
	    if (cov->z[i][j] < min) min = cov->z[i][j];
        }
    }

    cov->min = min;
    cov->max = max;
}


static void
search_top (GpivCov *cov,
            gint peak_act,
            gint x_corr,
            gint sweep,
            gint i_skip_act,
            gint j_skip_act,
            float *z_max,
            long *i_max,
            long *j_max
            )
/* ----------------------------------------------------------------------------
 * searches top in cov. function
 */
{
    gint h, i, j;
    gint z_rl = cov->z_rl, z_rh = cov->z_rh, z_cl = cov->z_cl,
        z_ch = cov->z_ch;


    for (h = 1; h <= peak_act + 1; h++) {
	z_max[h] = -1.0;
	i_max[h] = -2;
	j_max[h] = -3;
    }

    for (h = 1; h <= peak_act; h++) {
	for (i = z_rl + 1; i < z_rh - 1; i++) {
	    for (j = z_cl + 1; j < z_ch - 1; j++) {

		if (x_corr == 1 || (sweep == 0 || (i != i_skip_act ||
						   j != j_skip_act))) {
		    if (h == 1
			|| (h == 2
			    && (i != i_max[1] || j != j_max[1]))
			|| (h == 3
			    && (i != i_max[1] || j != j_max[1])
			    && (i != i_max[2] || j != j_max[2]))) {
			if (cov->z[i][j] > z_max[h]) {
			    if ((cov->z[i][j] >= cov->z[i - 1][j]) &&
				(cov->z[i][j] >= cov->z[i + 1][j]) &&
				(cov->z[i][j] >= cov->z[i][j - 1]) &&
				(cov->z[i][j] >= cov->z[i][j + 1])) {
				z_max[h] = cov->z[i][j];
				i_max[h] = i;
				j_max[h] = j;
			    }
			}
		    }

		}
	    }
	}
    }
}



static char *
cov_subtop (float **z,
            long *i_max,
            long *j_max,
            float *epsi_x,
            float *epsi_y,
            int ifit,
            int peak_act
            )
/*-----------------------------------------------------------------------------
 * Calculates particle displacements at sub-pixel level
 */
{
    char *err_msg = NULL;
    double A_log, B_log, C_log;
    double min = 10e-3;
    gboolean flag = TRUE;


    if (ifit == GPIV_GAUSS) {
/*
 * sub-pixel estimator by gaussian fit
 */
/*         g_message ("cov_subtop:: z = %f", z[i_max[peak_act]][j_max[peak_act]]); */
        if (z[i_max[peak_act]][j_max[peak_act]] > min) {
            C_log = log((double) z[i_max[peak_act]][j_max[peak_act]]);
/*         g_message ("cov_subtop:: C_log"); */
        } else {
            flag = FALSE;
        }

        if (flag && z[i_max[peak_act] - 1][j_max[peak_act]] > min) {
            A_log = log((double) z[i_max[peak_act] - 1][j_max[peak_act]]);
/*             g_message ("cov_subtop:: A_log"); */
        } else {
            flag = FALSE;
        }

        if (flag && z[i_max[peak_act] + 1][j_max[peak_act]] > min) {
            B_log = log((double) z[i_max[peak_act] + 1][j_max[peak_act]]);
/*             g_message ("cov_subtop:: B_log"); */
        } else {
            flag = FALSE;
        }

        if (flag && (2 * (A_log + B_log - 2 * C_log)) != 0.0) {
            *epsi_y = (A_log - B_log) / (2 * (A_log + B_log - 2 * C_log));
        } else {
            *epsi_y = 0.0;
            peak_act = -1;
            err_msg = "epsi_y = 0.0";
/*             g_message ("cov_subtop:: %s", err_msg); */
            flag = FALSE;
        }


        if (flag && z[i_max[peak_act]][j_max[peak_act] - 1] != 0.0) {
            A_log = log((double) z[i_max[peak_act]][j_max[peak_act] - 1]);
        } else {
            flag = FALSE;
        }

        if (flag && z[i_max[peak_act]][j_max[peak_act] + 1] != 0.0) {
            B_log = log((double) z[i_max[peak_act]][j_max[peak_act] + 1]);
        } else {
            flag = FALSE;
        }

        if (flag && (2 * (A_log + B_log - 2 * C_log)) != 0.0) {
            *epsi_x = (A_log - B_log) / (2 * (A_log + B_log - 2 * C_log));
        } else {
            *epsi_x = 0.0;
            peak_act = -1;
            err_msg = "epsi_x = 0.0";
/*             g_message ("cov_subtop:: %s", err_msg); */
            flag = FALSE;
        }


    } else if (ifit == GPIV_POWER) {
/*
 * sub-pixel estimator by quadratic fit
 */
	*epsi_y = (z[i_max[peak_act] - 1][j_max[peak_act]] -
		   z[i_max[peak_act] + 1][j_max[peak_act]]) /
	    (2 * (z[i_max[peak_act] - 1][j_max[peak_act]] +
		  z[i_max[peak_act] + 1][j_max[peak_act]] -
		  2 * z[i_max[peak_act]][j_max[peak_act]]));

	*epsi_x = (z[i_max[peak_act]][j_max[peak_act] - 1] -
		   z[i_max[peak_act]][j_max[peak_act] + 1]) /
	    (2 * (z[i_max[peak_act]][j_max[peak_act] - 1] +
		  z[i_max[peak_act]][j_max[peak_act] + 1] -
		  2 * z[i_max[peak_act]][j_max[peak_act]]));


    } else if (ifit == GPIV_GRAVITY) {
/*
 * sub-pixel estimator by centre of gravity
 */
	*epsi_y = (z[i_max[peak_act] - 1][j_max[peak_act]] -
		   z[i_max[peak_act] + 1][j_max[peak_act]]) /
	    (z[i_max[peak_act] - 1][j_max[peak_act]] +
	     z[i_max[peak_act] + 1][j_max[peak_act]] +
	     z[i_max[peak_act]][j_max[peak_act]]);

	*epsi_x = (z[i_max[peak_act]][j_max[peak_act] - 1] -
		   z[i_max[peak_act]][j_max[peak_act] + 1]) /
	    (z[i_max[peak_act]][j_max[peak_act] - 1] +
	     z[i_max[peak_act]][j_max[peak_act] + 1] +
	     z[i_max[peak_act]][j_max[peak_act]]);


    } else {
	err_msg = "LIBGPIV internal error: cov_subtop: invalid fit parameter";
        gpiv_warning("%s", err_msg);
        return err_msg;
    }

/*     fprintf (stderr, "LIBGPIV cov_subtop:: epsi_y = %f epsi_x = %f\n", */
/*              *epsi_y, *epsi_x); */


        return err_msg;
}



static int
cov_top (GpivPivPar piv_par,
         GpivPivData * piv_data,
         int index_y,
         int index_x,
         GpivCov *cov,
         int x_corr,
         int ifit,
         int sweep,
         int last_sweep,
         int peak,
         int peak_act,
         int pre_shift_row_act,
         int pre_shift_col_act,
         int i_skip_act,
         int j_skip_act,
         gboolean *flag_subtop
         )
/* ----------------------------------------------------------------------------
 * detects location of peak and snr in correlation function
 */
{
#define INITIAL_MIN 9999.9
    char *err_msg = NULL;
    float z_min, *z_max, *z_max_next;
    int h, i, j, i_min, j_min;
    long *i_max, *j_max, *i_max_next, *j_max_next;

    int z_rl = cov->z_rl, z_rh = cov->z_rh, z_cl = cov->z_cl, z_ch = cov->z_ch;

    int ipoint_x = (int) piv_data->point_x[index_y][index_x];
    int ipoint_y = (int) piv_data->point_y[index_y][index_x];
/*     float epsi_x = 0.0, epsi_y = 0.0; */
    gboolean flag_snr = TRUE;
    gint dim = peak_act;


    i_max = gpiv_nulvector_index(1, dim + 1);
    j_max = gpiv_nulvector_index(1, dim + 1);
    z_max = gpiv_vector_index(1, dim + 1);
    i_max_next = gpiv_nulvector_index(1, dim + 2);
    j_max_next = gpiv_nulvector_index(1, dim + 2);
    z_max_next = gpiv_vector_index(1, dim + 2);

/*
 * BUGFIX: CHECK!!
 * finding a local top within the interrogation region. In case of
 * autocorrelation, exclude the first max (normally at i=0,j=0 if no
 * pre-shifting has been used), by increasing peak_act with 1 during the first
 * iteration sweep, then call it skip_act
 */

    if (sweep == 0 && x_corr == 0) {
	peak_act = peak + 1;
    } else {
	if (x_corr == 0)
	    peak_act = peak;
    }


/*     g_message("cov_top:: finding a local top 1"); */
    search_top (cov, peak_act, x_corr, sweep, i_skip_act, j_skip_act,
                z_max, i_max, j_max);

    for (h = 1; h <= peak_act + 1; h++) {
        if (z_max_next[h] == -1.0) {
            ifit = GPIV_NONE;
            flag_snr = FALSE;
/*             g_warning("cov_top:: No first top found at i = %d j = %d", */
/*                       index_y, index_x); */
        }
    }

/*
 * Define first max to be skipped if autocorr, eventually shift this
 * point with new pre-shifting values
 */


    if (x_corr == 0 && sweep == 0) {
	i_skip_act = i_max[1];
	j_skip_act = j_max[1];
    }

/* BUGFIX: don't calculate snr for the Challenge project */
/*     flag_snr = FALSE;   */

/*
 * Search next higher peak for SNR calculation
 */
    if (flag_snr) {
        search_top (cov, peak_act + 1, x_corr, sweep, i_skip_act, j_skip_act,
                    z_max_next, i_max_next, j_max_next);
    }

/*
 * Check if second top has been found
 */
    for (h = 1; h <= peak_act + 1; h++) {
        if (z_max_next[h] == -1.0) {
            flag_snr = FALSE;
        }
    }


    if (flag_snr
        && cov->z[i_max_next[peak_act + 1]][j_max_next[peak_act + 1]] != 0.0) {
        cov->snr = cov->z[i_max[peak_act]][j_max[peak_act]] - cov->min /
	(cov->z[i_max_next[peak_act + 1]][j_max_next[peak_act + 1]] - cov->min);
/*         if (last_sweep == 1) g_message("cov_top:: snr = %f",cov->snr); */
    } else {
        cov->snr = 0.0;
        piv_data->snr[index_y][index_x] = cov->snr;
/*         piv_data->peak_no[index_y][index_x] = -1; */
    }

/*
 * Searching of minimum around cov. peak_act and remove 'pedestal'
 */
    z_min = INITIAL_MIN;
    i_min = INITIAL_MIN;
    j_min = INITIAL_MIN;
    for (i = i_max[peak_act] - 1; i <= i_max[peak_act] + 1; i++) {
	for (j = j_max[peak_act] - 1; j <= j_max[peak_act] + 1; j++) {
	    if ((i >= z_rl && i <= z_rh) && (j >= z_cl && j <= z_ch)) {
		if (cov->z[i][j] < z_min) {
		    z_min = cov->z[i][j];
		    i_min = i;
		    j_min = j;
		}
	    }
	}
    }

    if (z_min <= INITIAL_MIN) {
        for (i = i_max[peak_act] - 1; i <= i_max[peak_act] + 1; i++) {
            for (j = j_max[peak_act] - 1; j <= j_max[peak_act] + 1; j++) {
/*           cov->z[i][j] = cov->z[i][j]-z_min; */
                cov->z[i][j] = cov->z[i][j] - z_min + 0.1;
            }
        }
    } else {
        ifit = GPIV_NONE;
    }

/*
 * Calculate particle displacement at integer pixel numbers or at sub-pixel
 */
    if (ifit == GPIV_NONE) {
        cov->subtop_x = 0.0;
        cov->subtop_y = 0.0;

    } else {
            if ((err_msg = cov_subtop (cov->z, i_max, j_max, &cov->subtop_x,
                                       &cov->subtop_y, ifit, peak_act))
                != NULL) {
                g_message("%s", err_msg);
                *flag_subtop = TRUE;
            }
    }

/*
 * Writing maximuma  to cov
 */
    cov->top_y = i_max[peak_act];
    cov->top_x = j_max[peak_act];

/*
 * Free memeory
 */
    gpiv_free_nulvector_index(i_max, 1, dim + 1);
    gpiv_free_nulvector_index(j_max, 1, dim + 1);
    gpiv_free_vector_index(z_max, 1, dim + 1);
    gpiv_free_nulvector_index(i_max_next, 1, dim + 2);
    gpiv_free_nulvector_index(j_max_next, 1, dim + 2);
    gpiv_free_vector_index(z_max_next, 1, dim + 2);

    return 0;
}



static
void pack_cov (float **covariance,
               GpivCov *cov,
               int int_size_0
               )
/*-----------------------------------------------------------------------------
 * Packs the unordered covariance data in an ordered sequence when returning
 * from cova_nr
 */
{
    int i, j;
    int z_rnl = cov->z_rnl, z_rnh = cov->z_rnh, z_rpl = cov->z_rpl, 
        z_rph = cov->z_rph;
    int z_cnl = cov->z_cnl, z_cnh = cov->z_cnh, z_cpl = cov->z_cpl, 
        z_cph = cov->z_rph;


    for (i = z_rnl; i < z_rnh; i++) {
	for (j = z_cnl; j < z_cnh; j++) {
	    cov->z[i - int_size_0][j - int_size_0] = covariance[i][j];
	}
	for (j = z_cpl; j < z_cph; j++) {
	    cov->z[i - int_size_0][j] = covariance[i][j];
	}
    }

    for (i = z_rpl; i < z_rph; i++) {
	for (j = z_cnl; j < z_cnh; j++) {
	    cov->z[i][j - int_size_0] = covariance[i][j];
	}
	for (j = z_cpl; j < z_cph; j++) {
	    cov->z[i][j] = covariance[i][j];
	}
    }
}



static void
weight_cov (GpivCov *cov,
            GpivCov *w_k
            )
/*-----------------------------------------------------------------------------
 * Corrects ordered covariance data with weighting kernel
 */
{
    int i, j;
    int z_rl = w_k->z_rl, z_rh = w_k->z_rh;
    int z_cl = w_k->z_cl, z_ch = w_k->z_ch;


    if (w_k == NULL) {
        g_message("LIBGPIV internal error: weight_cov: w_k = NULL");
        return;
    }

    for (i = z_rl; i < z_rh; i++) {
	for (j = z_cl; j < z_ch; j++) {
	    cov->z[i][j] = cov->z[i][j] / w_k->z[i][j];
	}
    }

}


static gchar *
filter_cov_spof (fftw_complex *a, 
                 fftw_complex *b,
                 gint m,
                 gint n
                 )
/*-----------------------------------------------------------------------------
 * Applies Symmetric Phase Only filtering on the complex arrays a and b
 *
 * REFERENCES:
 *     M.P. Wernet, "Symmetric phase only filtering: a new paradigm for DPIV 
 *     data processing", Meas. Sci. Technol, vol 16 (2005), pp 601 - 618
 */
{
    gchar *err_msg = NULL;
    gfloat amplitude_a, amplitude_b;
    gint i, j, ij;


    /*         assert (a[0] != NULL); */
    /*         assert (b[0] != NULL); */

    for (i = 0; i < m; i++) {
        for (j = 0; j < n / 2 + 1; j++) {
            ij = i * (n / 2 + 1) + j;
            amplitude_a = sqrt(a[ij][0] * a[ij][0] + a[ij][1] * a[ij][1]);
            amplitude_b = sqrt(b[ij][0] * b[ij][0] + b[ij][1] * b[ij][1]);

            if (amplitude_a == 0.0 || amplitude_b == 0.0) {
                a[ij][0] = 0.0;
                a[ij][1] = 0.0;
                b[ij][0] = 0.0;
                b[ij][1] = 0.0;
            } else {
                a[ij][0] /= sqrt(amplitude_a) * sqrt(amplitude_b);
                a[ij][1] /= sqrt(amplitude_a) * sqrt(amplitude_b);
                b[ij][0] /= sqrt(amplitude_a) * sqrt(amplitude_b);
                b[ij][1] /= sqrt(amplitude_a) * sqrt(amplitude_b);
            }
        }
    }


    return err_msg;
}



static gchar *
cova (int int_size,
      float **int_area_1,
      float **int_area_2,
      GpivCov *cov,
      gboolean spof_filter
      )
/*-----------------------------------------------------------------------------
 * Calculates the covariance function of int_area_1 and int_area_2 by
 * means of Fast Fourier Transforms.
 */
{
    gchar *err_msg = NULL;
    int M = GPIV_ZEROPAD_FACT * int_size, N = GPIV_ZEROPAD_FACT * int_size;
    float covariance_max, covariance_min;
    gint i, j;
    float **covariance;

    double **a, **b, **c;
    fftw_complex  *A, *B, **C;

    fftw_plan  plan/* , plan_a, plan_b, plan_c */;
    gdouble scale = 1.0 / (M * N);


#ifdef DEBUG
    FILE *fp = my_utils_fopen_tmp (GPIV_LOGFILE, "w");
#endif
#ifdef USE_MTRACE
    /*     printf ("LIBGPIV:: cova with mtrace\n"); */
    mtrace();
#endif

#ifdef _OPENMP
/*     gpiv_warning ("cova:: 1 ===> nthreads = %d", omp_get_thread_num()); */
    fftw_plan_with_nthreads(omp_get_thread_num());
/*     fftw_plan_with_nthreads(2); */
#endif

    g_assert (int_area_1[0] != NULL);
    g_assert (int_area_2[0] != NULL);
    g_assert (cov != NULL);

    a = gpiv_double_matrix(M, 2 * (N / 2 + 1));
    A = (fftw_complex *) &a[0][0];
    b = gpiv_double_matrix(M, 2 * (N / 2 + 1));
    B = (fftw_complex *) &b[0][0];
    c = gpiv_double_matrix(M, N);
    C = gpiv_fftw_complex_matrix(M, N /2 + 1);

    covariance = gpiv_matrix(M, N);
    /* BUGFIX: may be removed */
    memset(covariance[0], 0, (sizeof(float)) * M * N);

    /*
     * FFT both interrogation areas
     */
#ifdef DEBUG
    fprintf (fp, "New I.A:\n");
#endif
#pragma omp parallel for
    for (i = 0; i < M; ++i) {
	for (j = 0; j < N; ++j) {
	    a[i][j] = (double) int_area_1[i][j];
	    b[i][j] = (double) int_area_2[i][j];
#ifdef DEBUG
            fprintf (fp, "cova:: int_area_1[%d][%d] = %f  a[%d][%d] = %f  int_area_2[%d][%d] = %f  b[%d][%d] = %f\n", 
                     i, j, int_area_1[i][j],
                     i, j, a[i][j],
                     i, j, int_area_2[i][j],
                     i, j, b[i][j]
                     );
#endif /* DEBUG */
        }
    }

#ifdef DEBUG
    fprintf (fp, "\n\n");
#endif

    /*
     * make plans and perform FT
     */
    plan = fftw_plan_dft_r2c_2d(M, N, (double *) &a[0][0], 
                                (fftw_complex *) &a[0][0], 
                                FFTW_MEASURE);
    fftw_execute(plan);
    fftw_destroy_plan(plan);
    /*     fftw_forget_wisdom(); */


    plan = fftw_plan_dft_r2c_2d(M, N, (double *) &b[0][0], 
                                (fftw_complex *) &b[0][0], 
                                FFTW_MEASURE);
    fftw_execute(plan);
    fftw_destroy_plan(plan);

    if (spof_filter) {
        if ((err_msg = filter_cov_spof(A, B, M, N)) != NULL) {
            return (err_msg);
        }
    }

    /*
     * B * conjugate(A) result in correct sign of displacements!
     */
#pragma omp parallel for
    for (i = 0; i < M; ++i) {
	for (j = 0; j < N / 2 + 1; ++j) {
	    gint ij = i * (N / 2 + 1) + j;
	    C[i][j][0] = (B[ij][0] * A[ij][0] + B[ij][1] * A[ij][1]) * scale;
	    C[i][j][1] = (B[ij][1] * A[ij][0] - B[ij][0] * A[ij][1]) * scale;
#ifdef DEBUG
            fprintf (fp, "cova:: A[%d]_re = %f A[%d]_im = %f  B[%d]_re = %f B[%d]_im = %f\n",
                     ij, A[ij][0], ij, A[ij][1],
                     ij, B[ij][0], ij, B[ij][1]
                     );
#endif
	}
    }
#ifdef DEBUG
    fprintf (fp, "\n\n");
#endif

    /*
     * inverse transform to get c, the covariance of a and b;
     * this has the side effect of overwriting C
     */
    plan = fftw_plan_dft_c2r_2d(M, N, (fftw_complex *) &C[0][0], 
                                (double *) &c[0][0],
                                FFTW_MEASURE);
    fftw_execute(plan);
    fftw_destroy_plan(plan);

    /*
     * Put the data back in a 2-dim array covariance[][]
     */
#pragma omp parallel for
    for (i = 0; i < M; i++) {
	for (j = 0; j < N; j++) {
	    covariance[i][j] = (float) c[i][j];
            /*             fprintf (fp, "cova:: c[%d][%d] = %f\n", i, j, c[i][j]); */
	}
    }
#ifdef DEBUG
    fprintf (fp, "\n\n");
#endif

    /*
     * normalisation => correlation function
     */
    covariance_max = -10.0e+9;
    covariance_min = 10.0e+9;
#pragma omp parallel for
    for (i = 0; i < M; i++) {
	for (j = 0; j < N; j++) {
	    if (covariance[i][j] > covariance_max)
		covariance_max = covariance[i][j];
	    if (covariance[i][j] < covariance_min)
		covariance_min = covariance[i][j];
	}
    }

#pragma omp parallel for
    for (i = 0; i < M; i++) {
	for (j = 0; j < N; j++) {
	    covariance[i][j] = covariance[i][j] / covariance_max;
	}
    }


    /*
     * Packing the unordered covariance data into the ordered array of
     * Covariance structure
     */
    pack_cov(covariance, cov, M);
    /* BUGFIX: may be changed */
    cov_min_max(cov);
    /*     cov->min = covariance_min; */
    /*     cov->max = covariance_max; */


    /*
     * free mems
     */
    gpiv_free_matrix (covariance);
    gpiv_free_fftw_complex_matrix (C);
    gpiv_free_double_matrix (c);
    gpiv_free_double_matrix (b);
    gpiv_free_double_matrix (a);
    A = NULL;
    B = NULL;

    /*
     * BUGFIX: fftw_cleanup really slows down!
     */
    /*     fftw_forget_wisdom(); */
    /*     fftw_cleanup(); */


#ifdef DEBUG
    fclose(fp);
#endif
#ifdef USE_MTRACE
    muntrace();
#endif
    return err_msg;
}



static gchar *
ia_weight_gauss (gint int_size, 
                 float **int_area
                 )
/**----------------------------------------------------------------------------
 * DESCRIPTION:
 *     Weights Interrogation Area's
 */
{
    gchar *err_msg = NULL;
    gint i = 0, j = 0;
    gdouble weight;


    assert (int_area[0] != NULL);

    for (i = 0; i < int_size; i++) {
        for (j = 0; j < int_size; j++) {
            weight = exp( -(((double)i - (double)int_size / 2.0) 
                                    * ((double)i - (double)int_size / 2.0)
                                    + ((double)j - (double)int_size / 2.0) 
                                    * ((double)j - (double)int_size / 2.0))
                          / (2.0 * (double)int_size * (double)int_size));
/*             g_message("weight_ia:: 2a int_size = %d i = %d j = %d weight = %f", */
/*                       int_size, i, j, weight); */
            int_area[i][j] *= weight;
        }
    }


    return err_msg;
}


/*
 * From piv_speed
 */
static void
nearest_point (gint i,
               gfloat x, 
               gfloat point_x, 
               gfloat *min, 
               gint *index, 
               gboolean *exist
               )
/*-----------------------------------------------------------------------------
 * Test if current point_x is nearest from x
 */
{
    gfloat dif = abs (x - point_x);

    if (dif < *min) {
        *exist = TRUE;
        *min = dif;
        *index = i;
    }

}


static gboolean
nearest_index (enum Position pos,
               gint vlength,
               gfloat *src_point, 
               gfloat dest_point,
               gint *index
               )
/*-----------------------------------------------------------------------------
 * Search nearest index from piv_data belonging to point (x, y)
 * in horizontal direction
 * pos_x/y index left/right, top/bottom of point
 */
{
    gint i, j;
    gfloat min = 10.0e4;
    gboolean exist = FALSE;

    *index = 0;
/* g_message ("nearest_index::  dest_point=%f", dest_point); */
    for (i = 0; i < vlength; i++) {
/* g_message ("nearest_index::  src_point[%d]=%f", i, src_point[i]); */

        if (pos ==  LOWER
            && src_point[i] <= dest_point) {
            nearest_point (i, dest_point, src_point[i], &min, 
                           index, &exist);
/* g_message ("nearest_index::  index_l=%d", *index); */

        } else if (pos == NEXT_LOWER
                   &&  i > 0
                   && src_point[i - 1] < dest_point) {
 
            nearest_point (i - 1, dest_point, src_point[i - 1], &min, 
                           index, &exist);
/* g_message("nearest_index::  src_point[%d]=%f index_ll=%d", */
/*           i-1, src_point[i - 1], *index); */

        } else if (pos == HIGHER
                   && src_point[i] > dest_point) {
            nearest_point (i, dest_point, src_point[i], &min, index, &exist);
/* g_message("nearest_index::  index_h=%d", *index); */
            
        } else if (pos ==  NEXT_HIGHER
                   && i <  vlength - 1 
                   && src_point[i + 1] > dest_point) {
            nearest_point (i + 1, dest_point, src_point[i + 1], 
                           &min, 
                           index, &exist);
/* g_message ("nearest_index::  src_point[%d]=%f index_hh=%d", */
/*           i+1, src_point[i + 1], *index); */
            
        }
        
    }

    return exist;
}



static gdouble
bilinear_interpol (gdouble alpha_hor,
                   gdouble alpha_vert,
                   gdouble src_dx_nw,
                   gdouble src_dx_ne,
                   gdouble src_dx_sw,
                   gdouble src_dx_se
                   )
/*-----------------------------------------------------------------------------
 * Bilinear interpolation of src_dx_*
 * _ne: NORTH_EAST
 * _nw: NORTH_WEST
 * _se: SOUTH_EAST
 * _SW: SOUTH_WEST
 */
{
    gdouble dx, dx_n, dx_s;
    dx_n = (1.0 - alpha_hor) * src_dx_nw + alpha_hor * src_dx_ne;
    dx_s = (1.0 - alpha_hor) * src_dx_sw + alpha_hor * src_dx_se;
    dx =  (1.0 - alpha_vert) * dx_n + alpha_vert * dx_s;

/*     g_message ("bilinear_interpol:: alpha_hor=%f alpha_vert=%f, dx_n = %f dx_s = %f => dx = %f",  */
/*               alpha_hor, alpha_vert, dx_n, dx_s, dx); */
    return dx;
}



static void *
intpol_facts (gfloat *src_point, 
              gfloat *dest_point, 
              gint src_vlength,
              gint dest_vlength,
              gint *index_l,
              gint *index_h,
              gint *index_ll,
              gint *index_hh,
              double *alpha
              )
/*-----------------------------------------------------------------------------
 * calculates normalized interpolation factors for piv_data_src
 * Think of:
 *          _l (LOWER) is used for _w (WEST) or _n (NORTH),
 *          _h (HIGHER) is used for _e (EAST) or _s (SOUTH)
 *          _ll (NEXT_LOWER) is used for _ww (WEST_WEST) or _nn (NORTH_NORTH),
 *          _hh (NEXT_HIGHER) is used for _ee (EAST_EAST) or _ss (SOUTH_SOUTH)
 */
{
    gboolean *exist_l, *exist_h, *exist_ll, *exist_hh;
    double *dist_l, *dist_h, *dist_ll, *dist_hh;
    enum Position pos;
    gint i;

    exist_l = gpiv_gbolvector (dest_vlength);
    exist_h = gpiv_gbolvector (dest_vlength);
    exist_ll = gpiv_gbolvector (dest_vlength);
    exist_hh = gpiv_gbolvector (dest_vlength);

    dist_l = gpiv_dvector (dest_vlength);
    dist_h = gpiv_dvector (dest_vlength);
    dist_ll = gpiv_dvector (dest_vlength);
    dist_hh = gpiv_dvector (dest_vlength);

/*     g_warning ("intpol_facts:: 1, src_vlengthth=%d dest_vlength=%d",  */
/*               src_vlength, dest_vlength); */
/*
 * Searching adjacent and next to adjacent points of dest_point in src_point
 * data array
 */
    for (i = 0; i < dest_vlength; i++) {
/* g_message ("intpol_facts::   (next) adjacent point for dest_point[%d]=%f",  */
/*           i, dest_point[i]); */
        pos = LOWER;
        exist_l[i] = FALSE;
        if (exist_l[i] = 
            nearest_index (pos, 
                           src_vlength, 
                           src_point,
                           dest_point[i],
                           &index_l[i])) {
/*             g_message ("intpol_facts:: index_l[%d]=%d", i, index_l[i]); */
            dist_l[i] = dest_point[i] - src_point[index_l[i]];
        } else {
/*
 * To be used for extrapolation in negative direction 
 * by applying higher and next to higher points of src data
 */
            pos = NEXT_HIGHER;
            exist_hh[i] = FALSE;
            if (exist_hh[i] = 
                nearest_index (pos, 
                               src_vlength, 
                               src_point,
                               dest_point[i],
                               &index_hh[i])) {
/*                 g_message ("intpol_facts:: index_hh[%d]=%d", i, index_hh[i]); */
                dist_hh[i] = dest_point[i] - src_point[index_hh[i]];
            }
        }
        


        pos = HIGHER;
        exist_h[i] = FALSE;
        if (exist_h[i] = 
            nearest_index (pos, 
                           src_vlength, 
                           src_point,
                           dest_point[i],
                           &index_h[i])) {
/*                 g_message ("intpol_facts:: index_h[%d]=%d", i, index_h[i]); */
            dist_h[i] = dest_point[i] - src_point[index_h[i]];
        } else {

/*
 * To be used for extrapolation in positive direction 
 * by applying lower and next to lower points of src data
 */
            pos = NEXT_LOWER;
            exist_ll[i] = FALSE;
            index_ll[i] = 0;
            if (exist_ll[i] = 
                nearest_index (pos, 
                               src_vlength, 
                               src_point,
                               dest_point[i],
                               &index_ll[i])) {
/*                 g_message ("intpol_facts:: index_ll[%d]=%d, index_l[%d]=%d",  */
/*                           i, index_ll[i], i, index_l[i]); */
                dist_ll[i] = dest_point[i] - src_point[index_ll[i]];
            }
        }

/*
 * calculating of weight factors for inter- or extrapolation
 */

/* g_message ("intpol_facts:: weight factors for dest_point[%d]=%f",  */
/*           i, dest_point[i]); */
        if (exist_l[i] && exist_h[i]) {
/* g_message ("intpol_facts:: index_l[%d]=%d index_h[%d]=%d src_point_l=%f src_point_h=%f",  */
/*           i, index_l[i], i, index_h[i],  */
/*           src_point[index_l[i]], src_point[index_h[i]]); */
/*
 * Inner point: bilinear interpolation
 */
            if (src_point[index_l[i]] != src_point[index_h[i]]) {
                alpha[i] = dist_l[i] / 
                    (src_point[index_h[i]] - src_point[index_l[i]]);
            } else {
                alpha[i] = 1.0;
            }
            

        } else if (exist_l[i] && exist_ll[i] && !exist_h[i]) {
/* 
 * extrapolation from two lower values
 */
/* g_message ("intpol_facts:: index_l[%d]=%d index_ll[%d]=%d src_point_l=%f src_point_ll=%f",  */
/*           i, index_l[i], i, index_ll[i],  */
/*           src_point[index_l[i]], src_point[index_ll[i]]); */

            if (src_point[index_ll[i]] != src_point[index_l[i]]) {
                alpha[i] = dist_ll[i] / 
                    (src_point[index_l[i]] - src_point[index_ll[i]]);
                index_h[i] = index_l[i];
                index_l[i] = index_ll[i];
            } else {
                alpha[i] = 1.0;
            }


        } else if (!exist_l[i] && exist_h[i] && exist_hh[i]) {
/* 
 * extrapolation from two higher values
 */
/* g_message ("intpol_facts:: index_h=%d index_hh=%d src_point_h=%f src_point_hh=%f",  */
/*           index_h[i], index_hh[i], src_point[index_h[i]],  */
/*           src_point[index_hh[i]]); */

            if (src_point[index_hh[i]] != src_point[index_h[i]]) {
                alpha[i] = dist_h[i] / 
                    (src_point[index_hh[i]] - src_point[index_h[i]]);
                index_l[i] = index_h[i];
                index_h[i] = index_hh[i];
            } else {
                alpha[i] = 1.0;
            }
            

        } else {
            alpha[i] = 1.0;
        }
    }


    gpiv_free_gbolvector (exist_l);
    gpiv_free_gbolvector (exist_h);
    gpiv_free_gbolvector (exist_ll);
    gpiv_free_gbolvector (exist_hh);
    
    gpiv_free_dvector (dist_l);
    gpiv_free_dvector (dist_h);
    gpiv_free_dvector (dist_ll);
    gpiv_free_dvector (dist_hh);
 
}


static void
dxdy_at_new_grid_block (const GpivPivData *piv_data_src, 
                        GpivPivData *piv_data_dest,
                        gint expansion_factor,
                        gint smooth_window
                        )
/*-----------------------------------------------------------------------------
 * Calculates displacements from old to new grid, that has been expanded by
 * factor 2 and avarages with smoothing window. Works only correct if all neighbours 
 * at equal distances
 */
{
    int i, j, k, l, ef = expansion_factor, sw = smooth_window;
    int count = 0;
    GpivPivData *pd = NULL;

    pd = gpiv_alloc_pivdata (piv_data_dest->nx, piv_data_dest->ny);

/*
 * Copy blocks of 2x2 input data to pd 
 */
    for (i = 0; i < piv_data_src->ny; i++) {
        for (j = 0; j < piv_data_src->nx; j++) {
            for (k = 0; k < 2; k++) {
                if (ef * i+k < pd->ny) {
                    for (l = 0; l < 2; l++) {
                        if (ef * j+l < pd->nx) {
                            pd->dx[ef * i+k][ef * j+l] = piv_data_src->dx[i][j];
                            pd->dy[ef * i+k][ef * j+l] = piv_data_src->dy[i][j];
                        }
                    }
                }
            }   
        }
    }

/*
 * smooth the data
 */
    for (i = 0; i < piv_data_src->ny; i++) {
        for (j = 0; j < piv_data_src->nx; j++) {
            count = 0;
            for (k = -sw + 1; k < sw; k++) {
                if (i + k > 0 && i + k < pd->ny) {
                    for (l = -sw + 1; l < sw; l++) {
                        if (j + l > 0 && j + l < pd->ny) {
                            count++;
                            piv_data_dest->dx[i][j] += pd->dx[i+k][j+l];
                            piv_data_dest->dy[i][j] += pd->dy[i+k][j+l];
                        }
                    }
                }
            }
            piv_data_dest->dx[i][j] = piv_data_dest->dx[i][j] / (float)count;
            piv_data_dest->dy[i][j] = piv_data_dest->dx[i][j] / (float)count;
        }
    }

    gpiv_free_pivdata (pd);
}



static gchar *
update_pivdata_imgdeform_zoff (const GpivImage *image, 
                               GpivImage *lo_image, 
                               const GpivPivPar *piv_par, 
                               const GpivValidPar *valid_par, 
                               GpivPivData *piv_data, 
                               GpivPivData *lo_piv_data, 
                               gfloat *cum_residu, 
                               gboolean *cum_residu_reached,
                               gfloat *sum_dxdy, 
                               gfloat *sum_dxdy_old,
                               gboolean isi_last,
                               gboolean grid_last,
                               gboolean sweep_last,
                               gboolean verbose
                               )
/*-----------------------------------------------------------------------------
 * Validates and updates / renews pivdata and some other variables when image 
 * deformation or zero-offset interrogation scheme is used
 */
{

    gchar *err_msg = NULL;


    /*
     * Test on outliers
     */
    if ((err_msg = 
         gpiv_valid_errvec (lo_piv_data, 
                            image, 
                            piv_par,
                            valid_par, 
                            TRUE))
        != NULL) {
        return err_msg;
    }
            

    if (piv_par->int_scheme == GPIV_IMG_DEFORM) {

        /*
         * Update PIV estimators with those from the last interrogation
         * Resetting local PIV estimators for eventual next interrogation
         */
        if ((err_msg = gpiv_add_dxdy_pivdata (lo_piv_data, piv_data))
            != NULL) {
            return err_msg;
        }

        if ((err_msg = gpiv_0_pivdata (lo_piv_data))
            != NULL) {
            return err_msg;
        }

        /*
         * Deform image with updated PIV estimators.
         * First, copy local from original image.
         * Deform with newly updated PIV estimators.
         * Eventually write deformed image.
         */

        if ((err_msg = gpiv_cp_img_data (image, lo_image))
            != NULL) {
            return err_msg;
        }

        if ((err_msg = gpiv_imgproc_deform (lo_image, piv_data))
            != NULL) {
            return err_msg;
        }
/* #define DEBUG */
#ifdef DEBUG
        if (sweep_last && verbose) {
            printf ("\n");
            if ((err_msg = 
                 my_utils_write_tmp_image (lo_image, GPIV_DEFORMED_IMG_NAME,
                                           "Writing deformed image to:"))
                != NULL) {
                return err_msg;
            }
        }
#endif /* DEBUG */
/* #undef DEBUG */

    } else {

        /*
         * Renew PIV estimators with those from the last interrogation
         */
        if ((err_msg = gpiv_0_pivdata (piv_data))
            != NULL) {
            return err_msg;
        }
        if ((err_msg = gpiv_add_dxdy_pivdata (lo_piv_data, piv_data))
            != NULL) {
            return err_msg;
        }
    }

    /*
     * Checking the relative cumulative residu for convergence
     * if final residu has been reached, cum_residu_reached will be set.
     */
    if (isi_last && grid_last) {
        *sum_dxdy_old = *sum_dxdy;
        *sum_dxdy = 0.0;
        gpiv_sum_dxdy_pivdata (piv_data, sum_dxdy);
        *cum_residu = fabsf ((*sum_dxdy - *sum_dxdy_old) / 
                            ((gfloat)piv_data->nx * (gfloat)piv_data->ny));
        if (*cum_residu < GPIV_CUM_RESIDU_MIN) {
            *cum_residu_reached = TRUE;
        }
    }


    return err_msg;
}



#undef NMIN_TO_INTERPOLATE


#ifdef ENABLE_MPI
static GpivPivData *
piv_interrogate_img__scatterv_pivdata(GpivPivData *piv_data)
/*---------------------------------------------------------------------------------------
 * Scatter the piv_data equally over its rows.
 *
 * The number of rows in piv_data need not be a multiple of nprocs. 
 * Therefore, the first (piv_data->ny)%nprocs  processes get 
 * ceil(piv_data->ny/np/nprocs) rows, and the remaining processes get
 * floor(piv_data->ny)/nprocs) rows.
 */
{
    GpivPivData *pd = NULL, *mpi_piv_data = NULL;
    gint i, nprocs, rank;
    gint *counts = NULL, *displs = NULL;


    MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

#ifdef DEBUG
    if (rank ==0) g_message ("gpiv_piv_interrogate_img:: nx=%d ny=%d nprocs = %d", 
                             piv_data->nx, piv_data->ny, nprocs);
#endif

    counts = gpiv_piv_mpi_compute_counts(piv_data->nx, piv_data->ny);
    displs = gpiv_piv_mpi_compute_displs(counts, piv_data->nx, piv_data->ny);
    mpi_piv_data = gpiv_cp_pivdata (piv_data);
    gpiv_free_pivdata (piv_data);

    for (i = 0; i < nprocs; i++) {
        if (rank == i) pd = gpiv_alloc_pivdata(mpi_piv_data->nx, counts[i] / mpi_piv_data->nx);
    }

    gpiv_piv_mpi_scatterv_pivdata (mpi_piv_data, pd, counts, displs);


    gpiv_free_pivdata (mpi_piv_data);
    gpiv_free_ivector (counts);
    gpiv_free_ivector (displs);


    return pd;
}



static GpivPivData *
piv_interrogate_img__gatherv_pivdata(GpivPivData *lo_piv_data, 
                                     GpivPivData *piv_data)
/*---------------------------------------------------------------------------------------
 * Gathers the piv_data equally over its rows. 
 * Counterpart of piv_interrogate_img__scatterv_pivdata
 *
 * The number of rows in piv_data need not be a multiple of nprocs. 
 * Therefore, the first (piv_data->ny)%nprocs  processes get 
 * ceil(piv_data->ny/np/nprocs) rows, and the remaining processes get
 * floor(piv_data->ny)/nprocs) rows.
 */
{
    GpivPivData *pd = NULL, *mpi_piv_data = NULL;
    gint *counts = NULL, *displs = NULL;


    counts = gpiv_piv_mpi_compute_counts(piv_data->nx, piv_data->ny);
    displs = gpiv_piv_mpi_compute_displs(counts, piv_data->nx, piv_data->ny);
    mpi_piv_data = gpiv_alloc_pivdata(piv_data->nx, piv_data->ny);
    gpiv_piv_mpi_gatherv_pivdata (lo_piv_data, mpi_piv_data, counts, displs);
    gpiv_free_ivector (counts);
    gpiv_free_ivector (displs);
    gpiv_free_pivdata (lo_piv_data);
    pd = gpiv_cp_pivdata (mpi_piv_data);
    gpiv_free_pivdata (mpi_piv_data);


    return pd;
}




guint
substr_noremain(guint n, 
                guint m)
/*-------------------------------------------------------------------
 * Substracts 1 while remainder of n not equal to zero
 */
{
    while (fmod((double) n, (double) m) != 0) {
        n--;
    }


    return (guint) n;
}



#endif /* ENABLE_MPI */