snaphu-sys 0.1.2

Low-level Rust bindings to the SNAPHU C library
Documentation
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
#ifndef SNAPHU_H
#define SNAPHU_H
/*************************************************************************

  snaphu header file
  Written by Curtis W. Chen
  Copyright 2002 Board of Trustees, Leland Stanford Jr. University
  Please see the supporting documentation for terms of use.
  No warranty.

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

#include <stddef.h>

/**********************/
/* defined constants  */
/**********************/

#define PROGRAMNAME          "snaphu"
#define VERSION              "2.0.7"
#define BUGREPORTEMAIL       "snaphu@gmail.com"
#ifdef PI
#undef PI
#endif
#define PI                   3.14159265358979323846
#define TWOPI                6.28318530717958647692
#define SQRTHALF             0.70710678118654752440
#define MAXSTRLEN            512
#define MAXTMPSTRLEN         1024
#define MAXLINELEN           2048
#define TRUE                 1
#define FALSE                0
#define LARGESHORT           32000
#define LARGEINT             2000000000
#define LARGEFLOAT           1.0e35
#define VERYFAR              LARGEINT
#define GROUNDROW            -2
#define GROUNDCOL            -2
#define BOUNDARYROW          -4
#define BOUNDARYCOL          -4
#define MAXGROUPBASE         LARGEINT
#define ONTREE               -1
#define INBUCKET             -2
#define NOTINBUCKET          -3
#define PRUNED               -4
#define MASKED               -5
#define BOUNDARYPTR          -6
#define BOUNDARYCANDIDATE    -7
#define BOUNDARYLEVEL        LARGEINT
#define INTERIORLEVEL        (BOUNDARYLEVEL-1)
#define MINBOUNDARYSIZE      100
#define POSINCR              0
#define NEGINCR              1
#define NOCOSTSHELF          -LARGESHORT
#define MINSCALARCOST        1
#define INITARRSIZE          500
#define NEWNODEBAGSTEP       500
#define CANDIDATEBAGSTEP     500
#define NEGBUCKETFRACTION    1.0
#define POSBUCKETFRACTION    1.0
#define CLIPFACTOR           0.6666666667
#define NSOURCELISTMEMINCR   1024
#define NLISTMEMINCR         1024
#define DEF_OUTFILE          "snaphu.out"
#define DEF_SYSCONFFILE      ""     /* "/usr/local/snaphu/snaphu.conf" */
#define DEF_WEIGHTFILE       ""     /* "snaphu.weight" */
#define DEF_AMPFILE          ""     /* "snaphu.amp" */
#define DEF_AMPFILE2         ""     /* "snaphu.amp" */
#define DEF_MAGFILE          ""     /* "snaphu.mag" */
#define DEF_CORRFILE         ""     /* "snaphu.corr" */
#define DEF_ESTFILE          ""     /* "snaphu.est" */
#define DEF_COSTINFILE       ""
#define DEF_BYTEMASKFILE     ""
#define DEF_DOTILEMASKFILE   ""
#define DEF_INITFILE         ""
#define DEF_FLOWFILE         ""
#define DEF_EIFILE           ""
#define DEF_ROWCOSTFILE      ""
#define DEF_COLCOSTFILE      ""
#define DEF_MSTROWCOSTFILE   ""
#define DEF_MSTCOLCOSTFILE   ""
#define DEF_MSTCOSTSFILE     ""
#define DEF_CORRDUMPFILE     ""
#define DEF_RAWCORRDUMPFILE  ""
#define DEF_CONNCOMPFILE     ""
#define DEF_COSTOUTFILE      ""
#define DEF_LOGFILE          ""
#define MAXITERATION         5000
#define NEGSHORTRANGE        SHRT_MIN
#define POSSHORTRANGE        SHRT_MAX
#define MAXRES               SCHAR_MAX
#define MINRES               SCHAR_MIN
#define PROBCOSTP            (-99.999)
#define NULLFILE             "/dev/null"
#define DEF_ERRORSTREAM      stderr
#define DEF_OUTPUTSTREAM     stdout
#define DEF_VERBOSESTREAM    NULL
#define DEF_COUNTERSTREAM    NULL
#define DEF_INITONLY         FALSE
#define DEF_INITMETHOD       MSTINIT
#define DEF_UNWRAPPED        FALSE
#define DEF_REGROWCONNCOMPS  FALSE
#define DEF_EVAL             FALSE
#define DEF_WEIGHT           1
#define DEF_COSTMODE         TOPO
#define DEF_VERBOSE          FALSE
#define DEF_AMPLITUDE        TRUE
#define AUTOCALCSTATMAX      0
#define MAXNSHORTCYCLE       8192
#define USEMAXCYCLEFRACTION  (-123)
#define COMPLEX_DATA         1         /* file format */
#define FLOAT_DATA           2         /* file format */
#define ALT_LINE_DATA        3         /* file format */
#define ALT_SAMPLE_DATA      4         /* file format */
#define TILEINITFILEFORMAT   ALT_LINE_DATA
#define TILEINITFILEROOT     "snaphu_tileinit_"
#define ABNORMAL_EXIT        1         /* exit code */
#define NORMAL_EXIT          0         /* exit code */
#define DUMP_PATH            "/tmp/"   /* default location for writing dumps */
#define NARMS                8         /* number of arms for Despeckle() */
#define ARMLEN               5         /* length of arms for Despeckle() */
#define KEDGE                5         /* length of edge detection window */
#define ARCUBOUND            200       /* capacities for cs2 */
#define MSTINIT              1         /* initialization method */
#define MCFINIT              2         /* initialization method */
#define BIGGESTDZRHOMAX      10000.0
#define SECONDSPERPIXEL      0.000001  /* for delay between thread creations */
#define MAXTHREADS           64
#define TMPTILEDIRROOT       "snaphu_tiles_"
#define TILEDIRMODE          511
#define TMPTILEROOT          "tmptile_"
#define TMPTILECOSTSUFFIX    "cost_"
#define TMPTILEOUTFORMAT     ALT_LINE_DATA
#define REGIONSUFFIX         "_regions"
#define LOGFILEROOT          "tmptilelog_"
#define RIGHT                1
#define DOWN                 2
#define LEFT                 3
#define UP                   4
#define TILEDPSICOLFACTOR    0.8
#define TILEOVRLPWARNTHRESH  400
#define ZEROCOSTARC          -LARGEINT
#define PINGPONG             2
#define SINGLEANTTRANSMIT    1
#define NOSTATCOSTS          0
#define TOPO                 1
#define DEFO                 2
#define SMOOTH               3
#define CONNCOMPOUTTYPEUCHAR 1
#define CONNCOMPOUTTYPEUINT  4


/* SAR and geometry parameter defaults */

#define DEF_ORBITRADIUS      7153000.0
#define DEF_ALTITUDE         0.0
#define DEF_EARTHRADIUS      6378000.0
#define DEF_BASELINE         150.0
#define DEF_BASELINEANGLE    (1.25*PI)
#define DEF_BPERP            0
#define DEF_TRANSMITMODE     PINGPONG
#define DEF_NLOOKSRANGE      1
#define DEF_NLOOKSAZ         5
#define DEF_NLOOKSOTHER      1
#define DEF_NCORRLOOKS       23.8
#define DEF_NCORRLOOKSRANGE  3  
#define DEF_NCORRLOOKSAZ     15
#define DEF_NEARRANGE        831000.0
#define DEF_DR               8.0
#define DEF_DA               20.0 
#define DEF_RANGERES         10.0
#define DEF_AZRES            6.0
#define DEF_LAMBDA           0.0565647


/* scattering model defaults */

#define DEF_KDS              0.02
#define DEF_SPECULAREXP      8.0
#define DEF_DZRCRITFACTOR    2.0
#define DEF_SHADOW           FALSE
#define DEF_DZEIMIN          -4.0
#define DEF_LAYWIDTH         16 
#define DEF_LAYMINEI         1.25
#define DEF_SLOPERATIOFACTOR 1.18
#define DEF_SIGSQEI          100.0


/* decorrelation model parameters */

#define DEF_DRHO             0.005
#define DEF_RHOSCONST1       1.3
#define DEF_RHOSCONST2       0.14
#define DEF_CSTD1            0.4
#define DEF_CSTD2            0.35
#define DEF_CSTD3            0.06
#define DEF_DEFAULTCORR      0.01
#define DEF_RHOMINFACTOR     1.3


/* pdf model parameters */

