aboutsummaryrefslogtreecommitdiff
path: root/noao/digiphot/photcal/mkobsfile/phagrow.x
blob: a8c6dfce37b039361e19d3a93f7e919936dae7f2 (plain) (blame)
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
include <time.h>
include <mach.h>
include <fset.h>
include "../lib/apfile.h"


# PH_AGROW - Compute the curve of growth using the data from the input
# photometry files, optional airmasses from the airmass file, and the
# initial values of the parameters.

procedure ph_agrow (apcat, magfd, logfd, mgd, imtable, id, x, y, nap, rap,
	mag, merr, naperts, params, lterms, smallap, largeap)

int	apcat			# the aperture correction file descriptor
int	magfd			# the output magnitude file descriptor
int	logfd			# the log file descriptor
pointer	mgd			# pointer to the plot metacode file
pointer	imtable			# pointer to the image symbol table
int	id[ARB]			# the star ids
real	x[ARB]			# the star x coordinates
real	y[ARB]			# the star y coordinates
int	nap[ARB]		# the array of aperture numbers
real	rap[naperts,ARB]	# input array of aperture radii
real	mag[naperts,ARB]	# input array of magnitudes / differences
real	merr[naperts,ARB]	# input array of magnitude errors
int	naperts			# the number of input apertures
double	params[ARB]		# the initial values of the parameters
int	lterms			# the number of terms to be fit
int	smallap			# the small aperture number
int	largeap			# the large aperture number

int	nimages
pointer	agr
int	stnsymbols()
int	ph_amfit()

begin
	if (logfd != NULL)
	    call ph_logtitle (logfd, apcat)

	nimages = stnsymbols (imtable, 0)
	if (nimages <= 0) {
	    call printf ("Error: There is no input data to fit\n")
	    if (logfd != NULL)
	        call fprintf (logfd, "There is no input data to fit\n")
	    return
	}

	# Allocate memory required for fitting.
	call ph_ameminit (agr, lterms, naperts)

	# Fit the seeing radii and the cog model parameters.
	if (ph_amfit (imtable, agr, nap, rap, mag, merr, naperts, params,
	    lterms) == ERR) {
	    call printf ("Error: The cog model fit did not converge\n")
	    if (logfd != NULL) {
		call ph_ishow (logfd, params, lterms)
	        call ph_pshow (logfd, agr, lterms)
	        call ph_rshow (logfd, imtable)
	        call fprintf (logfd,
		    "Error: The cog model fit did not converge\n")
	    }
	} else {
	    if (logfd != NULL) {
		call ph_ishow (logfd, params, lterms)
	        call ph_pshow (logfd, agr, lterms)
	        call ph_rshow (logfd, imtable)
	    }
	    call ph_aeval (imtable, agr, apcat, magfd, logfd, mgd, id, x, y,
	        nap, rap, mag, merr, naperts, smallap, largeap)
	    if (logfd != NULL)
		call ph_tfshow (logfd, agr, naperts)
	}

	# Free memory required for fitting.
	call ph_amemfree (agr)
end


# PH_LOGTITLE -- Print the title for the new log file entry

procedure ph_logtitle (logfd, apcat)

int	logfd			# the log file descriptor
int	apcat			# the aperture correction file descriptor

pointer	sp, afname, date
long	clktime()

begin
	# Allocate working space.
	call smark (sp)
	call salloc (afname, SZ_FNAME, TY_CHAR)
	call salloc (date, SZ_TIME, TY_CHAR)

	# Get the file name and the times.
	call fstats (apcat, F_FILENAME, Memc[afname], SZ_FNAME)
	call cnvtime (clktime (long(0)), Memc[date], SZ_TIME)

	call fprintf (logfd, "NEW LOGFILE ENTRY AT: %s\n")
	    call pargstr (Memc[date])
	call fprintf (logfd, "APFILE: %s\n\n")
	    call pargstr (Memc[afname])

	call sfree (sp)
end


# PH_AMEMINIT -- Allocate memory for doing the fit.

procedure ph_ameminit (agr, lterms, naperts)

pointer	agr			# pointer to the fitting structure
int	lterms			# the number of terms to fit
int	naperts			# the number of apertures

begin
	call malloc (agr, LEN_AGRSTRUCT, TY_STRUCT)

	call malloc (AGR_DM(agr), naperts, TY_DOUBLE)
	call malloc (AGR_DDDR(agr), naperts, TY_DOUBLE)
	call malloc (AGR_T(agr), lterms * naperts, TY_DOUBLE)
	call malloc (AGR_U(agr), lterms * lterms, TY_DOUBLE)
	call malloc (AGR_V(agr), lterms, TY_DOUBLE)
	call malloc (AGR_POLD(agr), lterms, TY_DOUBLE)
	call malloc (AGR_DP(agr), lterms, TY_DOUBLE)
	call malloc (AGR_PARAMS(agr), MAX_MTERMS, TY_DOUBLE)
	call malloc (AGR_PERRORS(agr), MAX_MTERMS, TY_DOUBLE)
	call malloc (AGR_PCLAMPS(agr), MAX_MTERMS, TY_DOUBLE)

	call malloc (AGR_RBAR(agr), naperts, TY_REAL)
	call malloc (AGR_W(agr), naperts, TY_REAL)
	call malloc (AGR_THEO(agr), naperts, TY_REAL)
	call malloc (AGR_ADOPT(agr), naperts, TY_REAL)
	call malloc (AGR_WOBS(agr), naperts, TY_REAL)
	call malloc (AGR_OBS(agr), naperts, TY_REAL)
	call malloc (AGR_WADO(agr), naperts, TY_REAL)

	call malloc (AGR_CUM(agr), naperts + 1, TY_REAL)
	call malloc (AGR_TCUM(agr), naperts + 1, TY_REAL)
	call malloc (AGR_WCUM(agr), naperts + 1, TY_REAL)
	call malloc (AGR_MAGS(agr), naperts, TY_REAL)
	call malloc (AGR_CMAGS(agr), naperts, TY_REAL)
	call malloc (AGR_TMAGS(agr), naperts, TY_REAL)
	call malloc (AGR_WMAGS(agr), naperts, TY_REAL)

	call calloc (AGR_AVE(agr), naperts, TY_REAL)
	call calloc (AGR_RESID(agr), naperts, TY_REAL)
	call calloc (AGR_RESSQ(agr), naperts, TY_REAL)
	call calloc (AGR_WR(agr), naperts, TY_REAL)
	call calloc (AGR_TAVE(agr), naperts, TY_REAL)
	call calloc (AGR_TRESID(agr), naperts, TY_REAL)
	call calloc (AGR_TRESSQ(agr), naperts, TY_REAL)
	call calloc (AGR_TWR(agr), naperts, TY_REAL)
end


# PH_AMFIT -- Fit the seeing disk widths and the model parameters.

int procedure ph_amfit (imtable, agr, nap, rap, mag, merr, naperts, params,
	lterms)

pointer	imtable			# pointer to the image symbol table
pointer	agr			# pointer to the fitting structure
int	nap[ARB]		# the array of aperture numbers
real	rap[naperts,ARB]	# input array of aperture radii
real	mag[naperts,ARB]	# input array of magnitudes / differences
real	merr[naperts,ARB]	# input array of magnitude errors
int	naperts			# the number of input apertures
double	params[ARB]		# the parameters to be fit
int	lterms			# number of terms to fit

double	pold, sumd, sumw, sumn, sumr, sumy, old
int	niter, i, j, k, nimages, ipow, nterms, iflag, ntimes, ngood
pointer	sp, sym, symbol
real	gain, rold, rclamp, dr
int	stnsymbols()
pointer	sthead(), stnext()