#define DEF_DZLAYPEAK        -2.0
#define DEF_AZDZFACTOR       0.99
#define DEF_DZEIFACTOR       4.0 
#define DEF_DZEIWEIGHT       0.5 
#define DEF_DZLAYFACTOR      1.0
#define DEF_LAYCONST         0.9
#define DEF_LAYFALLOFFCONST  2.0
#define DEF_SIGSQSHORTMIN    1
#define DEF_SIGSQLAYFACTOR   0.1


/* deformation mode parameters */

#define DEF_DEFOAZDZFACTOR   1.0
#define DEF_DEFOTHRESHFACTOR 1.2
#define DEF_DEFOMAX          1.2
#define DEF_SIGSQCORR        0.05
#define DEF_DEFOLAYCONST     0.9


/* algorithm parameters */

#define DEF_FLIPPHASESIGN    FALSE
#define DEF_ONETILEREOPT     FALSE
#define DEF_RMTILEINIT       TRUE
#define DEF_MAXFLOW          4
#define DEF_KROWEI           65
#define DEF_KCOLEI           257
#define DEF_KPARDPSI         7
#define DEF_KPERPDPSI        7
#define DEF_THRESHOLD        0.001
#define DEF_INITDZR          2048.0
#define DEF_INITDZSTEP       100.0
#define DEF_MAXCOST          1000.0
#define DEF_COSTSCALE        100.0 
#define DEF_COSTSCALEAMBIGHT 80.0 
#define DEF_DNOMINCANGLE     0.01
#define DEF_SRCROW           -1
#define DEF_SRCCOL           -1
#define DEF_P                PROBCOSTP
#define DEF_BIDIRLPN         TRUE
#define DEF_NSHORTCYCLE      200
#define DEF_MAXNEWNODECONST  0.0008
#define DEF_MAXCYCLEFRACTION 0.00001
#define DEF_NCONNNODEMIN     0
#define DEF_MAXNFLOWCYCLES   USEMAXCYCLEFRACTION
#define DEF_INITMAXFLOW      9999
#define INITMAXCOSTINCR      200
#define NOSTATINITMAXFLOW    15
#define DEF_ARCMAXFLOWCONST  3
#define DEF_DUMPALL          FALSE
#define DUMP_INITFILE        "snaphu.init"
#define DUMP_FLOWFILE        "snaphu.flow"
#define DUMP_EIFILE          "snaphu.ei"
#define DUMP_ROWCOSTFILE     "snaphu.rowcost"
#define DUMP_COLCOSTFILE     "snaphu.colcost"
#define DUMP_MSTROWCOSTFILE  "snaphu.mstrowcost"
#define DUMP_MSTCOLCOSTFILE  "snaphu.mstcolcost"
#define DUMP_MSTCOSTSFILE    "snaphu.mstcosts"
#define DUMP_CORRDUMPFILE    "snaphu.corr"
#define DUMP_RAWCORRDUMPFILE "snaphu.rawcorr"
#define INCRCOSTFILEPOS      "snaphu.incrcostpos"
#define INCRCOSTFILENEG      "snaphu.incrcostneg"
#define DEF_CS2SCALEFACTOR   8
#define DEF_NMAJORPRUNE      LARGEINT
#define DEF_PRUNECOSTTHRESH  LARGEINT
#define DEF_EDGEMASKTOP      0
#define DEF_EDGEMASKBOT      0
#define DEF_EDGEMASKLEFT     0
#define DEF_EDGEMASKRIGHT    0
#define CONNCOMPMEMINCR      1024


/* default tile parameters */

#define DEF_NTILEROW         1
#define DEF_NTILECOL         1
#define DEF_ROWOVRLP         0
#define DEF_COLOVRLP         0
#define DEF_PIECEFIRSTROW    1
#define DEF_PIECEFIRSTCOL    1
#define DEF_PIECENROW        0
#define DEF_PIECENCOL        0
#define DEF_TILECOSTTHRESH   500
#define DEF_MINREGIONSIZE    100
#define DEF_NTHREADS         1
#define DEF_SCNDRYARCFLOWMAX 8
#define DEF_TILEEDGEWEIGHT   2.5
#define DEF_TILEDIR          ""
#define DEF_ASSEMBLEONLY     FALSE
#define DEF_RMTMPTILE        TRUE


/* default connected component parameters */
#define DEF_MINCONNCOMPFRAC  0.01
#define DEF_CONNCOMPTHRESH   300
#define DEF_MAXNCOMPS        32
#define DEF_CONNCOMPOUTTYPE  CONNCOMPOUTTYPEUCHAR


/* default file formats */

#define DEF_INFILEFORMAT              COMPLEX_DATA
#define DEF_UNWRAPPEDINFILEFORMAT     ALT_LINE_DATA
#define DEF_MAGFILEFORMAT             FLOAT_DATA
#define DEF_OUTFILEFORMAT             ALT_LINE_DATA
#define DEF_CORRFILEFORMAT            ALT_LINE_DATA
#define DEF_ESTFILEFORMAT             ALT_LINE_DATA
#define DEF_AMPFILEFORMAT             ALT_SAMPLE_DATA

/* command-line usage help strings */

#define OPTIONSHELPFULL\
 "usage:  snaphu [options] infile linelength [options]\n"\
 "options:\n"\
 "  -t              use topography mode costs (default)\n"\
 "  -d              use deformation mode costs\n"\
 "  -s              use smooth-solution mode costs\n"\
 "  -C <confstr>    parse argument string as config line as from conf file\n"\
 "  -f <filename>   read configuration parameters from file\n"\
 "  -o <filename>   write output to file\n"\
 "  -a <filename>   read amplitude data from file\n"\
 "  -A <filename>   read power data from file\n"\
 "  -m <filename>   read interferogram magnitude data from file\n"\
 "  -M <filename>   read byte mask data from file\n"\
 "  -c <filename>   read correlation data from file\n"\
 "  -e <filename>   read coarse unwrapped-phase estimate from file\n"\
 "  -w <filename>   read scalar weights from file\n"\
 "  -b <decimal>    perpendicular baseline (meters, topo mode only)\n"\
 "  -p <decimal>    Lp-norm parameter p\n"\
 "  -i              do initialization and exit\n"\
 "  -n              do not use statistical costs (with -p or -i)\n"\
 "  -u              infile is already unwrapped; initialization not needed\n"\
 "  -q              quantify cost of unwrapped input file then exit\n"\
 "  -g <filename>   grow connected components mask and write to file\n"\
 "  -G <filename>   grow connected components mask for unwrapped input\n"\
 "  -S              single-tile reoptimization after multi-tile init\n"\
 "  -k              keep temporary tile outputs\n"\
 "  -l <filename>   log runtime parameters to file\n"\
 "  -v              give verbose output\n"\
 "  --mst           use MST algorithm for initialization (default)\n"\
 "  --mcf           use MCF algorithm for initialization\n"\
 "  --aa <filename1> <filename2>    read amplitude from next two files\n"\
 "  --AA <filename1> <filename2>    read power from next two files\n"\
 "  --costinfile <filename>         read statistical costs from file\n"\
 "  --costoutfile <filename>        write statistical costs to file\n"\
 "  --tile <nrow> <ncol> <rowovrlp> <colovrlp>  unwrap as nrow x ncol tiles\n"\
 "  --nproc <integer>               number of processors used in tile mode\n"\
 "  --tiledir <dirname>             use specified directory for tiles\n"\
 "  --assemble                      assemble unwrapped tiles in tiledir\n"\
 "  --piece <firstrow> <firstcol> <nrow> <ncol>  unwrap subset of image\n" \
 "  --debug, --dumpall              dump all intermediate data arrays\n"\
 "  --copyright, --info             print copyright and bug report info\n"\
 "  -h, --help                      print this help text\n"\
 "\n"

#define OPTIONSHELPBRIEF\
 "usage:  snaphu [options] infile linelength [options]\n"\
 "most common options:\n"\
 "  -t              use topography mode costs (default)\n"\
 "  -d              use deformation mode costs\n"\
 "  -s              use smooth-solution mode costs\n"\
 "  -C <confstr>    parse argument string as config line as from conf file\n"\
 "  -f <filename>   read configuration parameters from file\n"\
 "  -o <filename>   write output to file\n"\
 "  -a <filename>   read amplitude data from file\n"\
 "  -c <filename>   read correlation data from file\n"\
 "  -M <filename>   read byte mask data from file\n"\
 "  -b <decimal>    perpendicular baseline (meters)\n"\
 "  -i              do initialization and exit\n"\
 "  -S              single-tile reoptimization after multi-tile init\n"\
 "  -l <filename>   log runtime parameters to file\n"\
 "  -u              infile is already unwrapped; initialization not needed\n"\
 "  -v              give verbose output\n"\
 "  --mst           use MST algorithm for initialization (default)\n"\
 "  --mcf           use MCF algorithm for initialization\n"\
 "  --tile <nrow> <ncol> <rowovrlp> <colovrlp>  unwrap as nrow x ncol tiles\n"\
 "  --nproc <integer>               number of processors used in tile mode\n"\
 "\n"\
 "type snaphu -h for a complete list of options\n"\
 "\n"