begin
	nimages = stnsymbols (imtable, 0)
	if (nimages <= 0)
	    return (ERR)

	# Allocate temporary space
	call smark (sp)
	call salloc (sym, nimages, TY_POINTER)

	# Order the symbol table.
	symbol = sthead (imtable)
	do k = nimages, 1, -1 {
	    Memi[sym+k-1] = symbol
	    symbol = stnext (imtable, symbol)
	}

	# Initialize some variables
	ipow = 1
	nterms = 0
	gain = 0.0
	pold = 0.0d0
	call aclrd (Memd[AGR_POLD(agr)], lterms)
	call ph_apinit (params, Memd[AGR_PARAMS(agr)], Memd[AGR_PERRORS(agr)],
	    Memd[AGR_PCLAMPS(agr)])

	# Compute an improved value for ro and for the stellar profile
	# model parameters.

	for (niter = 1; niter <= AGR_ITMAX; niter = niter + 1) {

	    sumd = 0.0d0
	    sumw = 0.0d0
	    sumn = 0.0d0

	    # Compute the number of terms to be fit this iteration.
	    call ph_anterms (niter, lterms, gain, nterms)

	    # Zero the accumulation matrix and vector
	    call aclrd (Memd[AGR_U(agr)], lterms * lterms)
	    call aclrd (Memd[AGR_V(agr)], lterms)

	    do k = 1, nimages {

		# Get the current symbol.
		symbol = Memi[sym+k-1]

		# Check to see if there is any data.
		if (IMT_NENTRIES(symbol) <= 0) {
		    IMT_RO(symbol) = INDEFR
		    next
		}

		# Check to see if there is any good data.
		ngood = 0
		do i = 1, IMT_NENTRIES(symbol) {
		    do j = 2, nap[i]
			ngood = ngood + 1
		}
		if (ngood <= 0) {
		    IMT_RO(symbol) = INDEFR
		    next
		}

		# Get better estimage of ro.
		if (niter == 1) {
		    if (k > 1 && ! IS_INDEFR(IMT_RO(Memi[sym+k-2]))) {
		        IMT_RO(symbol) = IMT_RO(Memi[sym+k-2])
		    } else
			IMT_RO(symbol) = 0.5 * rap[1,1]
		}

		# Set the model derivative vector
		call ph_adddr (rap[1,IMT_OFFSET(symbol)], Memd[AGR_DDDR(agr)],
		    naperts, Memd[AGR_PARAMS(agr)], IMT_RO(symbol),
		    IMT_NXAIRMASS(symbol))

		# Get the new estimate of ro
		rold = 0.0
		rclamp = IMT_RO(symbol) / 4.0
		ntimes = 0
		repeat {
		    
		    sumr = 0.0d0
		    sumy = 0.0d0

		    call ph_adddrdm (rap[1,IMT_OFFSET(symbol)], 
		        Memd[AGR_DM(agr)], Memd[AGR_DDDR(agr)], naperts,
			Memd[AGR_PARAMS(agr)], IMT_RO(symbol),
			IMT_NXAIRMASS(symbol), niter)

		    call ph_awsum (nap[IMT_OFFSET(symbol)],
		        mag[1,IMT_OFFSET(symbol)],
		        merr[1,IMT_OFFSET(symbol)], Memd[AGR_DM(agr)],
			Memr[AGR_W(agr)], Memd[AGR_DDDR(agr)], naperts,
			IMT_NENTRIES(symbol), ipow, sumr, sumy)

		    if (sumy > 0.0d0) {
			dr = sumr / sumy
			if (dr * rold < 0.0)
			    rclamp = 0.5 * rclamp
			IMT_RO(symbol) = IMT_RO(symbol) - dr / (1.0 + abs (dr /
			    rclamp))
			if (IMT_RO(symbol) <= EPSILONR) {
			    IMT_RO(symbol) = INDEFR
			    call sfree (sp)
			    return (ERR)
			}
			rold = dr
			if (abs (dr / IMT_RO(symbol)) <= 3.0e-4)
			    break
		    } else {
			IMT_RO(symbol) = INDEFR
		        break
		    }

		    ntimes = ntimes + 1
		    if (ntimes >= 100) {
			IMT_RO(symbol) = INDEFR
			call sfree (sp)
			return (ERR)
		    }
		}

		call ph_adp (rap[1,IMT_OFFSET(symbol)], Memd[AGR_DM(agr)],
		    Memd[AGR_T(agr)], naperts, lterms, nterms,
		    Memd[AGR_PARAMS(agr)], IMT_RO(symbol),
		    IMT_NXAIRMASS(symbol))

		call ph_aaccum (nap[IMT_OFFSET(symbol)],
		    mag[1,IMT_OFFSET(symbol)], merr[1,IMT_OFFSET(symbol)],
		    Memd[AGR_DM(agr)], Memr[AGR_W(agr)], naperts,
		    IMT_NENTRIES(symbol), Memd[AGR_T(agr)], Memd[AGR_U(agr)],
		    Memd[AGR_V(agr)], lterms, nterms, ipow, sumd, sumw, sumn)
	    }

	    # Invert the matrix.
	    call dinver (Memd[AGR_U(agr)], lterms, nterms, iflag)
	    if (iflag != 0) {
		call sfree (sp)
		return (ERR)
	    }

	    # Get new values for the parameters.
	    call dmvmul (Memd[AGR_U(agr)], lterms, nterms, Memd[AGR_V(agr)],
		Memd[AGR_DP(agr)])
	    call ph_apsolve (Memd[AGR_POLD(agr)], Memd[AGR_PARAMS(agr)],
	        Memd[AGR_DP(agr)], Memd[AGR_PCLAMPS(agr)], nterms, ipow)

	    # Test the fit.
	    #if (sumn > 6.0)
	    if (sumn > (nterms + 1.0))
	        #sumn = sqrt (sumd / (sumn - 6.0))
	        sumn = sqrt (sumd / (sumn - (nterms + 1.0)))
	    else
		sumn = 0.0
	    sumd = sqrt (sumd / sumw)
	    gain = 2.0 * abs (old - sumd) / (old + sumd)
	    old = sumd
	    if ((nterms < lterms) || (gain > 0.001)) {
		next
	    } else if (ipow <= 2) {
		ipow = 3
		call amovkd (0.1d0, Memd[AGR_PCLAMPS(agr)], 4)
		next
	    } else
		break
	}

	if (niter > AGR_ITMAX) {
	    call sfree (sp)
	    return (ERR)
	}

	# Compute the errors.
	do k = 1, nterms {
	    if (Memd[AGR_U(agr)+(k-1)*lterms+k-1] > 0.0)
	        Memd[AGR_PERRORS(agr)+k-1] =
	            sumn * sqrt (Memd[AGR_U(agr)+(k-1)*lterms+k-1])
	    else
	        Memd[AGR_PERRORS(agr)+k-1] = 0.0d0
	}


	call sfree (sp)
	return (OK)
end


# PH_ISHOW -- Show the initial values of the parameters.

procedure ph_ishow (fd, params, mterms)

int	fd			# pointer to the output file descriptor
double	params[ARB]		# the parameter values
int	mterms			# the number of terms to be fit

int	i

begin
	# Print out the best fit parameters.
	call fprintf (fd,
	    "\nThe initial cog model parameter values for nparams %d\n")
	    call pargi (mterms)
	do i = 1, MAX_MTERMS {
	    call fprintf (fd, "\t%10s: %15.7g\n")
		switch (i) {
		case 1:
		    call pargstr ("swings")
		case 2:
		    call pargstr ("pwings")
		case 3:
		    call pargstr ("pgauss")
		case 4:
		    call pargstr ("rgescale")
		case 5:
		    call pargstr ("xwings")
		}
		call pargd (params[i])
	}
	call fprintf (fd, "\n")
end


# PH_PSHOW -- Show the results of the parameter fitting.

procedure ph_pshow (fd, agr, mterms)

int	fd			# the output file descriptor
pointer	agr			# the pointer to the fitting descriptor
int	mterms			# the number of parameters to fit

begin
	call ph_pwrite (fd, Memd[AGR_PARAMS(agr)], Memd[AGR_PERRORS(agr)],
	    MAX_MTERMS, mterms)
end


# PH_RSHOW -- Show the computed seeing parameters as a function of image.

procedure ph_rshow (fd, imtable)

int	fd			# the output file descriptor
pointer	imtable			# pointer to the symbol table

int	i, nimages
pointer	sp, sym, symbol
int	stnsymbols()
pointer	sthead(), stnext()

begin
	nimages = stnsymbols (imtable, 0)
	if (nimages <= 0)
	    return

	# Allocate temporary space
	call smark (sp)
	call salloc (sym, nimages, TY_POINTER)

	# Order the symbol table.
	symbol = sthead (imtable)
	do i = nimages, 1, -1 {
	    Memi[sym+i-1] = symbol
	    symbol = stnext (imtable, symbol)
	}

	call fprintf (fd,
	    "\nThe seeing radius and assumed airmass for each image\n")
	do i = 1, nimages {
	    symbol = Memi[sym+i-1]
	    call fprintf (fd, "%30s  %8.4f  %8.3f\n")
		call pargstr (IMT_IMNAME(symbol))
		call pargr (IMT_RO(symbol))
		call pargr (IMT_XAIRMASS(symbol))
	}
	call fprintf (fd, "\n")

	call sfree (sp)
end


# PH_AEVAL -- Evaluate the fit for all the images.

procedure ph_aeval (imtable, agr, apcat, magfd, logfd, mgd, id, x, y, nap,
        rap, mag, merr, naperts, smallap, largeap)

pointer	imtable			# pointer to the image symbol table
pointer	agr			# pointer to the fitting structure
int	apcat			# the aperture correction file descriptor
int	magfd			# the best magnitudes file descriptor
int	logfd			# the log file descriptor
pointer	mgd			# pointer to the plot metacode file
int	id[ARB]			# the star ids
real	x[ARB]			# the star x coordinates
real	y[ARB]			# the star y coordinates
int	nap[ARB]		# the array of aperture numbers
real	rap[naperts,ARB]	# input array of aperture radii
real	mag[naperts,ARB]	# input array of magnitudes / differences
real	merr[naperts,ARB]	# input array of magnitude errors
int	naperts			# the number of input apertures
int	smallap			# the small aperture number
int	largeap			# the large aperture number

int	k, nimages
pointer	sp, sym, symbol
int	stnsymbols()
pointer	sthead(), stnext()