#define COPYRIGHT\
 "Written by Curtis W. Chen\n"\
 "Copyright 2002,2017 Board of Trustees, Leland Stanford Jr. University\n"\
 "\n"\
 "Except as noted below, permission to use, copy, modify, and\n"\
 "distribute, this software and its documentation for any purpose is\n"\
 "hereby granted without fee, provided that the above copyright notice\n"\
 "appear in all copies and that both that copyright notice and this\n"\
 "permission notice appear in supporting documentation, and that the\n"\
 "name of the copyright holders be used in advertising or publicity\n"\
 "pertaining to distribution of the software with specific, written\n"\
 "prior permission, and that no fee is charged for further distribution\n"\
 "of this software, or any modifications thereof.  The copyright holder\n"\
 "makes no representations about the suitability of this software for\n"\
 "any purpose.  It is provided \"as is\" without express or implied\n"\
 "warranty.\n"\
 "\n"\
 "THE COPYRIGHT HOLDER DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS\n"\
 "SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n"\
 "FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY\n"\
 "SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER\n"\
 "RESULTING FROM LOSS OF USE, DATA, PROFITS, QPA OR GPA, WHETHER IN AN\n"\
 "ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT\n"\
 "OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n"\
 "\n"\
 "The parts of this software derived from the CS2 minimum cost flow\n"\
 "solver written by A. V. Goldberg and B. Cherkassky are governed by the\n"\
 "terms of the copyright holder of that software.  Permission has been\n"\
 "granted to use and distrubute that software for strictly noncommercial\n"\
 "purposes as part of this package, provided that the following\n"\
 "copyright notice from the original distribution and URL accompany the\n"\
 "software:\n"\
 "\n"\
 "  COPYRIGHT C 1995 IG Systems, Inc.  Permission to use for\n"\
 "  evaluation purposes is granted provided that proper\n"\
 "  acknowledgments are given.  For a commercial licence, contact\n"\
 "  igsys@eclipse.net (http://www.igsystems.com/cs2).\n"\
 "\n"\
 "  This software comes with NO WARRANTY, expressed or implied. By way\n"\
 "  of example, but not limitation, we make no representations of\n"\
 "  warranties of merchantability or fitness for any particular\n"\
 "  purpose or that the use of the software components or\n"\
 "  documentation will not infringe any patents, copyrights,\n"\
 "  trademarks, or other rights.\n"\
 "\n"\
 "\n"\
 "Please send snaphu bug reports to " BUGREPORTEMAIL "\n"\
 "\n"


/********************/
/* type definitions */
/********************/

/** node data structure */
typedef struct nodeST{
  int row,col;                  /** row, col of this node */
  struct nodeST *next;          /** ptr to next node in thread or bucket */
  struct nodeST *prev;          /** ptr to previous node in thread or bucket */
  struct nodeST *pred;          /** parent node in tree */
  unsigned int level;           /** tree level */
  int group;                    /** for marking label */
  int incost,outcost;           /** costs to, from root of tree */
}nodeT;


/** boundary neighbor structure */
typedef struct neighborST{
  nodeT *neighbor;              /** neighbor node pointer */
  int arcrow;                   /** row of arc to neighbor */
  int arccol;                   /** col of arc to neighbor */
  int arcdir;                   /** direction of arc to neighbor */
}neighborT;


/** boundary data structure */
typedef struct boundaryST{
  nodeT node[1];                /** ground node pointed to by this boundary */
  neighborT* neighborlist;      /** list of neighbors of common boundary */
  nodeT **boundarylist;         /** list of nodes covered by common boundary */
  long nneighbor;               /** number of neighbor nodes of boundary */
  long nboundary;               /** number of nodes covered by boundary */
}boundaryT;

  
/** arc cost data structure */
typedef struct costST{
  short offset;                 /** offset of wrapped phase gradient from 0 */
  short sigsq;                  /** variance due to decorrelation */
  short dzmax;                  /** largest discontinuity on shelf */
  short laycost;                /** cost of layover discontinuity shelf */
}costT;


/** arc cost data structure for smooth costs */
typedef struct smoothcostST{
  short offset;                 /** offset of wrapped phase gradient from 0 */
  short sigsq;                  /** variance due to decorrelation */
}smoothcostT;


/** arc cost data structure for bidirectional scalar costs */
typedef struct bidircostST{
  short posweight;              /** weight for positive flows */
  short negweight;              /** weight for negative flows */
}bidircostT;


/** incremental cost data structure */
typedef struct incrcostST{
  short poscost;                /** cost for positive flow increment */
  short negcost;                /** cost for negative flow increment */
}incrcostT;


/** arc candidate data structure */
typedef struct candidateST{
  nodeT *from, *to;             /** endpoints of candidate arc */
  long violation;               /** magnitude of arc violation */
  int arcrow,arccol;            /** indexes into arc arrays */
  signed char arcdir;           /** direction of arc (1=fwd, -1=rev) */
}candidateT;


/** bucket data structure */
typedef struct bucketST{
  long size;                    /** number of buckets in list */
  long curr;                    /** current bucket index */
  long maxind;                  /** maximum bucket index */
  long minind;                  /** smallest (possibly negative) bucket index */
  nodeT **bucket;               /** array of first nodes in each bucket */
  nodeT **bucketbase;           /** real base of bucket array */
  signed char wrapped;          /** flag denoting wrapped circular buckets */
}bucketT;


/** secondary arc data structure */
typedef struct scndryarcST{
  int arcrow;                   /** row of arc in secondary network array */
  int arccol;                   /** col of arc in secondary network array */
  nodeT *from;                  /** secondary node at tail of arc */
  nodeT *to;                    /** secondary node at head of arc */
  signed char fromdir;          /** direction from which arc enters head */
}scndryarcT;


/** supplementary data structure for secondary nodes */
typedef struct nodesuppST{
  int row;                      /** row of node in primary network problem */
  int col;                      /** col of node in primary network problem */
  nodeT **neighbornodes;        /** pointers to neighboring secondary nodes */
  scndryarcT **outarcs;         /** pointers to secondary arcs to neighbors */
  int noutarcs;                 /** number of arcs from this node */
}nodesuppT;