begin
	nimages = stnsymbols (imtable, 0)
	if (nimages <= 0)
	    return

	# Initialize some vectors.
	call aclrr (Memr[AGR_TAVE(agr)], naperts)
	call aclrr (Memr[AGR_TRESID(agr)], naperts)
	call aclrr (Memr[AGR_TRESSQ(agr)], naperts)
	call aclrr (Memr[AGR_TWR(agr)], naperts)

	# Allocate temporary space
	call smark (sp)
	call salloc (sym, nimages, TY_POINTER)

	# Order the symbol table.
	symbol = sthead (imtable)
	do k = nimages, 1, -1 {
	    Memi[sym+k-1] = symbol
	    symbol = stnext (imtable, symbol)
	}

	# Write the banner for the apfile.
	call fprintf (apcat,
        "# The aperture correction from apertures %d to %d in magnitudes\n\n")
	    call pargi (smallap)
	    call pargi (largeap)

	# Write the banner for the magfile.
	if (magfd != NULL) {
	    call fprintf (magfd, "# Magnitudes corrected to aperture %d\n\n")
	        call pargi (largeap)
	    call fprintf (magfd,
"#%19tImage%30tFilter%39tExptime%47tAirmass%62tOtime%70tXcenter%80tYcenter\
%93tMag%101tMerr%107tRadius\n\n")
	}

	# Compute the aperture corrections.
	do k = 1, nimages {

	    symbol = Memi[sym+k-1]

	    # Initialize some vectors.
	    call aclrr (Memr[AGR_AVE(agr)], naperts)
	    call aclrr (Memr[AGR_RESID(agr)], naperts)
	    call aclrr (Memr[AGR_RESSQ(agr)], naperts)
	    call aclrr (Memr[AGR_WR(agr)], naperts)

	    call aclrr (Memr[AGR_ADOPT(agr)], naperts)
	    call aclrr (Memr[AGR_WADO(agr)], naperts)
	    call aclrr (Memr[AGR_WOBS(agr)], naperts)

	    call ph_rinit (rap[1,IMT_OFFSET(symbol)], Memr[AGR_RBAR(agr)],
	        naperts)
	    call ph_tinit (rap[1,IMT_OFFSET(symbol)], Memr[AGR_THEO(agr)],
	        naperts, Memd[AGR_PARAMS(agr)], IMT_RO(symbol),
		IMT_NXAIRMASS(symbol))

	    # Accumulate the difference data.
	    call ph_taccum (nap[IMT_OFFSET(symbol)], mag[1,IMT_OFFSET(symbol)],
		merr[1,IMT_OFFSET(symbol)], Memr[AGR_THEO(agr)],
		Memr[AGR_W(agr)], Memr[AGR_ADOPT(agr)],
		Memr[AGR_WOBS(agr)], Memr[AGR_AVE(agr)],
		Memr[AGR_RESID(agr)], Memr[AGR_RESSQ(agr)],
		Memr[AGR_WR(agr)], Memr[AGR_OBS(agr)], Memr[AGR_WADO(agr)],
		naperts, IMT_NENTRIES(symbol))

	    # Compute the cumulative differences.
	    call ph_tcum (rap[1,IMT_OFFSET(symbol)], Memr[AGR_ADOPT(agr)],
		Memr[AGR_WADO(agr)], Memr[AGR_CUM(agr)], Memr[AGR_TCUM(agr)],
		Memr[AGR_WCUM(agr)], naperts, Memd[AGR_PARAMS(agr)],
		IMT_RO(symbol), IMT_NXAIRMASS(symbol))

	    # Write the aperture photometry file.
	    call ph_wapcat (apcat, IMT_IMNAME(symbol), IMT_RO(symbol),
	        Memr[AGR_ADOPT(agr)], Memr[AGR_WADO(agr)], naperts, smallap,
		largeap)

	    if (logfd != NULL) {
		call ph_twrite (logfd, IMT_IMNAME(symbol), IMT_RO(symbol),
		    IMT_XAIRMASS(symbol), Memr[AGR_RBAR(agr)],
		    Memr[AGR_THEO(agr)], Memr[AGR_OBS(agr)],
		    Memr[AGR_WOBS(agr)], Memr[AGR_ADOPT(agr)],
		    Memr[AGR_WADO(agr)], rap[1,IMT_OFFSET(symbol)],
		    Memr[AGR_CUM(agr)], Memr[AGR_TCUM(agr)],
		    Memr[AGR_WCUM(agr)], naperts)
		call fprintf (logfd, "\n")
		call ph_tmags (logfd, id[IMT_OFFSET(symbol)],
		    x[IMT_OFFSET(symbol)], y[IMT_OFFSET(symbol)],
		    nap[IMT_OFFSET(symbol)], rap[1,IMT_OFFSET(symbol)],
		    mag[1,IMT_OFFSET(symbol)], merr[1,IMT_OFFSET(symbol)],
		    Memr[AGR_ADOPT(agr)], Memr[AGR_W(agr)],
		    Memr[AGR_CUM(agr)], Memr[AGR_TCUM(agr)],
		    Memr[AGR_WCUM(agr)], Memr[AGR_MAGS(agr)],
		    Memr[AGR_CMAGS(agr)], Memr[AGR_TMAGS(agr)],
		    Memr[AGR_WMAGS(agr)], naperts, IMT_NENTRIES(symbol))
		call ph_papcor (logfd, IMT_IMNAME(symbol), IMT_RO(symbol),
		    rap[1,IMT_OFFSET(symbol)], Memr[AGR_ADOPT(agr)],
		    Memr[AGR_WADO(agr)], naperts, smallap, largeap)
		call fprintf (logfd, "\n")
	    }

	    if (magfd != NULL) {
		call ph_wmags (magfd, symbol, x[IMT_OFFSET(symbol)],
		    y[IMT_OFFSET(symbol)], nap[IMT_OFFSET(symbol)],
		    rap[1,IMT_OFFSET(symbol)], mag[1,IMT_OFFSET(symbol)],
		    merr[1,IMT_OFFSET(symbol)], Memr[AGR_ADOPT(agr)],
		    Memr[AGR_WADO(agr)], Memr[AGR_W(agr)], Memr[AGR_CUM(agr)],
		    Memr[AGR_WCUM(agr)], Memr[AGR_MAGS(agr)],
		    Memr[AGR_CMAGS(agr)], Memr[AGR_WMAGS(agr)], naperts,
		    IMT_NENTRIES(symbol), largeap)
	    }

	    if (mgd != NULL) {
		call ph_gimfit (mgd, agr, IMT_IMNAME(symbol), IMT_RO(symbol),
	            IMT_XAIRMASS(symbol), nap[IMT_OFFSET(symbol)],
		    nap[IMT_OFFSET(symbol)], rap[1,IMT_OFFSET(symbol)],
		    mag[1,IMT_OFFSET(symbol)], naperts,
		    IMT_NENTRIES(symbol), YES)
	        if (! IS_INDEFR(IMT_RO(symbol))) {
		    call ph_gaimres (mgd, agr, IMT_IMNAME(symbol),
		        IMT_RO(symbol), IMT_XAIRMASS(symbol),
			nap[IMT_OFFSET(symbol)], nap[IMT_OFFSET(symbol)],
			rap[1,IMT_OFFSET(symbol)], mag[1,IMT_OFFSET(symbol)],
			naperts, IMT_NENTRIES(symbol), YES)
		    call ph_gbimres (mgd, agr, IMT_IMNAME(symbol),
		        IMT_RO(symbol), IMT_XAIRMASS(symbol),
			nap[IMT_OFFSET(symbol)], nap[IMT_OFFSET(symbol)],
			mag[1,IMT_OFFSET(symbol)], naperts,
			IMT_NENTRIES(symbol), YES)
		    call ph_gaximres (mgd, agr, IMT_IMNAME(symbol),
		        IMT_RO(symbol), IMT_XAIRMASS(symbol),
		        nap[IMT_OFFSET(symbol)], nap[IMT_OFFSET(symbol)],
		        x[IMT_OFFSET(symbol)], mag[1,IMT_OFFSET(symbol)],
			naperts, IMT_NENTRIES(symbol), YES)
		    call ph_gayimres (mgd, agr, IMT_IMNAME(symbol),
		        IMT_RO(symbol), IMT_XAIRMASS(symbol),
			nap[IMT_OFFSET(symbol)], nap[IMT_OFFSET(symbol)],
			y[IMT_OFFSET(symbol)], mag[1,IMT_OFFSET(symbol)],
			naperts, IMT_NENTRIES(symbol), YES)
		    call ph_gacum (mgd, agr, IMT_IMNAME(symbol),
		        IMT_RO(symbol), IMT_XAIRMASS(symbol),
			nap[IMT_OFFSET(symbol)], nap[IMT_OFFSET(symbol)],
			rap[1,IMT_OFFSET(symbol)], mag[1,IMT_OFFSET(symbol)],
			naperts, IMT_NENTRIES(symbol), smallap, largeap, YES)
		}
	    }

	    if (! IS_INDEFR(IMT_RO(symbol))) {
	        call aaddr (Memr[AGR_AVE(agr)], Memr[AGR_TAVE(agr)],
	            Memr[AGR_TAVE(agr)], naperts)
	        call aaddr (Memr[AGR_RESID(agr)], Memr[AGR_TRESID(agr)],
	            Memr[AGR_TRESID(agr)], naperts)
	        call aaddr (Memr[AGR_RESSQ(agr)], Memr[AGR_TRESSQ(agr)],
	            Memr[AGR_TRESSQ(agr)], naperts)
	        call aaddr (Memr[AGR_WR(agr)], Memr[AGR_TWR(agr)],
	            Memr[AGR_TWR(agr)], naperts)
	    }
	}

	call sfree (sp)
end


# PH_A1EVAL -- Evaluate the fit for all the images.

procedure ph_a1eval (agr, image, r0, xairmass, nap, rap, mag, merr,
	naperts, npts)