/** run-time parameter data structure */
typedef struct paramST{

  /* SAR and geometry parameters */
  double orbitradius;     /** radius of platform orbit (meters) */
  double altitude;        /** SAR altitude (meters) */
  double earthradius;     /** radius of earth (meters) */
  double bperp;           /** nominal perpendiuclar baseline (meters) */
  signed char transmitmode; /** transmit mode (PINGPONG or SINGLEANTTRANSMIT) */
  double baseline;        /** baseline length (meters, always postive) */
  double baselineangle;   /** baseline angle above horizontal (rad) */
  long nlooksrange;       /** number of looks in range for input data */ 
  long nlooksaz;          /** number of looks in azimuth for input data */ 
  long nlooksother;       /** number of nonspatial looks for input data */ 
  double ncorrlooks;      /** number of independent looks in correlation est */
  long ncorrlooksrange;   /** number of looks in range for correlation */ 
  long ncorrlooksaz;      /** number of looks in azimuth for correlation */ 
  double nearrange;       /** slant range to near part of swath (meters) */
  double dr;              /** range bin spacing (meters) */
  double da;              /** azimuth bin spacing (meters) */
  double rangeres;        /** range resolution (meters) */
  double azres;           /** azimuth resolution (meters) */
  double lambda;          /** wavelength (meters) */

  /* scattering model parameters */
  double kds;             /** ratio of diffuse to specular scattering */
  double specularexp;     /** power specular scattering component */
  double dzrcritfactor;   /** fudge factor for linearizing scattering model */
  signed char shadow;     /** allow discontinuities from shadowing */
  double dzeimin;         /** lower limit for backslopes (if shadow = FALSE) */
  long laywidth;          /** width of window for summing layover brightness */
  double layminei;        /** threshold brightness for assuming layover */
  double sloperatiofactor;/** fudge factor for linearized scattering slopes */
  double sigsqei;         /** variance (dz, meters) due to uncertainty in EI */

  /* decorrelation model parameters */
  double drho;            /** step size of correlation-slope lookup table */
  double rhosconst1,rhosconst2;/** for calculating rho0 in biased rho */
  double cstd1,cstd2,cstd3;/** for calculating correlation power given nlooks */
  double defaultcorr;     /** default correlation if no correlation file */
  double rhominfactor;    /** threshold for setting unbiased correlation to 0 */

  /* pdf model parameters */
  double dzlaypeak;       /** range pdf peak for no discontinuity when bright */
  double azdzfactor;      /** fraction of dz in azimuth vs. rnage */
  double dzeifactor;      /** nonlayover dz scale factor */
  double dzeiweight;      /** weight to give dz expected from intensity */
  double dzlayfactor;     /** layover regime dz scale factor */
  double layconst;        /** normalized constant pdf of layover edge */
  double layfalloffconst; /** factor of sigsq for layover cost increase */
  long sigsqshortmin;     /** min short value for costT variance */
  double sigsqlayfactor;  /** fration of ambiguityheight^2 for layover sigma */

  /* deformation mode parameters */
  double defoazdzfactor;  /** scale for azimuth ledge in defo cost function */
  double defothreshfactor;/** factor of rho0 for discontinuity threshold */
  double defomax;         /** max discontinuity (cycles) from deformation */
  double sigsqcorr;       /** variance in measured correlation */
  double defolayconst;    /** layconst for deformation mode */

  /* algorithm parameters */
  signed char eval;       /** evaluate unwrapped input file if TRUE */
  signed char unwrapped;  /** input file is unwrapped if TRUE */
  signed char regrowconncomps;/** grow connected components and exit if TRUE */
  signed char initonly;   /** exit after initialization if TRUE */
  signed char initmethod; /** MST or MCF initialization */
  signed char costmode;   /** statistical cost mode */
  signed char dumpall;    /** dump intermediate files */
  signed char verbose;    /** print verbose output */
  signed char amplitude;  /** intensity data is amplitude, not power */
  signed char havemagnitude; /** flag: create correlation from other inputs */
  signed char flipphasesign; /** flag: flip phase and flow array signs */
  signed char onetilereopt;  /** flag: reoptimize full input after tile init */
  signed char rmtileinit; /** flag to remove temporary tile unw init soln */
  long initmaxflow;       /** maximum flow for initialization */
  long arcmaxflowconst;   /** units of flow past dzmax to use for initmaxflow */
  long maxflow;           /** max flow for tree solve looping */
  long krowei, kcolei;    /** size of boxcar averaging window for mean ei */
  long kpardpsi;          /** length of boxcar for mean wrapped gradient */
  long kperpdpsi;         /** width of boxcar for mean wrapped gradient */
  double threshold;       /** thershold for numerical dzrcrit calculation */
  double initdzr;         /** initial dzr for numerical dzrcrit calc. (m) */
  double initdzstep;      /** initial stepsize for spatial decor slope calc. */
  double maxcost;         /** min and max float values for cost arrays */
  double costscale;       /** scale factor for discretizing to integer costs */
  double costscaleambight;/** ambiguity height for auto costs caling */
  double dnomincangle;    /** step size for range-varying param lookup table */
  long srcrow,srccol;     /** source node location */
  double p;               /** power for Lp-norm solution (less than 0 is MAP) */
  signed char bidirlpn;   /** use bidirectional Lp costs if TRUE */
  long nshortcycle;       /** number of points for one cycle in short int dz */
  double maxnewnodeconst; /** number of nodes added to tree on each iteration */
  long maxnflowcycles;    /** max number of cycles to consider nflow done */
  double maxcyclefraction;/** ratio of max cycles to pixels */
  long nconnnodemin;      /** min number of nodes to keep in connected set */
  long cs2scalefactor;    /** scale factor for cs2 initialization (eg, 3-30) */
  long nmajorprune;       /** number of major iterations between tree pruning */
  long prunecostthresh;   /** cost threshold for pruning */
  long edgemasktop;       /** number of pixels to mask at top edge of input */
  long edgemaskbot;       /** number of pixels to mask at bottom edge */
  long edgemaskleft;      /** number of pixels to mask at left edge */
  long edgemaskright;     /** number of pixels to mask at right edge */
  long parentpid;         /** process identification number of parent */

  /* tiling parameters */
  long ntilerow;          /** number of tiles in azimuth */
  long ntilecol;          /** number of tiles in range */
  long rowovrlp;          /** pixels of overlap between row tiles */
  long colovrlp;          /** pixels of overlap between column tiles */
  long piecefirstrow;     /** first row (indexed from 1) for piece mode */
  long piecefirstcol;     /** first column (indexed from 1) for piece mode */
  long piecenrow;         /** number of rows for piece mode */
  long piecencol;         /** number of cols for piece mode */
  long tilecostthresh;    /** maximum cost within single reliable tile region */
  long minregionsize;     /** minimum number of pixels in a region */
  long nthreads;          /** number of parallel processes to run */
  long scndryarcflowmax;  /** max flow increment for which to keep cost data */
  double tileedgeweight;  /** weight applied to tile-edge secondary arc costs */
  signed char assembleonly; /** flag for assemble-only (no unwrap) mode */
  signed char rmtmptile;  /** flag for removing temporary tile files */
  char tiledir[MAXSTRLEN];/** directory for temporary tile files */

  /* connected component parameters */
  double minconncompfrac; /** min fraction of pixels in connected component */
  long conncompthresh;    /** cost threshold for connected component */
  long maxncomps;         /** max number of connected components */
  int conncompouttype;    /** flag for type of connected component output file */
  
}paramT;


/** input file name data structure */
typedef struct infileST{
  char infile[MAXSTRLEN];             /** input interferogram */
  char magfile[MAXSTRLEN];            /** interferogram magnitude (optional) */
  char ampfile[MAXSTRLEN];            /** image amplitude or power file */
  char ampfile2[MAXSTRLEN];           /** second amplitude or power file */
  char weightfile[MAXSTRLEN];         /** arc weights */
  char corrfile[MAXSTRLEN];           /** correlation file */
  char estfile[MAXSTRLEN];            /** unwrapped estimate */
  char costinfile[MAXSTRLEN];         /** file from which cost data is read */
  char bytemaskfile[MAXSTRLEN];       /** signed char valid pixel mask */
  char dotilemaskfile[MAXSTRLEN];     /** signed char tile unwrap mask file */
  signed char infileformat;           /** input file format */
  signed char unwrappedinfileformat;  /** input file format if unwrapped */
  signed char magfileformat;          /** interferogram magnitude file format */
  signed char corrfileformat;         /** correlation file format */
  signed char weightfileformat;       /** weight file format */
  signed char ampfileformat;          /** amplitude file format */
  signed char estfileformat;          /** unwrapped-estimate file format */
}infileT;


/** output file name data structure */
typedef struct outfileST{
  char outfile[MAXSTRLEN];            /** unwrapped output */
  char initfile[MAXSTRLEN];           /** unwrapped initialization */
  char flowfile[MAXSTRLEN];           /** flows of unwrapped solution */
  char eifile[MAXSTRLEN];             /** despckled, normalized intensity */
  char rowcostfile[MAXSTRLEN];        /** statistical azimuth cost array */
  char colcostfile[MAXSTRLEN];        /** statistical range cost array */
  char mstrowcostfile[MAXSTRLEN];     /** scalar initialization azimuth costs */
  char mstcolcostfile[MAXSTRLEN];     /** scalar initialization range costs */
  char mstcostsfile[MAXSTRLEN];       /** scalar initialization costs (all) */
  char corrdumpfile[MAXSTRLEN];       /** correlation coefficient magnitude */
  char rawcorrdumpfile[MAXSTRLEN];    /** correlation coefficient magnitude */
  char conncompfile[MAXSTRLEN];       /** connected component map or mask */
  char costoutfile[MAXSTRLEN];        /** file to which cost data is written */
  char logfile[MAXSTRLEN];            /** file to which parmeters are logged */
  signed char outfileformat;          /** output file format */
}outfileT;


/** tile parameter data structure */
typedef struct tileparamST{
  long firstcol;          /** first column of tile to process (index from 0) */
  long ncol;              /** number of columns in tile to process */
  long firstrow;          /** first row of tile to process (index from 0) */
  long nrow;              /** number of rows in tile to process */
}tileparamT;


/** connected component size structure */
typedef struct conncompsizeST{
  unsigned int tilenum;               /** tile index */
  unsigned int icomptile;             /** conn comp index in tile */
  unsigned int icompfull;             /** conn comp index in full array */
  long npix;                          /** number of pixels in conn comp */
}conncompsizeT;


/** type for total cost of solution (may overflow long) */
typedef double totalcostT;
#define INITTOTALCOST LARGEFLOAT



/***********************/
/* function prototypes */
/***********************/

/* functions in snaphu_tile.c */

/**
 * Sets up tile parameters and output file names for the current tile.
 */
int SetupTile(long nlines, long linelen, paramT *params, 
              tileparamT *tileparams, outfileT *outfiles, 
              outfileT *tileoutfiles, long tilerow, long tilecol);
/**
 * Read the tile mask if a file name is specified in the infiles structure,
 * otherwise return an array of all ones.
 */
signed char **SetUpDoTileMask(infileT *infiles, long ntilerow, long ntilecol);
/**
 * Grows contiguous regions demarcated by arcs whose residual costs are
 * less than some threshold.  Numbers the regions sequentially from 0.
 */
int GrowRegions(void **costs, short **flows, long nrow, long ncol, 
                incrcostT **incrcosts, outfileT *outfiles, 
                tileparamT *tileparams, paramT *params);
/**
 * Grows contiguous regions demarcated by arcs whose residual costs are
 * less than some threshold.  Numbers the regions sequentially from 1.
 * Writes out byte file of connected component mask, with 0 for any pixels
 * not assigned to a component.
 */
int GrowConnCompsMask(void **costs, short **flows, long nrow, long ncol, 
                      incrcostT **incrcosts, outfileT *outfiles, 
                      paramT *params);
/**
 * TODO: comment
 */
int AssembleTiles(outfileT *outfiles, paramT *params, 
                  long nlines, long linelen);


/* functions in snaphu_solver.c */

/**
 * TODO: comment
 */
int SetGridNetworkFunctionPointers(void);
/**
 * TODO: comment
 */
int SetNonGridNetworkFunctionPointers(void);
/**
 * Solves the nonlinear network optimization problem.
 */
long TreeSolve(nodeT **nodes, nodesuppT **nodesupp, nodeT *ground, 
               nodeT *source, candidateT **candidatelistptr, 
               candidateT **candidatebagptr, long *candidatelistsizeptr,
               long *candidatebagsizeptr, bucketT *bkts, short **flows, 
               void **costs, incrcostT **incrcosts, nodeT ***apexes, 
               signed char **iscandidate, long ngroundarcs, long nflow, 
               float **mag, float **wrappedphase, char *outfile, 
               long nnoderow, int *nnodesperrow, long narcrow, 
               int *narcsperrow, long nrow, long ncol,
               outfileT *outfiles, long nconnected, paramT *params);
/**
 * TODO: comment
 */
int InitNetwork(short **flows, long *ngroundarcsptr, long *ncycleptr, 
                long *nflowdoneptr, long *mostflowptr, long *nflowptr, 
                long *candidatebagsizeptr, candidateT **candidatebagptr, 
                long *candidatelistsizeptr, candidateT **candidatelistptr, 
                signed char ***iscandidateptr, nodeT ****apexesptr, 
                bucketT **bktsptr, long *iincrcostfileptr, 
                incrcostT ***incrcostsptr, nodeT ***nodesptr, nodeT *ground, 
                long *nnoderowptr, int **nnodesperrowptr, long *narcrowptr,
                int **narcsperrowptr, long nrow, long ncol, 
                signed char *notfirstloopptr, totalcostT *totalcostptr,
                paramT *params);
/**
 * TODO: comment
 */
long SetupTreeSolveNetwork(nodeT **nodes, nodeT *ground, nodeT ***apexes, 
                           signed char **iscandidate, long nnoderow,
                           int *nnodesperrow, long narcrow, int *narcsperrow,
                           long nrow, long ncol);
/**
 * Check magnitude masking to make sure we have at least one pixel
 * that is not masked; return 0 on success, or 1 if all pixels masked.
 */
signed char CheckMagMasking(float **mag, long nrow, long ncol);
/**
 * Set group numbers of nodes to MASKED if they are surrounded by
 * zero-magnitude pixels, 0 otherwise.
 */
int MaskNodes(long nrow, long ncol, nodeT **nodes, nodeT *ground, 
              float **mag);
/**
 * Return maximum flow magnitude that does not traverse an arc adjacent
 * to a masked interferogram pixel.
 */
long MaxNonMaskFlow(short **flows, float **mag, long nrow, long ncol);
/**
 * TODO: comment
 */
int InitNodeNums(long nrow, long ncol, nodeT **nodes, nodeT *ground);
/**
 * TODO: comment
 */
int InitNodes(long nrow, long ncol, nodeT **nodes, nodeT *ground);
/**
 * TODO: comment
 */
void BucketInsert(nodeT *node, long ind, bucketT *bkts);
/**
 * TODO: comment
 */
void BucketRemove(nodeT *node, long ind, bucketT *bkts);
/**
 * TODO: comment
 */
nodeT *ClosestNode(bucketT *bkts);
/**
 * Create a list of node pointers to be sources for each set of
 * connected pixels (not disconnected by masking).  Return the number
 * of sources (ie, the number of connected sets of pixels).
 */
long SelectSources(nodeT **nodes, float **mag, nodeT *ground, long nflow, 
                   short **flows, long ngroundarcs, 
                   long nrow, long ncol, paramT *params,
                   nodeT ***sourcelistptr, long **nconnectedarrptr);
/**
 * Updates the incremental cost for an arc.
 */
long ReCalcCost(void **costs, incrcostT **incrcosts, long flow, 
                long arcrow, long arccol, long nflow, long nrow, 
                paramT *params);
/**
 * Calculates the costs for positive and negative dflow flow increment
 * if there is zero flow on the arc.
 */
int SetupIncrFlowCosts(void **costs, incrcostT **incrcosts, short **flows,
                       long nflow, long nrow, long narcrow, 
                       int *narcsperrow, paramT *params);
/**
 * Computes the total cost of the flow array and prints it out.  Pass nrow
 * and ncol if in grid mode (primary network), or pass nrow=ntiles and 
 * ncol=0 for nongrid mode (secondary network).
 */
totalcostT EvaluateTotalCost(void **costs, short **flows, long nrow, long ncol,
                             int *narcsperrow,paramT *params);
/**
 * Initializes the flow on a the network using minimum spanning tree
 * algorithm.  
 */
int MSTInitFlows(float **wrappedphase, short ***flowsptr, 
                 short **mstcosts, long nrow, long ncol, 
                 nodeT ***nodes, nodeT *ground, long maxflow);
/**
 * Initializes the flow on a the network using minimum cost flow
 * algorithm.  
 */
int MCFInitFlows(float **wrappedphase, short ***flowsptr, short **mstcosts, 
                 long nrow, long ncol, long cs2scalefactor);


/**
 * Builds cost arrays for arcs based on interferogram intensity 
 * and correlation, depending on options and passed parameters.  
 */
int BuildCostArrays(void ***costsptr, short ***mstcostsptr, 
                    float **mag, float **wrappedphase, 
                    float **unwrappedest, long linelen, long nlines, 
                    long nrow, long ncol, paramT *params, 
                    tileparamT *tileparams, infileT *infiles, 
                    outfileT *outfiles);
/**
 * Calculates topography arc distance given an array of cost data structures.
 */
void CalcCostTopo(void **costs, long flow, long arcrow, long arccol, 
                  long nflow, long nrow, paramT *params, 
                  long *poscostptr, long *negcostptr);
/**
 * Calculates deformation arc distance given an array of cost data structures.
 */
void CalcCostDefo(void **costs, long flow, long arcrow, long arccol, 
                  long nflow, long nrow, paramT *params, 
                  long *poscostptr, long *negcostptr);
/**
 * Calculates smooth-solution arc distance given an array of smoothcost
 *  data structures.
 */
void CalcCostSmooth(void **costs, long flow, long arcrow, long arccol, 
                    long nflow, long nrow, paramT *params, 
                    long *poscostptr, long *negcostptr);
/**
 * Calculates the L0 arc distance given an array of short integer weights.
 */
void CalcCostL0(void **costs, long flow, long arcrow, long arccol, 
                long nflow, long nrow, paramT *params, 
                long *poscostptr, long *negcostptr);
/**
 * Calculates the L1 arc cost given an array of bidirectional cost weights.
 */
void CalcCostL1(void **costs, long flow, long arcrow, long arccol, 
                long nflow, long nrow, paramT *params, 
                long *poscostptr, long *negcostptr);
/**
 * Calculates the L2 arc distance given an array of short integer weights.
 */
void CalcCostL2(void **costs, long flow, long arcrow, long arccol, 
                long nflow, long nrow, paramT *params, 
                long *poscostptr, long *negcostptr);