pointer	agr			# pointer to the fitting structure
char	image[ARB]		# the image name
real	r0			# the seeing radius
real	xairmass		# the airmass value
int	nap[ARB]		# the number of apertures array 
real	rap[naperts,ARB]	# the list of aperture radii
real	mag[naperts,ARB]	# the magnitude difference array
real	merr[naperts,ARB]	# the magnitude error array
int	naperts			# the number of apertures
int	npts			# the number of points

begin
	# Initialize some vectors.
	call aclrr (Memr[AGR_AVE(agr)], naperts)
	call aclrr (Memr[AGR_RESID(agr)], naperts)
	call aclrr (Memr[AGR_RESSQ(agr)], naperts)
	call aclrr (Memr[AGR_WR(agr)], naperts)
	call aclrr (Memr[AGR_ADOPT(agr)], naperts)
	call aclrr (Memr[AGR_WOBS(agr)], naperts)

	# Compute the theoretical curve
	call ph_rinit (rap, Memr[AGR_RBAR(agr)], naperts)
	call ph_tinit (rap, Memr[AGR_THEO(agr)], naperts,
	    Memd[AGR_PARAMS(agr)], r0, xairmass)

	# Accumulate the difference data.
	call ph_taccum (nap, mag, merr, Memr[AGR_THEO(agr)], Memr[AGR_W(agr)],
	    Memr[AGR_ADOPT(agr)], Memr[AGR_WOBS(agr)], Memr[AGR_AVE(agr)],
	    Memr[AGR_RESID(agr)], Memr[AGR_RESSQ(agr)], Memr[AGR_WR(agr)],
	    Memr[AGR_OBS(agr)], Memr[AGR_WADO(agr)], naperts, npts)

	# Compute the cumulative differences.
	call ph_tcum (rap, Memr[AGR_ADOPT(agr)], Memr[AGR_WADO(agr)],
	    Memr[AGR_CUM(agr)], Memr[AGR_TCUM(agr)], Memr[AGR_WCUM(agr)],
	    naperts, Memd[AGR_PARAMS(agr)], r0, xairmass)
end


# PH_TFSHOW -- Compute and print the summary statistics.

procedure ph_tfshow (fd, agr, naperts)

int	fd			# the output file descriptor
pointer	agr			# the pointer to the fit structure
int	naperts			# the number of apertures

begin
	call ph_rwrite (fd, Memr[AGR_TAVE(agr)], Memr[AGR_TWR(agr)],
	    Memr[AGR_TRESID(agr)], Memr[AGR_TRESSQ(agr)], naperts)
end


# PH_AMEMFREE -- Free the memory used for doing the fit

procedure ph_amemfree (agr)

pointer	agr			# pointer to the fitting structure

begin
	call mfree (AGR_DM(agr), TY_DOUBLE)
	call mfree (AGR_DDDR(agr), TY_DOUBLE)
	call mfree (AGR_T(agr), TY_DOUBLE)
	call mfree (AGR_U(agr), TY_DOUBLE)
	call mfree (AGR_V(agr), TY_DOUBLE)
	call mfree (AGR_POLD(agr), TY_DOUBLE)
	call mfree (AGR_DP(agr), TY_DOUBLE)
	call mfree (AGR_PARAMS(agr), TY_DOUBLE)
	call mfree (AGR_PERRORS(agr), TY_DOUBLE)
	call mfree (AGR_PCLAMPS(agr), TY_DOUBLE)

	call mfree (AGR_RBAR(agr), TY_REAL)
	call mfree (AGR_W(agr), TY_REAL)
	call mfree (AGR_THEO(agr), TY_REAL)
	call mfree (AGR_WR(agr), TY_REAL)
	call mfree (AGR_ADOPT(agr), TY_REAL)
	call mfree (AGR_WOBS(agr), TY_REAL)
	call mfree (AGR_OBS(agr), TY_REAL)
	call mfree (AGR_WADO(agr), TY_REAL)

	call mfree (AGR_CUM(agr), TY_REAL)
	call mfree (AGR_TCUM(agr), TY_REAL)
	call mfree (AGR_WCUM(agr), TY_REAL)
	call mfree (AGR_MAGS(agr), TY_REAL)
	call mfree (AGR_CMAGS(agr), TY_REAL)
	call mfree (AGR_TMAGS(agr), TY_REAL)
	call mfree (AGR_WMAGS(agr), TY_REAL)

	call mfree (AGR_AVE(agr), TY_REAL)
	call mfree (AGR_RESID(agr), TY_REAL)
	call mfree (AGR_RESSQ(agr), TY_REAL)
	call mfree (AGR_TAVE(agr), TY_REAL)
	call mfree (AGR_TRESID(agr), TY_REAL)
	call mfree (AGR_TRESSQ(agr), TY_REAL)
	call mfree (AGR_TWR(agr), TY_REAL)

	call mfree (agr, TY_STRUCT)
end


# PH_AGETP -- Fetch the initial values of the parameters for the cog model.

procedure ph_agetp (params)

double	params[ARB]

real	clgetr()

begin
	params[1] = clgetr ("swings")
	params[2] = clgetr ("pwings")
	params[3] = clgetr ("pgauss")
	params[4] = clgetr ("rgescale")
	params[5] = clgetr ("xwings")
end


# PH_APINIT -- Set the initial values for the curve of growth model parameters.

procedure ph_apinit (iparams, oparams, perrors, pclamps) 

double	iparams[ARB]		# the input parameters array
double	oparams[ARB]		# the output parameters array
double	perrors[ARB]		# the parameter errors array
double	pclamps[ARB]		# array of parameter clamps

begin
	call amovd (iparams, oparams, MAX_MTERMS)
	call aclrd (perrors, MAX_MTERMS)
	call amovkd (0.2d0, pclamps, MAX_MTERMS)
	pclamps[4] = 0.5d0
end


# PH_ANTERMS -- Compute the number of terms to use in the fit.

procedure ph_anterms (niter, lterms, gain, nterms)

int	niter			# the current iteration
int	lterms			# the maximum number of terms to be fit
real	gain			# the current value of the gain
int	nterms			# the current number of terms to be fit

int	n

begin
	n = 1
	if (nterms >= 1 && gain <= 0.04) {
	    n = 2
	    if (nterms >= 2 && gain <= 0.016) {
	        n = 3
		if (nterms >= 3 && gain <= 0.006) {
	            n = 4
		    if (nterms >= 4 && gain <= 0.0025)
	    	        n = 5
		}
	    }
	}

	nterms = min (n, lterms)
end


# PH_ADDDR -- Compute the derivative wrt ro vector.

procedure ph_adddr (rap, dddr, naperts, params, r0, xairmass)

real	rap[ARB]		# array of aperture radii
double  dddr[ARB]		# the output derivatives array
int	naperts			# the number of apertures
double  params[ARB]		# the input parameter array
real	r0			# the current value of r0
real	xairmass		# the current value of the airmass

int	i
double	ph_dmag()

begin
	do i = 2, naperts {
	    dddr[i] = 500.0d0 * (ph_dmag (rap[i-1], rap[i], xairmass,
	        r0 - 0.001, params) - ph_dmag (rap[i-1], rap[i], xairmass,
		r0 + 0.001, params))
	}
end


# PH_ADDDRDM -- Compute the derivative wrt ro vector.

procedure ph_adddrdm (rap, dm, dddr, naperts, params, r0, xairmass, niter)

real	rap[ARB]		# array of aperture radii
double	dm[ARB]			# the output model differences array
double  dddr[ARB]		# the output derivatives array
int	naperts			# the number of apertures
double  params[ARB]		# the input parameter array
real	r0			# the current value of r0
real	xairmass		# the current value of the airmass
int	niter			# the current iteratiom

int	i
double	ph_dmag()

begin
	do i = 2, naperts {
	    dm[i] = ph_dmag (rap[i-1], rap[i], xairmass, r0, params)
	    #if (niter == 1)
	        dddr[i] = 500.0d0 * (ph_dmag (rap[i-1], rap[i], xairmass,
	            r0 - 0.001, params) - ph_dmag (rap[i-1], rap[i], xairmass,
		    r0 + 0.001, params))
	}
end


# PH_AWSUM -- Accumulate the weighted sums necessary to fit r0.

procedure ph_awsum (nap, mag, merr, dm, w, dddr, naperts, npts, ipow,
	sumr, sumy)

int	nap[ARB]			# array of aperture numbers
real	mag[naperts,ARB]		# array of magnitude difference
real	merr[naperts,ARB]		# array of magnitude errors
double	dm[ARB]				# array of model differences
real	w[ARB]				# array of weights
double	dddr[ARB]			# array of model derivatives
int	naperts				# number of apertures
int	npts				# number of data points
int	ipow				# weighting power factor
double	sumr, sumy			# the output sums

int	i, j
real	diff, wt

begin
	do i = 1, npts {
	    w[1] = 1.0d0
	    if (nap[i] <= 1)
		next
	    do j = 2, nap[i] {
		diff = mag[j,i] - dm[j]
		w[j] = 1.0 / (1.0 + abs (diff / (2.0 * merr[j,i])) **
		    ipow)
		w[j] = min (w[j], w[j-1])
		wt = w[j] / merr[j,i] ** 2
		sumr = sumr + wt * diff * dddr[j]
		sumy = sumy + wt * dddr[j] ** 2
	    }
	}
end


# PH_ADP -- Compute the parameter derivative vector with the new
# value of r0.