/**
 * Calculates the Lp arc distance given an array of short integer weights.
 */
void CalcCostLP(void **costs, long flow, long arcrow, long arccol, 
                long nflow, long nrow, paramT *params, 
                long *poscostptr, long *negcostptr);
/**
 * Calculates the L0 arc cost given an array of bidirectional cost weights.
 */
void CalcCostL0BiDir(void **costs, long flow, long arcrow, long arccol, 
                     long nflow, long nrow, paramT *params, 
                     long *poscostptr, long *negcostptr);
/**
 * Calculates the L1 arc cost given an array of bidirectional cost weights.
 */
void CalcCostL1BiDir(void **costs, long flow, long arcrow, long arccol, 
                     long nflow, long nrow, paramT *params, 
                     long *poscostptr, long *negcostptr);
/**
 * Calculates the L2 arc cost given an array of bidirectional cost weights.
 */
void CalcCostL2BiDir(void **costs, long flow, long arcrow, long arccol, 
                     long nflow, long nrow, paramT *params, 
                     long *poscostptr, long *negcostptr);
/**
 * Calculates the Lp arc cost given an array of bidirectional cost weights.
 */
void CalcCostLPBiDir(void **costs, long flow, long arcrow, long arccol, 
                     long nflow, long nrow, paramT *params, 
                     long *poscostptr, long *negcostptr);
/**
 * Calculates the arc cost given an array of long integer cost lookup tables.
 *
 * The cost array for each arc gives the cost for +/-flowmax units of
 * flow around the flow value with minimum cost, which is not
 * necessarily flow == 0.  The offset between the flow value with
 * minimum cost and flow == 0 is given by arroffset = costarr[0].
 * Positive flow values k for k = 1 to flowmax relative to this min
 * cost flow value are in costarr[k].  Negative flow values k relative
 * to the min cost flow from k = -1 to -flowmax costarr[flowmax-k].
 * costarr[2*flowmax+1] contains a scaling factor for extrapolating
 * beyond the ends of the cost table, assuming quadratically (with an offset)
 * increasing cost (subject to rounding and scaling).
 *
 * As of summer 2019, the rationale for how seconeary costs are
 * extrapolated beyond the end of the table has been lost to time, but
 * the logic at least does give a self-consistent cost function that
 * is continuous at +/-flowmax and quadratically increases beyond,
 * albeit not necessarily with a starting slope that has an easily
 * intuitive basis.
 */
void CalcCostNonGrid(void **costs, long flow, long arcrow, long arccol, 
                     long nflow, long nrow, paramT *params, 
                     long *poscostptr, long *negcostptr);
/**
 * Calculates topography arc cost given an array of cost data structures.
 */
long EvalCostTopo(void **costs, short **flows, long arcrow, long arccol,
                  long nrow, paramT *params);
/**
 * Calculates deformation arc cost given an array of cost data structures.
 */
long EvalCostDefo(void **costs, short **flows, long arcrow, long arccol,
                  long nrow, paramT *params);
/**
 * Calculates smooth-solution arc cost given an array of 
 * smoothcost data structures.
 */
long EvalCostSmooth(void **costs, short **flows, long arcrow, long arccol,
                    long nrow, paramT *params);
/**
 * Calculates the L0 arc cost given an array of cost data structures.
 */
long EvalCostL0(void **costs, short **flows, long arcrow, long arccol,
                long nrow, paramT *params);
/**
 * Calculates the L1 arc cost given an array of cost data structures.
 */
long EvalCostL1(void **costs, short **flows, long arcrow, long arccol,
                long nrow, paramT *params);
/**
 * Calculates the L2 arc cost given an array of cost data structures.
 */
long EvalCostL2(void **costs, short **flows, long arcrow, long arccol,
                long nrow, paramT *params);
/**
 * Calculates the Lp arc cost given an array of cost data structures.
 */
long EvalCostLP(void **costs, short **flows, long arcrow, long arccol,
                long nrow, paramT *params);
/**
 * Calculates the L0 arc cost given an array of bidirectional cost structures.
 */
long EvalCostL0BiDir(void **costs, short **flows, long arcrow, long arccol,
                     long nrow, paramT *params);
/**
 * Calculates the L1 arc cost given an array of bidirectional cost structures.
 */
long EvalCostL1BiDir(void **costs, short **flows, long arcrow, long arccol,
                     long nrow, paramT *params);
/**
 * Calculates the L1 arc cost given an array of bidirectional cost structures.
 */
long EvalCostL2BiDir(void **costs, short **flows, long arcrow, long arccol,
                     long nrow, paramT *params);
/**
 * Calculates the Lp arc cost given an array of bidirectional cost structures.
 */
long EvalCostLPBiDir(void **costs, short **flows, long arcrow, long arccol,
                     long nrow, paramT *params);
/**
 * Calculates the arc cost given an array of long integer cost lookup tables.
 */
long EvalCostNonGrid(void **costs, short **flows, long arcrow, long arccol, 
                     long nrow, paramT *params);


/* functions in snaphu_util.c */

/**
 * Sets the value of a signed character based on the string argument passed.
 *
 * Returns TRUE if the string was not a valid value, FALSE otherwise.
 */
signed char SetBooleanSignedChar(signed char *boolptr, char *str);
/**
 * Makes sure the passed float array is properly wrapped into the [0,2pi)
 * interval.
 */
int WrapPhase(float **wrappedphase, long nrow, long ncol);
/**
 * Computes an array of wrapped phase differences in range (across rows).
 * Input wrapped phase array should be in radians.  Output is in cycles.
 */
int CalcWrappedRangeDiffs(float **dpsi, float **avgdpsi, float **wrappedphase,
                          long kperpdpsi, long kpardpsi,
                          long nrow, long ncol);
/**
 * Computes an array of wrapped phase differences in range (across rows).
 * Input wrapped phase array should be in radians. Output is in cycles.
 */
int CalcWrappedAzDiffs(float **dpsi, float **avgdpsi, float **wrappedphase,
                       long kperpdpsi, long kpardpsi, long nrow, long ncol);
/**
 * Computes the cycle array of a phase 2D phase array. Input arrays 
 * should be type float ** and signed char ** with memory pre-allocated.  
 * Numbers of rows and columns in phase array should be passed.  
 * Residue array will then have size nrow-1 x ncol-1.  Residues will
 * always be -1, 0, or 1 if wrapped phase is passed in.
 */
int CycleResidue(float **phase, signed char **residue, 
                 int nrow, int ncol);
/**
 * Compute residue of node from wrapped phase.  Assumes that memory
 * exists and that row and col are in bounds of the 2-D array of
 * wrapped phase values passed.
 */
int NodeResidue(float **wphase, long row, long col);
/**
 * Calculates flow based on unwrapped phase data in a 2D array.  
 * Allocates memory for row and column flow arrays.
 */
int CalcFlow(float **phase, short ***flowsptr, long nrow, long ncol);
/**
 * This function takes row and column flow information and integrates
 * wrapped phase to create an unwrapped phase field.  The unwrapped
 * phase field will be the same size as the wrapped field.  The array
 * rowflow should have size N-1xM and colflow size NxM-1 where the 
 * phase fields are NxM.  Output is saved to a file.
 */
int IntegratePhase(float **psi, float **phi, short **flows,
                   long nrow, long ncol);
/**
 * Given an unwrapped phase array, parse the data and find the flows.
 * Assumes only integer numbers of cycles have been added to get the 
 * unwrapped phase from the wrapped pase.  Gets memory and writes 
 * wrapped phase to passed pointer.  Assumes flows fit into short ints.
 */
float **ExtractFlow(float **unwrappedphase, short ***flowsptr, 
                    long nrow, long ncol);
/**
 * Flips the sign of all values in a passed array if the flip flag is set.
 * Otherwise, does nothing.
 */
int FlipPhaseArraySign(float **arr, paramT *params, long nrow, long ncol);
/**
 * Flips the sign of all values in a row-by-column array if the flip
 * flip flag is set.  Otherwise, does nothing.
 */
int FlipFlowArraySign(short **arr, paramT *params, long nrow, long ncol);
/**
 * Allocates memory for 2D array.
 *
 * Dynamically allocates memory and returns pointer of
 * type void ** for an array of size nrow x ncol.  
 * First index is row number: array[row][col]
 * size is size of array element, psize is size of pointer
 * to array element (eg sizeof(float *)).
 */
void **Get2DMem(int nrow, int ncol, int psize, size_t size);
/**
 * Allocates memory for 2D array.  The array will have 2*nrow-1 rows.
 * The first nrow-1 rows will have ncol columns, and the rest will
 * have ncol-1 columns.
 */