procedure ph_adp (rap, dm, t, naperts, lterms, nterms, params, r0, xairmass)

real	rap[ARB]		# array of aperture radii
double	dm[ARB]			# the new model differences
double	t[lterms,ARB]		# the parameter derivatives matrix
int	naperts			# the number of apertures
int	lterms			# the size of the derivatives matrix
int	nterms			# the number of terms to be fit
double	params[ARB]		# the current model parameter values
real	r0			# the current r0 value
real	xairmass		# the current airmass

int	i, j
double	ph_dmag()

begin
	do j = 2, naperts {
	    dm[j] = ph_dmag (rap[j-1], rap[j], xairmass, r0, params)
	    do i = 1, nterms {
		params[i] = params[i] - 0.001
		t[i,j] = ph_dmag (rap[j-1], rap[j], xairmass, r0, params)
		params[i] = params[i] + 0.002
		t[i,j] = 500.0d0 * (t[i,j] - ph_dmag (rap[j-1], rap[j],
		    xairmass, r0, params))
		params[i] = params[i] - 0.001
	    }
	}
end


# PH_AACCUM -- Accumulate the matrix and vector required to solve for the
# parameter increments

procedure ph_aaccum (nap, mag, merr, dm, w, naperts, npts, t, u, v, lterms,
	nterms, ipow, sumd, sumw, sumn)

int	nap[ARB]			# array of aperture numbers
real	mag[naperts,ARB]		# array of magnitude difference
real	merr[naperts,ARB]		# array of magnitude errors
double	dm[ARB]				# array of model differences
real	w[ARB]				# array of weights
int	naperts				# number of apertures
int	npts				# number of data points
double	t[lterms,ARB]			# the array of parameter derivatives
double  u[lterms,ARB]			# the matrix to be accumulated
double	v[ARB]				# the vector to be accumulated
int	lterms				# the maximum number of terms to fit
int	nterms				# the current number of terms to fit
int	ipow				# power factor for the weights
double	sumd				# sum of the differences
double	sumw				# sum of the scatter
double	sumn				# sum of the weights

int	i, j, l, m
real	diff, wt

begin
	do i = 1, npts {
	    w[1] = 1.0
	    if (nap[i] <= 1)
		next
	    do j = 2, nap[i] {
		diff = mag[j,i] - dm[j]
		w[j] = 1.0 / (1.0 + abs (diff / (2.0 * merr[j,i])) ** ipow)
		w[j] = min (w[j], w[j-1])
		wt = w[j] / merr[j,i] ** 2
		sumd = sumd + wt * diff ** 2
		sumw = sumw + wt
		sumn = sumn + w[j]
		do l = 1, nterms {
		    v[l] = v[l] + wt * diff * t[l,j]
		    do m = 1, nterms
			u[l,m] = u[l,m] + wt * t[l,j] * t[m,j]
		}
	    }
	}
end


# PH_APSOLVE -- Solve for new values of the parameters.

procedure ph_apsolve (pold, params, dp, pclamps, nterms, ipow)

double	pold[ARB]		# the previous parameter imcrement values
double	params[ARB]		# the current values of the parameters
double	dp[ARB]			# the parameter increment values
double	pclamps[ARB]		# the parameter clamp values
int	nterms			# the number of terms that were fit
int	ipow			# the current weighting factor

int	i

begin
	do i = 1, nterms {
	    if (dp[i] * pold[i] < 0.0d0)
		pclamps[i] = 0.5 * pclamps[i]
	    pold[i] = dp[i]
	}

	params[1] = params[1] - dp[1] / ( 1.0d0 + abs (dp[1] / (pclamps[1] *
	    (params[1] - 1.0d0))))
	if (nterms >= 2) {
	    params[2] = params[2] - dp[2] / (1.0d0 + abs (dp[2] / (pclamps[2] *
		params[2] * (1.0d0 - params[2]))))
	    if (nterms >= 3) {
		params[3] = params[3] - dp[3] / (1.0d0 + abs (dp[3] /
		    (pclamps[3] * params[3] * (1.0d0 - params[3]))))
		if (ipow == 1) {
		    ipow = 2
		    pclamps[1] = 0.1d0
		    pclamps[2] = 0.1d0
		}
		if (nterms >= 4) {
		    params[4] = params[4] - dp[4] / (1.0d0 + abs (dp[4] /
			(pclamps[4] * params[4])))
		    if (nterms >= 5)
			params[5] = params[5] - dp[5] / (1.0d0 + abs (dp[5] /
			    (pclamps[5] * params[2])))
		}
	    }
	}
end

# PH_PWRITE -- Write out the theoetical model parameters.

procedure ph_pwrite (fd, params, perrors, max_nterms, nterms)

int	fd			# the output file descriptor
double	params[ARB]		# the current model parameter values
double	perrors[ARB]		# the current parameter errors
int	max_nterms		# the number of terms
int	nterms			# the number of terms to fit

int	i

begin
	# Print out the best fit parameters.
	call fprintf (fd,
	"\nThe computed cog model parameters and their errors for nparams %d\n")
	    call pargi (nterms)
	do i = 1, max_nterms {
	    call fprintf (fd, "\t%10s: %15.7g +/- %15.7g\n")
		switch (i) {
		case 1:
		    call pargstr ("swings")
		case 2:
		    call pargstr ("pwings")
		case 3:
		    call pargstr ("pgauss")
		case 4:
		    call pargstr ("rgescale")
		case 5:
		    call pargstr ("xwings")
		}
		call pargd (params[i])
		call pargd (perrors[i])
	}
	call fprintf (fd, "\n")
end

# PH_RINIT -- Initialize the rbar vector.

procedure ph_rinit (rap, rbar, naperts)

real	rap[ARB]		# the array of aperture radii
real	rbar[ARB]		# the mean radius estimates
int	naperts			# the number of aperture radii

int	j

begin
	do j = 2, naperts 
	    rbar[j] = 0.5 * (rap[j-1] + rap[j])
end

# PH_TINIT -- Initialize the rbar vector and compute the theoretical estimates.

procedure ph_tinit (rap, theo, naperts, params, r0, airmass)

real	rap[ARB]		# the array of aperture radii
real	theo[ARB]		# the current model estimates
int	naperts			# the number of aperture radii
double	params[ARB]		# the current parameter estimates
real	r0			# the seeing radius
real	airmass			# the airmass value

int	j
double	ph_dmag()

begin
	if (IS_INDEFR(r0))
	    call amovkr (INDEFR, theo[2], naperts - 1)
	else {
	    do j = 2, naperts 
	        theo[j] = ph_dmag (rap[j-1], rap[j], airmass, r0, params)
	}
end


# PH_TACCUM -- Accumulate the data.

procedure ph_taccum (nap, mag, merr, theo, w, adopt, wobs, ave, resid, ressq,
	wr, obs, wado, naperts, npts)

int	nap[ARB]			# array of aperture numbers
real	mag[naperts,ARB]		# the array of magnitude differences
real	merr[naperts,ARB]		# the array of magnitude errors
real	theo[ARB]			# the current model values
real	w[ARB]				# the working weight array
real	adopt[ARB]			# the adopted weight differences
real	wobs[ARB]			# the sum of the weights
real	ave[ARB]			# the average model values
real	resid[ARB]			# the residuals
real	ressq[ARB]			# the residuals squared
real	wr[ARB]				# the sum of the weights
real	obs[ARB]			# the observations
real	wado[ARB]			# the error in the observations
int	naperts				# the number of apertures
int	npts				# the number of npts

int	i, j
real	diff, wt, scale