void **Get2DRowColMem(long nrow, long ncol, int psize, size_t size);
/**
 * Allocates memory for 2D array.  The array will have 2*nrow-1 rows.
 * The first nrow-1 rows will have ncol columns, and the rest will
 * have ncol-1 columns.  Memory is initialized to zero.
 */
void **Get2DRowColZeroMem(long nrow, long ncol, int psize, size_t size);

/**
 * Has same functionality as malloc(), but exits if out of memory.
 */
void *MAlloc(size_t size);
/**
 *
 * Allocates zero-initialized memory for an array of elements.
 *
 * This function has the same behavior as `calloc`, except that it does
 * not return on allocation failure. If memory cannot be allocated, an
 * error message is written to standard error and the process terminates.
 *
 * Parameters:
 * - `nitems`: Number of elements to allocate.
 * - `size`:   Size in bytes of each element.
 *
 * Returns:
 * - A pointer to zero-initialized memory on success.
 * - `NULL` if `size` is zero.
 *
 * Ownership:
 * The caller owns the returned memory and must release it using `free`.
 *
 * Safety notes for FFI:
 * - This function never returns on out-of-memory conditions.
 * - It does not set `errno`.
 * - Callers must not assume recoverable failure semantics.
 */
void *CAlloc(size_t nitems, size_t size);
/**
 * Has same functionality as realloc(), but exits if out of memory.
 */
void *ReAlloc(void *ptr, size_t size);
/**
 * This function frees the dynamically allocated memory for a 2D
 * array.  Pass in a pointer to a pointer cast to a void **.
 * The function assumes the array is of the form arr[rows][cols]
 * so that nrow is the number of elements in the pointer array.
 */
int Free2DArray(void **array, unsigned int nrow);
/**
 * Sets all entries of a 2D array of shorts to the given value.  Assumes
 * that memory is already allocated.
 */
int Set2DShortArray(short **arr, long nrow, long ncol, long value);
/**
 * Given a 2D floating point array, returns FALSE if any elements are NaN
 * or infinite, and TRUE otherwise.
 */
signed char ValidDataArray(float **arr, long nrow, long ncol);
/**
 * Given a 2D floating point array, returns FALSE if any elements are
 * NaN or infinite or negative, and TRUE otherwise.
 */
signed char NonNegDataArray(float **arr, long nrow, long ncol);
/**
 * This function takes a double and returns a nonzero value if 
 * the arguemnt is finite (not NaN and not infinite), and zero otherwise.
 * Different implementations are given here since not all machines have
 * these functions available.
 */
signed char IsFinite(double d);
/**
 * Rounds a floating point number to the nearest integer.  
 *
 * The function takes a float and returns a long.
 */
long LRound(double a);
/**
 * Return the lesser of two long integers as a long.
 */
long LMin(long a, long b);
/**
 * Clips the input long integer so that it is no less than minval and
 * no greater than maxval, and returns a long integer.
 */
long LClip(long a, long minval, long maxval);
/**
 * Returns the maximum of the absolute values of element in a 
 * two-dimensional short array.  The number of rows and columns 
 * should be passed in. 
 */
long Short2DRowColAbsMax(short **arr, long nrow, long ncol);
/**
 * Given an array of floats, interpolates at the specified noninteger
 * index.  Returns first or last array value if index is out of bounds.
 */
float LinInterp1D(float *arr, double index, long nelem);
/**
 * Given a 2-D array of floats, interpolates at the specified noninteger
 * indices.  Returns first or last array values if index is out of bounds.
 */
float LinInterp2D(float **arr, double rowind, double colind , 
                  long nrow, long ncol);
/**
 * Filters magnitude/power data with adaptive geometric filter to get rid of 
 * speckle.  Allocates 2D memory for ei.  Does not square before averaging.
 */
int Despeckle(float **mag, float ***ei, long nrow, long ncol);
/**
 * Returns pointer to 2D array where passed array is in center and
 * edges are padded by mirror reflections.  If the pad dimensions are
 * too large for the array size, a pointer to the original array is
 * returned.
 */
float **MirrorPad(float **array1, long nrow, long ncol, long krow, long kcol);
/**
 * Takes in a 2-D array, convolves with boxcar filter of size specified.  
 * Uses a recursion technique (but the function does not actually call
 * itself recursively) to compute the result, so there may be roundoff 
 * errors.
 */
int BoxCarAvg(float **avgarr, float **padarr, long nrow, long ncol, 
              long krow, long kcol);
/**
 * Just like strncpy(), but terminates string by putting a null 
 * character at the end (may overwrite last character).
 */
char *StrNCopy(char *dest, const char *src, size_t n);
/**
 * Given a wrapped phase array and an unwrapped phase array, subtracts
 * the unwrapped data elementwise from the wrapped data and stores
 * the result, rewrapped to [0,2pi), in the wrapped array.
 */
int FlattenWrappedPhase(float **wrappedphase, float **unwrappedest, 
                        long nrow, long ncol);
/**
 * Adds the values of two 2-D arrays elementwise.
 */
int Add2DFloatArrays(float **arr1, float **arr2, long nrow, long ncol);
/**
 * Uses strtod to convert a string to a double, but also does error checking.
 * If any part of the string is not converted, the function does not make
 * the assignment and returns TRUE.  Otherwise, returns FALSE.
 */
int StringToDouble(char *str, double *d);
/**
 * Uses strtol to convert a string to a base-10 long, but also does error 
 * checking.  If any part of the string is not converted, the function does 
 * not make the assignment and returns TRUE.  Otherwise, returns FALSE.
 */
int StringToLong(char *str, long *l);
/**
 * Traps common signals that by default cause the program to abort.  
 * Sets (pointer to function) Handler as the signal handler for all.
 * Note that SIGKILL usually cannot be caught.  No return value.
 */
int CatchSignals(void (*SigHandler)(int));
/**
 * Set the global variable dumpresults_global to TRUE if SIGINT or SIGHUP
 * signals recieved.  Also sets requestedstop_global if SIGINT signal 
 * received.  This function should only be called via signal() when 
 * a signal is caught.
 */ 
void SetDump(int signum);
/**
 * Signal handler that sends a KILL signal to all processes in the group
 * so that children exit when parent exits.
 */
void KillChildrenExit(int signum);
/**
 * Signal handler that prints message about the signal received, then exits.
 */
void SignalExit(int signum);
/**
 * Compares two long integers.  For use with qsort().
 */
int LongCompare(const void *c1, const void *c2);

/* functions in snaphu_io.c */

/**
 * Sets all parameters to their initial default values.
 */
int SetDefaults(infileT *infiles, outfileT *outfiles, paramT *params);
/**
 * Parses command line inputs passed to main().
 */
int ProcessArgs(int argc, char *argv[], infileT *infiles, outfileT *outfiles,
                long *ncolptr, paramT *params);
/**
 * Checks all parameters to make sure they are valid.  This is just a boring
 * function with lots of checks in it.
 */
int CheckParams(infileT *infiles, outfileT *outfiles, 
                long linelen, long nlines, paramT *params);
/**
 * Read in parameter values from a file, overriding existing parameters.
 */
int ReadConfigFile(char *conffile, infileT *infiles, outfileT *outfiles,
                   long *ncolptr, paramT *params);
/**
 * Writes a text log file of configuration parameters and other
 * information.  The log file is in a format compatible to be used as
 * a configuration file.  
 */
int WriteConfigLogFile(int argc, char *argv[], infileT *infiles, 
                       outfileT *outfiles, long linelen, paramT *params);
/**
 * Gets the number of lines of data in the input file based on the file 
 * size.
 */
long GetNLines(infileT *infiles, long linelen, paramT *params);
/**
 * Writes the unwrapped phase to the output file specified, in the
 * format given in the parameter structure.
 */
int WriteOutputFile(float **mag, float **unwrappedphase, char *outfile, 
                    outfileT *outfiles, long nrow, long ncol);
/**
 * Write data in a two dimensional array to a file.  Data elements are
 * have the number of bytes specified by size (use sizeof() when 
 * calling this function.  
 */
int Write2DArray(void **array, char *filename, long nrow, long ncol, 
                 size_t size);
/**
 * Write data in a 2-D row-and-column array to a file.  Data elements 
 * have the number of bytes specified by size (use sizeof() when 
 * calling this function.  The format of the array is nrow-1 rows
 * of ncol elements, followed by nrow rows of ncol-1 elements each.
 */
int Write2DRowColArray(void **array, char *filename, long nrow, 
                       long ncol, size_t size);
/**
 * Reads the input file specified on the command line.
 */