begin
	do i = 1, npts {
	    w[1] = 1.0
	    if (nap[i] <= 1)
		next
	    do j = 2, nap[i] {
		if (IS_INDEFR(theo[j])) {
		    wt = 1.0 / merr[j,i] ** 2
		    ave[1] = INDEFR
		    ave[j] = INDEFR
		    resid[1] = INDEFR
		    resid[j] = INDEFR
		    ressq[1] = INDEFR
		    ressq[j] = INDEFR
		    wr[1] = INDEFR
		    wr[j] = INDEFR
		} else {
		    diff = mag[j,i] - theo[j]
		    w[j] = 1.0 / (1.0 + abs (diff / (2.0 * merr[j,i])))
		    w[j] = min (w[j], w[j-1])
		    wt = w[j] / merr[j,i] ** 2
		    ave[1] = ave[1] + wt * theo[j]
		    ave[j] = ave[j] + wt * theo[j]
		    resid[1] = resid[1] + wt * diff
		    resid[j] = resid[j] + wt * diff
		    ressq[1] = ressq[1] + wt * diff ** 2
		    ressq[j] = ressq[j] + wt * diff ** 2
		    wr[1] = wr[1] + wt
		    wr[j] = wr[j] + wt
		}
		adopt[j] = adopt[j] + wt * mag[j,i]
		wobs[j] = wobs[j] + wt
	    }
	}

	do j = 2, naperts {
	    if (wobs[j] <= 0.0)
		next
	    obs[j] = adopt[j] / wobs[j]
	    adopt[j] = 0.0
	    wobs[j] = 0.0
	}

	do i = 1, npts {
	    w[1] = 1.0
	    if (nap[i] <= 1)
		next
	    do j = 2, nap[i] {
		diff = mag[j,i] - obs[j]
		w[j] = 1.0 / (1.0 + abs (diff / (2.0 * merr[j,i])) ** 2)
		w[j] = min (w[j], w[j-1])
		wt = w[j] / merr[j,i] ** 2
		adopt[j] = adopt[j] + wt * mag[j,i]
		wobs[j] = wobs[j] + wt
	    }
	}

	do j = 2, naperts {
	    if (wobs[j] <= 0.0)
		next
	    obs[j] = adopt[j] / wobs[j]
	    adopt[j] = 0.0
	    wobs[j] = 0.0
	}

	do i = 1, npts {
	    w[1] = 1.0
	    if (nap[i] <= 1)
		next
	    do j = 2, nap[i] {
		diff = mag[j,i] - obs[j]
		w[j] = 1.0 / (1.0 + abs (diff / (2.0 * merr[j,i])) ** 3)
		w[j] = min (w[j], w[j-1])
		wt = w[j] / merr[j,i] ** 2
		adopt[j] = adopt[j] + wt * mag[j,i]
		wobs[j] = wobs[j] + wt
	    }
	}

	scale = 0.1
	do j = 2, naperts {
	    if (wobs[j] > 0.0) {
		obs[j] = adopt[j] / wobs[j]
		if (IS_INDEFR(theo[j]))
		    wt = 0.0
		else {
		    wt = 1.0 / (scale * theo[j]) ** 2
		    adopt[j] = adopt[j] + wt * theo[j]
		}
		wt = 1.0 / (wobs[j] + wt)
		adopt[j] = wt * adopt[j]
		#wado[j] = sqrt (wt)
		wado[j] = sqrt (wt + (scale * adopt[j]) ** 2)
		wobs[j] = sqrt (1.0 / wobs[j])
	    } else {
		adopt[j] = theo[j]
		if (IS_INDEFR(theo[j])) {
		    wado[j] = INDEFR
		    obs[j] = INDEFR
		    wobs[j] = INDEFR
		} else
		    wado[j] = 2.0 * scale * abs (theo[j])
	    }
	}
end


# PH_TCUM -- Compute the cumulative differences.

procedure ph_tcum (rap, adopt, wado, cum, tcum, wcum, naperts, params,
	r0, airmass)

real	rap[ARB]		# the list of aperture radii
real	adopt[ARB]		# the adopted differences
real	wado[ARB]		# the errors in the adopted differences
real	cum[ARB]		# the accumulated differences
real	tcum[ARB]		# the total accumulated differences
real	wcum[ARB]		# the accumulated difference errors
int	naperts			# the number of aperture radii
double	params[ARB]		# the current parameter values
real	r0			# the seeing radius
real	airmass			# the airmass

int	i
double	ph_dmag()

begin
	if (IS_INDEFR(r0)) {
	    call amovkr (INDEFR, cum, naperts + 1)
	    call amovkr (INDEFR, tcum, naperts + 1)
	    call amovkr (INDEFR, wcum, naperts + 1)
	} else {
	    cum[naperts+1] = 0.0
	    tcum[naperts+1] = ph_dmag (rap[naperts], 2.0 * rap[naperts],
	        airmass, r0, params)
	    wcum[naperts+1] = 0.0
	    do i = naperts, 2, -1 {
	        cum[i] = adopt[i] + cum[i+1]
	        tcum[i] = adopt[i] + tcum[i+1]
	        wcum[i] = wado[i] ** 2 + wcum[i+1]
	    }
	}
end


# PH_WAPCAT -- Write the image entry to the aperture correction catalog.

procedure ph_wapcat (apcat, image, r0, adopt, wado, naperts, smallap, largeap)

int	apcat			# the aperture correction catalog descriptor
char	image[ARB]		# the image name
real	r0			# the seeing radius
real	adopt[ARB]		# the adopted difference values
real	wado[ARB]		# the adopted difference errors
int	naperts			# the number of apertures
int	smallap			# the small aperture number
int	largeap			# the large aperture number

int	i
real	cum, wcum

begin
	if (IS_INDEFR(r0)) {
	    cum = INDEFR
	    wcum = INDEFR
	} else {
	    cum = 0.0
	    wcum = 0.0
	    do i = largeap, smallap + 1, -1 {
	        cum = cum + adopt[i]
	        wcum = wcum + wado[i] ** 2
	    }
	    wcum = sqrt (wcum)
	}
	call fprintf (apcat, "%s %g %g\n")
	    call pargstr (image)
	    call pargr (cum)
	    call pargr (wcum)
end


# PH_PAPCOR -- Print the aperture correction on the standard output.

procedure ph_papcor (fd, image, r0, rap, adopt, wado, naperts, smallap, largeap)

int	fd			# the output file descriptor
char	image[ARB]		# the image name
real	r0			# the seeing radius
real	rap[ARB]		# the aperture radii
real	adopt[ARB]		# the adopted difference values
real	wado[ARB]		# the adopted difference errors
int	naperts			# the number of apertures
int	smallap			# the small aperture number
int	largeap			# the large aperture number

int	i
real	cum, wcum

begin
	if (IS_INDEFR(r0)) {
	    cum = INDEFR
	    wcum = INDEFR
	}  else {
	    cum = 0.0
	    wcum = 0.0
	    do i = largeap, smallap + 1, -1 {
	        cum = cum + adopt[i]
	        wcum = wcum + wado[i] ** 2
	    }
	    wcum = sqrt (wcum)
	}

	call fprintf (fd,
	    "Image: %s rin=%.2f rout=%.2f apercor=%.3f +/- %.4f\n")
	    call pargstr (image)
	    call pargr (rap[smallap])
	    call pargr (rap[largeap])
	    call pargr (cum)
	    call pargr (wcum)
end


define	NPERLINE	7

# PH_TWRITE -- Write the results to the output file.

procedure ph_twrite (fd, image, r0, xairmass, rbar, theo, obs, wobs, adopt,
	wado, rap, cum, tcum, wcum, naperts)

int	fd			# the file descriptor
char	image			# the iamge name
real	r0			# the seeing disk
real	xairmass		# the assumed airmass
real	rbar[ARB]		# the list of mean aperture radii
real	theo[ARB]		# the theoretical model differences
real	obs[ARB]		# the observed differences
real	wobs[ARB]		# the observed difference errors
real	adopt[ARB]		# the adopted differences
real	wado[ARB]		# the adopted difference errors
real	rap[ARB]		# the list of aperture radii
real	cum[ARB]		# the cumulative differences
real	tcum[ARB]		# the total cumulative differences
real	wcum[ARB]		# the errors in the cumulative differences
int	naperts			# the number of aperture

int	j
real	sqwcum

begin
	# Print the title.
	call fprintf (fd, "\nThe cog for image %s from radius %.2f to %.2f\n")
	    call pargstr (image)
	    call pargr (rbar[2])
	    call pargr (rbar[naperts])

	# Print the mean aperture radius.
	do j = 2, naperts {
	    if (j == 2) {
		call fprintf (fd, "  radius  %9.4f")
		    call pargr (rbar[j])
	    } else if (mod (j, NPERLINE) == 1) {
		call fprintf (fd, "%9.4f\n")
		    call pargr (rbar[j])
	    } else if (mod (j, NPERLINE) == 2) {
		call fprintf (fd, "          %9.4f")
		    call pargr (rbar[j])
	    } else {
		call fprintf (fd, "%9.4f")
		    call pargr (rbar[j])
	    }
	}
	if (mod (naperts, NPERLINE) != 1)
	    call fprintf (fd, "\n")

	# Print the theoretical model.
	do j = 2, naperts {
	    if (j == 2) {
		call fprintf (fd, "   model  %9.4f")
		    call pargr (theo[j])
	    } else if (mod (j, NPERLINE) == 1) {
		call fprintf (fd, "%9.4f\n")
		    call pargr (theo[j])
	    } else if (mod (j, NPERLINE) == 2) {
		call fprintf (fd, "          %9.4f")
		    call pargr (theo[j])
	    } else {
		call fprintf (fd, "%9.4f")
		    call pargr (theo[j])
	    }
	}
	if (mod (naperts, NPERLINE) != 1)
	    call fprintf (fd, "\n")

	# Print the observed cog.
	do j = 2, naperts {
	    if (j == 2) {
		call fprintf (fd, "observed  %9.4f")
		    call pargr (obs[j])
	    } else if (mod (j, NPERLINE) == 1) {
		call fprintf (fd, "%9.4f\n")
		    call pargr (obs[j])
	    } else if (mod (j, NPERLINE) == 2) {
		call fprintf (fd, "          %9.4f")
		    call pargr (obs[j])
	    } else {
		call fprintf (fd, "%9.4f")
		    call pargr (obs[j])
	    }
	}
	if (mod (naperts, NPERLINE) != 1)
	    call fprintf (fd, "\n")

	# Print the errors in the observed cog.
	do j = 2, naperts {
	    if (j == 2) {
		call fprintf (fd, "   sigma  %9.4f")
		    call pargr (wobs[j])
	    } else if (mod (j, NPERLINE) == 1) {
		call fprintf (fd, "%9.4f\n")
		    call pargr (wobs[j])
	    } else if (mod (j, NPERLINE) == 2) {
		call fprintf (fd, "          %9.4f")
		    call pargr (wobs[j])
	    } else {
		call fprintf (fd, "%9.4f")
		    call pargr (wobs[j])
	    }
	}
	if (mod (naperts, NPERLINE) != 1)
	    call fprintf (fd, "\n")

	# Print the adopted cog.
	do j = 2, naperts {
	    if (j == 2) {
		call fprintf (fd, " adopted  %9.4f")
		    call pargr (adopt[j])
	    } else if (mod (j, NPERLINE) == 1) {
		call fprintf (fd, "%9.4f\n")
		    call pargr (adopt[j])
	    } else if (mod (j, NPERLINE) == 2) {
		call fprintf (fd, "          %9.4f")
		    call pargr (adopt[j])
	    } else {
		call fprintf (fd, "%9.4f")
		    call pargr (adopt[j])
	    }
	}
	if (mod (naperts, NPERLINE) != 1)
	    call fprintf (fd, "\n")

	# Print the errors in the adopted cog.
	do j = 2, naperts {
	    if (j == 2) {
		call fprintf (fd, "   sigma  %9.4f")
		    call pargr (wado[j])
	    } else if (mod (j, NPERLINE) == 1) {
		call fprintf (fd, "%9.4f\n")
		    call pargr (wado[j])
	    } else if (mod (j, NPERLINE) == 2) {
		call fprintf (fd, "          %9.4f")
		    call pargr (wado[j])
	    } else {
		call fprintf (fd, "%9.4f")
		    call pargr (wado[j])
	    }
	}
	if (mod (naperts, NPERLINE) != 1)
	    call fprintf (fd, "\n")

	# Print the title.
	call fprintf (fd,
	    "\nThe aperture correction for image %s from radius %.2f to %.2f\n")
	    call pargstr (image)
	    call pargr (rap[1])
	    call pargr (rap[naperts])

	# Print the aperture radii.
	do j = 1, naperts {
	    if (j == 1) {
		call fprintf (fd, "  radius  %9.4f")
		    call pargr (rap[j])
	    } else if (mod (j, NPERLINE) == 0) {
		call fprintf (fd, "%9.4f\n")
		    call pargr (rap[j])
	    } else if (mod (j, NPERLINE) == 1) {
		call fprintf (fd, "          %9.4f")
		    call pargr (rap[j])
	    } else {
		call fprintf (fd, "%9.4f")
		    call pargr (rap[j])
	    }
	}
	if (mod (naperts, NPERLINE) != 0)
	    call fprintf (fd, "\n")

	# Print the aperture correction.
	do j = 2, naperts {
	    if (j == 2) {
		call fprintf (fd, " apercor  %9.4f")
		    call pargr (cum[j])
	    } else if (mod (j, NPERLINE) == 1) {
		call fprintf (fd, "%9.4f\n")
		    call pargr (cum[j])
	    } else if (mod (j, NPERLINE) == 2) {
		call fprintf (fd, "          %9.4f")
		    call pargr (cum[j])
	    } else {
		call fprintf (fd, "%9.4f")
		    call pargr (cum[j])
	    }
	}
	if (mod (naperts, NPERLINE) != 1)
	    call fprintf (fd, "\n")


	# Print the error in the aperture correction.
	do j = 2, naperts {
	    sqwcum = wcum[j]
	    if (j == 2) {
		call fprintf (fd, "   sigma  %9.4f")
		    call pargr (sqwcum)
	    } else if (mod (j, NPERLINE) == 1) {
		call fprintf (fd, "%9.4f\n")
		    call pargr (sqwcum)
	    } else if (mod (j, NPERLINE) == 2) {
		call fprintf (fd, "          %9.4f")
		    call pargr (sqwcum)
	    } else {
		call fprintf (fd, "%9.4f")
		    call pargr (sqwcum)
	    }
	}
	if (mod (naperts, NPERLINE) != 1)
	    call fprintf (fd, "\n")

	# Print the title.
	call fprintf (fd,
	    "\nThe aperture correction for image %s from radius %.2f to %.2f\n")
	    call pargstr (image)
	    call pargr (rap[1])
	    call pargr (2.0 * rap[naperts])

	# Print the total aperture correction.
	do j = 2, naperts + 1 {
	    if (j == 2) {
		call fprintf (fd, "tapercor  %9.4f")
		    call pargr (tcum[j])
	    } else if (mod (j, NPERLINE) == 1) {
		call fprintf (fd, "%9.4f\n")
		    call pargr (tcum[j])
	    } else if (mod (j, NPERLINE) == 2) {
		call fprintf (fd, "          %9.4f")
		    call pargr (tcum[j])
	    } else {
		call fprintf (fd, "%9.4f")
		    call pargr (tcum[j])
	    }
	}
	if (mod (naperts + 1, NPERLINE) != 1)
	    call fprintf (fd, "\n")

	call fprintf (fd, "\n")
end


# PH_TMAGS -- Compute the correction to the last computed magnitude for
# each star and the total magnitude as a function of aperture.

procedure ph_tmags (logfd, id, x, y, nap, rap, mag, merr, adopt, w, cum,
	tcum, wcum, tmpmags, obs, tobs, wobs, naperts, npts)

int	logfd			# the output file descriptor
int	id[ARB]			# stellar id numbers
real	x[ARB]			# stellar x coordinates
real	y[ARB]			# stellar y coordinates
int	nap[ARB]		# array of aperture numbers
real	rap[naperts,ARB]	# the list of aperture radii
real	mag[naperts,ARB]	# the input magnitude difference array
real	merr[naperts,ARB]	# the input magnitude error array
real	adopt[ARB]		# the adopted difference values
real	w[ARB]			# the working weight array
real	cum[ARB]		# the accumulated difference array
real	tcum[ARB]		# the total accumulated difference array
real	wcum[ARB]		# the errors in the accumulated diff array
real	tmpmags[ARB]		# temporary magnitude array
real	obs[ARB]		# the accumulated magnitude array
real	tobs[ARB]		# the total accumulated magnitude array
real	wobs[ARB]		# the observations array
int	naperts			# number of apertures
int	npts			# number of points

int	i, j
real	diff

begin
	# Print the logfile banner.
	if (logfd != NULL) {
	    call fprintf (logfd, "\nThe observed, and corrected to radii %.2f ")
		call pargr (rap[naperts,1])
	    call fprintf (logfd, "and %.2f, magnitudes\n")
		call pargr (2.0 * rap[naperts,1])
	}

	do i = 1, npts {

	    # Compute the observed, correctged and estimated total 
	    # magnitudes.
	    tmpmags[1] = mag[1,i]
	    do j = 1, nap[i] {
		if (j == 1)
		    w[j] = 1.0
		else {
		    diff = mag[j,i] - adopt[j]
		    tmpmags[j] = tmpmags[j-1] + mag[j,i]
		    w[j] = 1.0 / (1.0 + (diff / (2.0 * merr[j,i])) ** 2)
		    w[j] = min (w[j], w[j-1])
		}
		if (IS_INDEFR(cum[j+1])) {
		    obs[j]  = INDEFR
		    tobs[j]  = INDEFR
		    wobs[j] = INDEFR
		} else {
		    obs[j]  = tmpmags[j] + cum[j+1]
		    tobs[j]  = tmpmags[j] + tcum[j+1]
		    wobs[j] = sqrt (wcum[j+1] + merr[j,i] ** 2 / w[j])
		}
	    }
	    do j = nap[i] + 1, naperts {
		obs[j]  = INDEFR
		tobs[j]  = INDEFR
		wobs[j] = INDEFR
	    }

	    # Write out the results for the star to the log file.

	    # Print the banner of the star.
	    call fprintf (logfd, "Star: %d  x: %.3f y: %.3f\n")
	        call pargi (id[i])
	        call pargr (x[i])
	        call pargr (y[i])

	    # Print the aperture radii.
	    do j = 1, naperts {
	        if (j == 1) {
		    call fprintf (logfd, "  radius  %9.4f")
		        call pargr (rap[j,i])
	        } else if (mod (j, NPERLINE) == 0) {
		    call fprintf (logfd, "%9.4f\n")
		        call pargr (rap[j,i])
	        } else if (mod (j, NPERLINE) == 1) {
		    call fprintf (logfd, "          %9.4f")
		        call pargr (rap[j,i])
	        } else {
		    call fprintf (logfd, "%9.4f")
		        call pargr (rap[j,i])
	        }
	    }
	    if (mod (naperts, NPERLINE) != 0)
	        call fprintf (logfd, "\n")

	    # Print the observed magnitudes.
	    do j = 1, naperts {
	        if (j == 1) {
		    call fprintf (logfd, "    mags  %9.4f")
	                call pargr (tmpmags[j])
	        } else if (mod (j, NPERLINE) == 0) {
		    call fprintf (logfd, "%9.4f\n")
		        call pargr (tmpmags[j])
	        } else if (mod (j, NPERLINE) == 1) {
		    call fprintf (logfd, "          %9.4f")
		        call pargr (tmpmags[j])
	        } else {
		    call fprintf (logfd, "%9.4f")
		        call pargr (tmpmags[j])
	        }
	    }
	    if (mod (naperts, NPERLINE) != 0)
	        call fprintf (logfd, "\n")

	    # Print the corrected magnitudes.
	    do j = 1, naperts {
	        if (j == 1) {
		    call fprintf (logfd, "   cmags  %9.4f")
		        call pargr (obs[j])
	        } else if (mod (j, NPERLINE) == 0) {
		    call fprintf (logfd, "%9.4f\n")
		        call pargr (obs[j])
	        } else if (mod (j, NPERLINE) == 1) {
		    call fprintf (logfd, "          %9.4f")
		        call pargr (obs[j])
	        } else {
		    call fprintf (logfd, "%9.4f")
		        call pargr (obs[j])
	        }
	    }
	    if (mod (naperts, NPERLINE) != 0)
	        call fprintf (logfd, "\n")

	    # Print the estimated total corrected magnitudes.
	    do j = 1, naperts {
	        if (j == 1) {
		    call fprintf (logfd, "  tcmags  %9.4f")
		        call pargr (tobs[j])
	        } else if (mod (j, NPERLINE) == 0) {
		    call fprintf (logfd, "%9.4f\n")
		        call pargr (tobs[j])
	        } else if (mod (j, NPERLINE) == 1) {
		    call fprintf (logfd, "          %9.4f")
		        call pargr (tobs[j])
	        } else {
		    call fprintf (logfd, "%9.4f")
		        call pargr (tobs[j])
	        }
	    }
	    if (mod (naperts, NPERLINE) != 0)
	        call fprintf (logfd, "\n")

	    # Print the errors in the total magnitudes
	    do j = 1, naperts {
	        if (j == 1) {
		    call fprintf (logfd, "   sigma  %9.4f")
		        call pargr (wobs[j])
	        } else if (mod (j, NPERLINE) == 0) {
		    call fprintf (logfd, "%9.4f\n")
		        call pargr (wobs[j])
	        } else if (mod (j, NPERLINE) == 1) {
		    call fprintf (logfd, "          %9.4f")
		        call pargr (wobs[j])
	        } else {
		    call fprintf (logfd, "%9.4f")
		        call pargr (wobs[j])
	        }
	    }
	    if (mod (naperts, NPERLINE) != 0)
	        call fprintf (logfd, "\n")
	}

	call fprintf (logfd, "\n")