int ReadInputFile(infileT *infiles, float ***magptr, float ***wrappedphaseptr,
                  short ***flowsptr, long linelen, long nlines, 
                  paramT *params, tileparamT *tileparams);
/**
 * Reads the interferogram magnitude in the specfied file if it exists.
 * Memory for the magnitude array should already have been allocated by
 * ReadInputFile().
 */
int ReadMagnitude(float **mag, infileT *infiles, long linelen, long nlines, 
                  tileparamT *tileparams);
/**
 * Read signed byte mask value; set magnitude to zero where byte mask
 * is zero or where pixel is close enough to edge as defined by
 * edgemask parameters; leave magnitude unchanged otherwise.
 */
int ReadByteMask(float **mag, infileT *infiles, long linelen, long nlines, 
                 tileparamT *tileparams, paramT *params);
/**
 * Reads the unwrapped-phase estimate from a file (assumes file name exists).
 */
int ReadUnwrappedEstimateFile(float ***unwrappedestptr, infileT *infiles, 
                              long linelen, long nlines, 
                              paramT *params, tileparamT *tileparams);
/**
 * Read in weights form rowcol format file of short ints.
 */
int ReadWeightsFile(short ***weightsptr,char *weightfile, 
                    long linelen, long nlines, tileparamT *tileparams);
/**
 * Reads the intensity information from specified file(s).  If possilbe,
 * sets arrays for average power and individual powers of single-pass
 * SAR images.  
 */
int ReadIntensity(float ***pwrptr, float ***pwr1ptr, float ***pwr2ptr, 
                  infileT *infiles, long linelen, long nlines, 
                  paramT *params, tileparamT *tileparams);
/**
 * Reads the correlation information from specified file.
 */
int ReadCorrelation(float ***corrptr, infileT *infiles,
                    long linelen, long nlines, tileparamT *tileparams);
/**
 * Read in the data from a file containing magnitude and phase
 * data.  File should have one line of magnitude data, one line
 * of phase data, another line of magnitude data, etc.  
 * ncol refers to the number of complex elements in one line of 
 * data.  
 */
int ReadAltLineFile(float ***mag, float ***phase, char *alfile, 
                    long linelen, long nlines, tileparamT *tileparams);
/**
 * Read only the phase data from a file containing magnitude and phase
 * data.  File should have one line of magnitude data, one line
 * of phase data, another line of magnitude data, etc.  
 * ncol refers to the number of complex elements in one line of 
 * data. 
 */
int ReadAltLineFilePhase(float ***phase, char *alfile, 
                         long linelen, long nlines, tileparamT *tileparams);
/**
 * Reads file of complex floats of the form real,imag,real,imag...
 * ncol is the number of complex samples (half the number of real
 * floats per line).  Ensures that phase values are in the range 
 * [0,2pi).
 */
int ReadComplexFile(float ***mag, float ***phase, char *rifile, 
                    long linelen, long nlines, tileparamT *tileparams);
/**
 * Reads file of real data of size elsize.  Assumes the native byte order 
 * of the platform. 
 */
int Read2DArray(void ***arr, char *infile, long linelen, long nlines, 
                tileparamT *tileparams, size_t elptrsize, size_t elsize);
/**
 * Reads file of real alternating floats from separate images.  Format is
 * real0A, real0B, real1A, real1B, real2A, real2B,...
 * ncol is the number of samples in each image (note the number of
 * floats per line in the specified file).
 */
int ReadAltSampFile(float ***arr1, float ***arr2, char *infile,
                     long linelen, long nlines, tileparamT *tileparams);
/**
 * Gets memory and reads single array from a file.  Array should be in the 
 * file line by line starting with the row array (size nrow-1 x ncol) and
 * followed by the column array (size nrow x ncol-1).  Both arrays 
 * are placed into the passed array as they were in the file.
 */
int Read2DRowColFile(void ***arr, char *filename, long linelen, long nlines, 
                     tileparamT *tileparams, size_t size);
/**
 * Similar to Read2DRowColFile(), except reads only row (horizontal) data
 * at specified locations.  tileparams->nrow is treated as the number of
 * rows of data to be read from the RowCol file, not the number of 
 * equivalent rows in the orginal pixel file (whose arcs are represented
 * in the RowCol file).
 */
int Read2DRowColFileRows(void ***arr, char *filename, long linelen, 
                         long nlines, tileparamT *tileparams, size_t size);
/**
 * Sets names of output files so that the program will dump intermediate
 * arrays.  Only sets names if they are not set already.
 */
int SetDumpAll(outfileT *outfiles, paramT *params);
/**
 * Sets the default stream pointers (global variables).
 */
int SetStreamPointers(void);
/**
 * Set the global stream pointer sp2 to be stdout if the verbose flag
 * is set in the parameter data type.
 */
int SetVerboseOut(paramT *params);
/**
 * Dumps incremental cost arrays, creating file names for them.
 */
int DumpIncrCostFiles(incrcostT **incrcosts, long iincrcostfile, 
                      long nflow, long nrow, long ncol);
/**
 * Create a temporary directory for tile files in directory of output file.  
 * Save directory name in buffer in paramT structure.
 */
int MakeTileDir(paramT *params, outfileT *outfiles);
/**
 * Given a filename, separates it into path and base filename.  Output
 * buffers should be at least MAXSTRLEN characters, and filename buffer
 * should be no more than MAXSTRLEN characters.  The output path 
 * has a trailing "/" character.
 */
int ParseFilename(char *filename, char *path, char *basename);
/**
 * Set name of temporary tile-mode output assuming nominal output file
 * name is in string passed.  Write new name in string memory pointed
 * to by input.
 */
int SetTileInitOutfile(char *outfile, long pid);
/**
 * Sets parameters for each tile and calls UnwrapTile() to do the
 * unwrapping.
 */
int Unwrap(infileT *infiles, outfileT *outfiles, paramT *params, 
           long linelen, long nlines);
/**
 * This is the main phase unwrapping function for a single tile.
 */
int UnwrapTile(infileT *infiles, outfileT *outfiles, paramT *params, 
                tileparamT *tileparams, long nlines, long linelen);
/* functions in snaphu_cs2.c  */

/** SolveCS2 - formerly `main()` */
void SolveCS2(signed char **residue, short **mstcosts, long nrow, long ncol, 
              long cs2scalefactor, short ***flowsptr);


/** Entrypoint (`main()`)
 *
 * This function is meant to be used with a wrapper function, and it operates exactly like SNAPHU's main CLI interface.
 */
int run_main(int argc, char **argv);
/* end of snaphu.h */

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

  This code is derived from cs2 v3.7
  Written by Andrew V. Goldberg and Boris Cherkassky
  Modifications for use in snaphu by Curtis W. Chen 

  Header for cs2 minimum cost flow solver.  This file is included with
  a #include from snaphu_cs2.c.

  The cs2 code is used here with permission for strictly noncommerical
  use.  The original cs2 source code can be downloaded from
 
    <http://www.igsystems.com/cs2>

  The original cs2 copyright is stated as follows:

    COPYRIGHT C 1995 IG Systems, Inc.  Permission to use for
    evaluation purposes is granted provided that proper
    acknowledgments are given.  For a commercial licence, contact
    igsys@eclipse.net.
    
    This software comes with NO WARRANTY, expressed or implied. By way
    of example, but not limitation, we make no representations of
    warranties of merchantability or fitness for any particular
    purpose or that the use of the software components or
    documentation will not infringe any patents, copyrights,
    trademarks, or other rights.

  Copyright 2002 Board of Trustees, Leland Stanford Jr. University

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

/* defs.h */

/** Excess of the node */
typedef long excess_t;

/** Arc */
typedef  
   struct arc_st
{
   short            r_cap;           /** residual capasity */
   short            cost;            /** cost  of the arc*/
   struct node_st   *head;           /** head node */
   struct arc_st    *sister;         /** opposite arc */
}
  arc;

typedef  /** node */
   struct node_st
{
   arc              *first;           /** first outgoing arc */
   arc              *current;         /** current outgoing arc */
   arc              *suspended;
   double           price;            /** distance from a sink */
   struct node_st   *q_next;          /** next node in push queue */
   struct node_st   *b_next;          /** next node in bucket-list */
   struct node_st   *b_prev;          /** previous node in bucket-list */
   long             rank;             /** bucket number */
   excess_t         excess;           /** excess of the node */
   signed char      inp;              /** temporary number of input arcs */
} node;

typedef /** bucket */
   struct bucket_st
{
   node             *p_first;         /** 1st node with positive excess 
                                         or simply 1st node in the buket */
} bucket;

#endif /* SNAPHU_H */