end


# PH_WMAGS -- Compute the correction to the last computed magnitude for
# each star and the total magnitude as a function of aperture.

procedure ph_wmags (magfd, imsymbol, x, y, nap, rap, mag, merr, adopt, wado,
    w, cum, wcum, tmpmags, obs, wobs, naperts, npts, largeap)

int	magfd			# the best magnitudes file descriptor
pointer	imsymbol		# the image symbol
real	x[ARB]			# stellar x coordinates
real	y[ARB]			# stellar y coordinates
int	nap[ARB]		# array of aperture numbers
real	rap[naperts,ARB]	# the input aperture radii
real	mag[naperts,ARB]	# the input magnitude difference array
real	merr[naperts,ARB]	# the input magnitude error array
real	adopt[ARB]		# the adopted difference values
real	wado[ARB]		# the adopted difference errors
real	w[ARB]			# the working weight array
real	cum[ARB]		# the accumulated difference array
real	wcum[ARB]		# the errors in the accumulated diff array
real	tmpmags[ARB]		# temporary magnitude array
real	obs[ARB]		# the accumulated magnitude array
real	wobs[ARB]		# the observations array
int	naperts			# number of apertures
int	npts			# number of points
int	largeap			# the largest aperture

int	i, j, jfinal
real	diff, sigmin, sigcor
real	assqr()

begin
	do i = 1, npts {

	    # Compute the observed, correctged and estimated total magnitudes.
	    tmpmags[1] = mag[1,i]
	    sigmin = MAX_REAL
	    #jfinal = min (nap[i], largeap)
	    jfinal = largeap
	    if (largeap < nap[i])
		sigcor = assqr (wado[largeap+1], nap[i] - largeap)
	    else
		sigcor = 0.0
	    do j = 1, min (nap[i], largeap) {
		if (j == 1)
		    w[j] = 1.0
		else {
		    diff = mag[j,i] - adopt[j]
		    tmpmags[j] = tmpmags[j-1] + mag[j,i]
		    w[j] = 1.0 / (1.0 + (diff / (2.0 * merr[j,i])) ** 2)
		    w[j] = min (w[j], w[j-1])
		}
		if (IS_INDEFR(cum[j+1])) {
		    obs[j] = INDEFR
		    wobs[j] = INDEFR
		} else {
		    obs[j]  = tmpmags[j] + cum[j+1] - cum[largeap+1]
		    wobs[j] = sqrt (wcum[j+1] - sigcor + merr[j,i] ** 2 / w[j])
		    if (wobs[j] < sigmin) {
		        jfinal = j
		        sigmin = wobs[j]
		    }
		}
	    }

	    # Write out the best magnitude.
	    if (magfd != NULL) {
		call fprintf (magfd,
"%23.23s  %10.10s  %8.2f  %6.3f  %11.1h  %8.2f  %8.2f  %7.3f  %7.3f  %6.3f\n")
		    call pargstr (IMT_IMNAME(imsymbol))
		    call pargstr (IMT_IFILTER(imsymbol))
		    call pargr (IMT_ITIME(imsymbol))
		    call pargr (IMT_XAIRMASS(imsymbol))
		    call pargr (IMT_OTIME(imsymbol))
		    call pargr (x[i])
		    call pargr (y[i])
		    call pargr (obs[jfinal])
		    call pargr (wobs[jfinal])
		    call pargr (rap[jfinal,i])
	    }
	}
end


# PH_ACHI -- Compute the chi statistic.

real procedure ph_achi (wr, resid, ressq, naperts)

real	wr[ARB]			# the weights
real	resid[ARB]		# the residuals
real	ressq[ARB]		# the residuals
int	naperts			# the number of apertures

double	sumwr, sumres, sumressq
real	chi
real	asumr()

begin
	sumwr = asumr (wr, naperts)
	sumres = asumr (resid, naperts)
	sumressq = asumr (ressq, naperts)
	if (sumwr <= 0.0d0)
	    chi = 0.0
	else
	    chi = sumressq / sumwr - (sumres / sumwr) ** 2
	if (chi <= 0.0 || chi > MAX_REAL)
	    return (INDEFR)
	else
	    return (chi)
end


# PH_RWRITE -- Write out the fit statistics for each aperture.

procedure ph_rwrite (fd, ave, wr, resid, ressq, naperts)

int	fd			# the output file descriptor
real	ave[ARB]		# the average values
real	wr[ARB]			# the weights
real	resid[ARB]		# the residuals
real	ressq[ARB]		# the residuals
int	naperts			# the number of apertures

int	j
real	rtmp

begin
	call fprintf (fd, "\nAverage model cog, residual, and rms residual ")
	call fprintf (fd, "for each aperture all images\n")
	do j = 1, naperts {
	    if (wr[j] <= 0.0) {
		ave[j] = INDEFR
		resid[j] = INDEFR
		ressq[j] = INDEFR
	    } else {
	        ave[j] = ave[j] / wr[j]
	        resid[j] = resid[j] / wr[j]
	        rtmp = ressq[j] / wr[j] - resid[j] ** 2
		if (rtmp <= 0.0)
		    ressq[j] = 0.0
		else
	            ressq[j] = sqrt (rtmp)
	    }
	    call fprintf (fd, "\t%3d  %9.5f  %9.5f  %9.5f\n")
		call pargi (j)
		call pargr (ave[j])
		call pargr (resid[j])
		call pargr (ressq[j])
	}
	call fprintf (fd, "\n")
end


# PH_DMAG -- Compute the integral of the magnitude between two radii
# assuming that the stellar profile can be approximated by a circular
# Moffat function.

double procedure ph_dmag (r1, r2, x, r0, params)

real	r1			# beginning radius for the integration
real	r2			# ending radius for the integration
real	x			# the airmass value
real	r0			# the hwhm of the psf
double	params[ARB]		# the model parameter array

double	bpex, pm1, x1, x2, x1sq, x2sq, d1, d2, i1, i2, dmag 

begin
	bpex = params[2] + params[5] * x
	pm1 = params[1] - 1.0d0
	x1 = (r1 / r0)
	x2 = (r2 / r0)
	x1sq = x1 ** 2
	x2sq = x2 ** 2
	x1 = x1 / params[4]
	x2 = x2 / params[4]
	d1 = 1.0d0 + r1 ** 2
	d2 = 1.0d0 + r2 ** 2
	i1 = bpex * (1.0d0 - 1.0d0 / d1 ** pm1) + (1.0d0 - bpex) *
	    (params[3] * (1.0d0 - exp (-0.5d0 * x1sq)) + (1.0d0 - params[3]) *
	    (1.0d0 - (1.0d0 + x1) * exp (-x1)))
	i2 = bpex * (1.0d0 - 1.0d0 / d2 ** pm1) + (1.0d0 - bpex) *
	    (params[3] * (1.0d0 - exp (-0.5d0 * x2sq)) + (1.0d0 - params[3]) *
	    (1.0d0 - (1.0d0 + x2) * exp (-x2)))
	dmag = -2.5d0 * log10 (i2 / i1)

	return (dmag)
end


# DMVMUL -- Multply a matrix (left-hand side) by a one dimensional vector
# (right-hand side) and return the resultant vector.

procedure dmvmul (matrix, maxdim, dim, vector, result)

double	matrix [maxdim, maxdim]	# input matrix
int	maxdim			# maximum size of input matrix
int	dim			# dimension of matrix and vectors
double	vector[maxdim]		# input vector
double	result[maxdim]		# iutput vector

double	sum
int	i, j

begin
	do i = 1, dim {
	    sum = 0.0d0
	    do j = 1, dim
		sum = sum + (matrix[j,i] * vector[j])
	    result[i] = sum
	}
end