This repository was archived by the owner on Jun 4, 2018. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathskycalc.c
More file actions
8490 lines (7383 loc) · 272 KB
/
Copy pathskycalc.c
File metadata and controls
8490 lines (7383 loc) · 272 KB
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
/* SKY CALCULATOR PROGRAM
John Thorstensen, Dartmouth College.
This program computes many quantities frequently needed by the
observational astronomer. It is written as a completely
self-contained program in standard c, so it should be
very transportable; the only issue I know of that really affects
portability is the adequacy of the double-precision floating
point accuracy on the machine. Experience shows that c compilers
on various systems have idiosyncracies, though, so be sure
to check carefully.
This is intended as an observatory utility program; I assume the
user is familiar with astronomical coordinates and nomenclature.
While the code should be very transportable, I also
assume it will be installed by a conscientious person who
will run critical tests before it is released at a new site.
Experience shows that some c compilers generate unforseen errors
when the code is ported, so the output should be checked meticulously
against data from other sites.
After prompting the user for site information, the program enters
its main command loop,
- enter RA, dec, proper motion, epoch, date, time,
new site parameters, etc. ... (when the code starts,
it initializes these things to the current date and time
and the celestial coordinates of the zenith at the
specified site).
- print an almanac of rise/set and twilight for the sun and
moon for the specified night
- compute and display circumstances of observation for the
current parameters, including precessed coordinates,
airmass, interference from moon or twilight, parallactic
angle, etc; the program also gives calendar date in
both UT and local, Julian date, and barycentric corrections.
- compute and display a table of airmasses (etc) at
hourly intervals through the night. This is very useful
at the telescope. Also, if one has a modest number of
objects, it may be convenient (using system utilities)
to redirect the output and print a hard copy of these
tables for ready reference.
- compute and display galactic and ecliptic coordinates.
- compute and display rough (of order 0.1 degree, but often
much better) positions of the major planets.
The program is self-contained. It has been developed primarily on
UNIX and Linux machines, and should adapt easily to any system with
a c compiler.
** BUT CAUTION ... **
Because many of the routines take a double-precision floating point
Julian Date as their time argument, one must be sure that the machine
and compiler carry sufficient mantissa to reach the desired accuracy.
On most architectures the double-precision floating point julian date
has an accuracy of order 0.01 seconds of time, which is just adequate.
LEGALITIES:
I make no guarantee as to the accuracy, reliability, or
appropriateness of this program, though I have found it to be
reasonably accurate and quite useful to the working astronomer.
The program is COPYRIGHT 2000 BY JOHN THORSTENSEN.
Permission is hereby granted for non-profit scientific or educational use.
For-profit use (e. g., by astrologers!) must be through negotiated
license. The author requests that observatories and astronomy
departments which install this as a utility notify the author
by paper mail, just so I know how widely it is used.
Credits:
* The julian date and sidereal time routines were
originally coded in PL/I by Steve Maker of Dartmouth College.
They were based on routines in the old American Ephemeris.
Many of the routines were coded from Jean Meeus' "Astronomical
Formulae for Calculators", published by Willman-Bell. This is
an extraordinarily helpful little book!
BUGS:
The program can enter an infinite loop of prompting in response
to incorrect input. This is fairly rare in practice, but
may be bothersome on multi-user systems. If anyone can document
this properly, I may be able to fix it. In the meantime you
may want to run this only on systems on which you can easily
stop runaway processes (e.g., by CRTL-C on Linux or UNIX machines.)
APOLOGIES/DISCLAIMER:
I am aware that the code here does not always conform to
the best programming practices. Not every possible error condition
is anticipated, and no guarantee is given that this is bug-free.
Nonetheless, most of this code has been shaken down at several
hundred sites for several years, and I have never received any
actual bug reports. Many users have found this program
to be useful.
CHANGES SINCE THE ORIGINAL DISTRIBUTION ....
The program as listed here is for the most part similar to that
posted on the IRAF bulletin board in 1990. Some changes
include:
01 In the original code, many functions returned structures, which
some c implementations do not like. These have been eliminated.
02 The original main() was extremely cumbersome; much of it has
been broken into smaller (but still large) functions.
03 The hourly airmass includes a column for the altitude of the
sun, which is printed if it is greater than -18 degrees.
04 The planets are included (see above). As part of this, the
circumstances calculator issues a warning when one is within
three degrees of a major planet. This warning is now also
included in the hourly-airmass table.
05 The changeover from standard to daylight time has been rationalized.
Input times between 2 and 3 AM on the night when DST starts (which
are skipped over and hence don't exist) are now disallowed; input
times between 1 and 2 AM on the night when DST ends (which are
ambiguous) are interpreted as standard times. Warnings are printed
in both the almanac and calculator mode when one is near to the
changeover.
06 a much more accurate moon calculation has been added; it's used
when the moon's coordinates are given explicitly, but not for
the rise/set times, which iterate and for which a lower precision
is adequate.
07 It's possible now to set the observatory elevation; in a second
revision there are now two separate elevation parameters specified.
The elevation above the horizon used only in rise/set calculations
and adjusts rise/set times assuming the parameter is the elevation
above flat surroundings (e. g., an ocean). The true elevation above
sea level is used (together with an ellipsoidal earth figure) in
determining the observatory's geocentric coordinates for use in
the topocentric correction of the moon's position and in the
calculation of the diurnal rotation part of the barycentric velocity
correction. These refinements are quite small.
08 The moon's altitude above the horizon is now printed in the
hourly airmass calculation; in the header line, its illuminated
fraction and angular separation from the object are included,
as computed for local midnight.
09 The helio/barycentric corrections have been revised and improved.
The same routines used for planetary positions are used to
compute the offset from heliocentric to solar-system
barycentric positions and velocities. The earth's position
(and the sun's position as well) have also been improved somewhat.
10 The printed day and date are always based on the same truncation
of the julian date argument, so they should now always agree
arbitrarily close to midnight.
11 A new convention has been adopted by which the default is that the
date specified is the evening date for the whole night. This way,
calculating an almanac for the night of July 3/4 and then specifying
a time after midnight gives the circumstances for the *morning of
July 4*. Typing 'n' toggles between this interpretation and a
literal interpretation of the date.
12 The planetary proximity warning is now included in the hourly airmass
table.
13 A routine has been added which calculates how far the moon is from
the nearest cardinal phase (to coin a phrase) and prints a
description. This information is now included in both the almanac
and the calculator mode.
14 The output formats have been changed slightly; it's hoped this
will enhance comprehensibility.
15 A substantial revision affecting the user interface took place
in September of 1993. A command 'a' has been added to the
'calculator' menu, which simply prints the almanac (rise, set,
and so on) for the current night. I'd always found that it was
easy to get disoriented using the '=' command -- too much
information about the moment, not enough about the time
context. Making the almanac info *conveniently* available
in the calculator mode helps your get oriented.
When the 'a' almanac is printed, space is saved over the
almanac printed on entry, because there does not need
to be a banner introducing the calculator mode. Therefore some
extra information is included with the 'a' almanac; this includes
the length of the night from sunset to sunrise, the number of
hours the sun is below -18 degrees altitude, and the number of hours
moon is down after twilight. In addition, moonrise and moonset
are printed in the order in which they occur, and the occasional
non-convergence of the rise/set algorithms at high latitude are
signalled more forcefully to the user.
16 I found this 'a' command to be convenient in practice, and never
liked the previous structure of having to 'quit' the calculator
mode to see almanac information for a different night. D'Anne
Thompson of NOAO also pointed out how hokey this was, especially the
use of a negative date to exit. So, I simply removed the outer
'almanac' loop and added a 'Q' to the main menu for 'quit'. The
use of upper case -- for this one command only -- should guard
against accidental exit.
17 The menu has been revised to be a little more readable.
18 More error checking was added in Nov. 1993, especially for numbers.
If the user gives an illegal entry (such as a number which isn't
legal), the rest of the command line is thrown away (to avoid
having scanf simply chomp through it) and the user is prompted
as to what to do next. This seems to have stopped all situations
in which execution could run away. Also, typing repeated carriage
returns with nothing on the line -- which a frustrated novice
user may do because of the lack of any prompts -- causes a
little notice to be printed to draw attention to the help and menu
texts.
19 I found in practice that, although the input parameters and
conditions are deducible *in principle* from such things as the
'a' and '=' output, it takes too much digging to find them. So
I instituted an 'l' command to 'look' at the current parameter
values. To make room for this I put the 'Cautions and legalities'
into the 'w' (inner workings) help text. This looks as though
it will be be very helpful to the user.
20 The more accurate moon calculation is used for moonrise and
moonset; the execution time penalty appears to be trivial.
Low precision moon is still used for the summary moon information
printed along with the hourly airmass table.
21 A calculation of the expected portion of the night-sky
brightness due to moonlight has been added. This is based on
Krisciunas and Schaefer's analytic fits (PASP, 1991). Obviously,
it's only an estimate which will vary considerably depending on
atmospheric conditions.
22 A very crude estimator of the zenith sky brightness in twilight
has been added.
23 A topocentric correction has been added for the sun, in anticipation
of adding eclipse prediction.
24 The code now checks for eclipses of the sun and moon, by making
very direct use of the predicted positions. If an eclipse is
predicted, a notice is printed in print_circumstances; also, a
disclaimer is printed for the lunar sky brightness if a lunar
eclipse is predicted to be under way.
25 In the driver of the main calculator loop, a provision has been
added for getting characters out of a buffer rather than reading
them directly off the command line. This allows one to type any
valid command character (except Q for quit) directly after a number
in an argument without generating a complaint from the program
(see note 18). This had been an annoying flaw.
26 In 1993 December/1994 January, the code was transplanted
to a PC and compiled under Borland Turbo C++, with strict
ANSI rules. The code was cut into 9 parts -- 8 subroutine
files, the main program, and an incude file containing
global variables and function prototypes.
27 An "extra goodies" feature has been added -- at present it
computes geocentric times of a repeating phenomenon as
viewed from a site. This can be used for relatively little-used
commands to save space on the main menu.
28 The sun and moon are now included in the "major planets"
printout. This allows one to find their celestial positions
even when they are not visible from the selected site.
29 A MAJOR new feature was added in February 1994, which computes
the observability of an object at new and full moon over a
range of dates. The galactic/ecliptic coordinate converter
was moved to the extra goodies menu to make room for this.
30 Inclusion of a season-long timescale means that it's not
always necessary to specify a date on entry to the program.
Accordingly, the program immediately starts up in what used
to be called "calculator" mode -- only the site is prompted
for. It is thought that the site will be relevant to nearly
all users.
31 Because the user is not led by the hand as much as before, the
startup messages were completely revised to direct new users
toward a short `guided tour' designed to show the program's
command structure and capabilities very quickly. Tests on
volunteers showed that users instinctively go for anything
called the `menu', despite the fact that that's a slow way to
learn, so all mention of the menu option is removed from the
startup sequence; they'll catch on soon enough.
32 Code has been added to automatically set the time and
date to the present on startup. A menu option 'T' has been
added to set the time and date to the present plus a settable
offset. This should be very useful while observing.
33 Because Sun machines apparently do not understand ANSI-standard
function declarations, the code has been revised back to K&R
style. It's also been put back in a monolithic block for
simplicity in distribution.
34 The startup has been simplified still further, in that the
coordinates are set automatically to the zenith on startup.
An 'xZ' menu item sets to the zenith for the currently specified
time and date (not necessarily the real time and date.)
35 Another MAJOR new capability was added in early 1994 --
the ability to read in a list of objects and set the current
coordinates to an object on the list. The list can be sorted
in a number of ways using information about the site, date
and time.
35 Calculator-like commands were added to the extra goodies menu
to do precessions and to convert Julian dates to calendar
dates. An option to set the date and time to correspond to
a given julian date was also added.
36 Another substantial new capability was added Aug 94 -- one can
toggle open a log file (always named "skyclg") and keep
a record of the output. This is done simply by replacing
most occurrences of "printf" with "oprintf", which mimics
printf but writes to a log file as well if it is open.
This appears to slow down execution somewhat.
37 12-degree twilight has been added to the almanac. While the
awkward "goto" statements have been retained, the statement
labels have been revised to make them a little clearer.
38 The precession routine was generalized to include nutation and
aberration, and routines to calculate these effects are now
included. Nearly all calls to the new routine leave the
aberration and nutation out, but 'xa' extra goodies gives
apparent place up to aberration and nutation. Tests against the
FK5 and "Apparent Places of Fundamental Stars" shows the
agreement to 0.1 arcsec or smaller.
39 Atmospheric refraction is computed and reported in the "xa"
apparent place calculation. Barometric pressure is guesstimated
from the observatory elevation above sea level.
40 An airmass based on a series expansion is printed in the "="
command, in place of the secant of the zenith distance, provided
sec z is < 12. The approximation breaks down larger than this.
41 The parallactic angle calculation has been simplified and folded
inside the routine which calculates altitude and azimuth.
42 A few utility routines (atan_circ, xyz_cel) were cleaned up.
43 I added a new option for reading the system clock every time
'timely' output is asked for, and computing for the updated
time & date. This is toggled on and off with 'xU', for
updating. The date and time can optionally be offset from that
read from the system clock, as in the 'T' option.
44 The sexigesimal coordinate-output routine "put_coords" was
revised to be more general and a little less ugly. It's not
necessarily shorter! This required gussying up the outputs
because the new routine doesn't space just the same.
It's now possible to include a "+" sign explicitly in the
output when desired.
45 The calendrical conversion routines have been replaced with
routines coded from Meeus' "Astronomical Formulae for
Calculators", to avoid the use of proprietary Numerical
Recipes code.
46 The routine used to sort objects by airmass, etc. has been
replaced with an original coding of the heapsort algorithm
to avoid the use of proprietary "Numerical Recipes" code.
All the code *should* now be freely distributable.
47 The routine which reads strings from input has been rewritten
so that it can take delimited strings like 18:02:12.33 ...
delimiter can be any character which is not a numeral,
a + or - sign, or a decimal point (i.e., anything which can't
be part of a number.)
48 Another 'xtra goodies' option has been added to print out the
parallax factors (i.e., parallax displacement in ra and dec
a star would have at exactly 1 pc distance at the nominal
time and date). Also prints XYZ for earth and annual aberration
(displacement of star due to finite speed of light and earth's
motion about the sun.)
49 In 2000 October I fixed some infelicities with the
xv and xf commands, and updated the xd (TDT - UT) command.
The TeX documentation and the on-line documentation were
updated. In 2002 Jan. finally fixed a bug which displayed the
wrong ephemeris in the header in the xv command
(computations were OK).
50 Added the capability to read and write site-parameter files.
51 replaced "round" with "roundx" to avoid name conflict arising
with a math library function.
52 2003 -- updated the etcorr routine again to reflect Delta T
values in 2003 almanac and adjust forward extrapolation to
match last tabulated value.
53 Added code adapted from F. Ochsenbein (CDS Strasbourg) to give the
constellation location of the point in question, and report the
location in the "=" and "xc" commands.
54 Added a "parallactic penalty" factor, i.e. the magnitude of
tan z times the magnitude of the sine of the parallactic angle.
This severity of the parallactic differential refraction effect
will be proportional to this, for a slit which defaults to
north-south.
*/
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <stdarg.h>
#include <string.h>
/* a couple of the system-dependent magic numbers are defined here */
#define SYS_CLOCK_OK 1 /* 1 means ANSI-standard time libraries do work,
2 means they don't. This is used by compiler switches in file 5 and
the main program. */
#define LOG_FILES_OK 1 /* 1 means that log files are enabled.
Any other value means they're not. */
#define MAX_OBJECTS 2000
#define MINSHORT -32767 /* min, max short integers and double precision */
#define MAXSHORT 32767
#define MAXDOUBLE 1.0e38
#define MINDOUBLE -1.0e38
#define BUFSIZE 150
#define XFORM_FROMSTD 1 /* defined quantities for apparent place transforms .. */
#define XFORM_TOSTDEP -1
#define XFORM_JUSTPRE 1
#define XFORM_DOAPPAR 0
/* some (not all) physical, mathematical, and astronomical constants
used are defined here. */
#define PI 3.14159265358979
#define TWOPI 6.28318530717959
#define PI_OVER_2 1.57079632679490 /* From Abramowitz & Stegun */
#define ARCSEC_IN_RADIAN 206264.8062471
#define DEG_IN_RADIAN 57.2957795130823
#define HRS_IN_RADIAN 3.819718634205
#define KMS_AUDAY 1731.45683633 /* km per sec in 1 AU/day */
#define SPEED_OF_LIGHT 299792.458 /* in km per sec ... exact. */
#define SS_MASS 1.00134198 /* solar system mass in solar units */
#define J2000 2451545. /* Julian date at standard epoch */
#define SEC_IN_DAY 86400.
#define FLATTEN 0.003352813 /* flattening of earth, 1/298.257 */
#define EQUAT_RAD 6378137. /* equatorial radius of earth, meters */
#define ASTRO_UNIT 1.4959787066e11 /* 1 AU in meters */
#define RSUN 6.96000e8 /* IAU 1976 recom. solar radius, meters */
#define RMOON 1.738e6 /* IAU 1976 recom. lunar radius, meters */
#define PLANET_TOL 3. /* flag if nearer than 3 degrees
to a major planet ... */
#define KZEN 0.172 /* zenith extinction, mag, for use
in lunar sky brightness calculations. */
#define FIRSTJD 2415387. /* 1901 Jan 1 -- calendrical limit */
#define LASTJD 2488070. /* 2099 Dec 31 */
/* MAGIC NUMBERS which might depend on how accurately double-
precision floating point is handled on your machine ... */
#define JDRESOLUTION 3.5e-8 /* 3 milliseconds */
#define EARTH_DIFF 0.05 /* used in numerical
differentiation to find earth velocity -- this value gives
about 8 digits of numerical accuracy on the VAX, but is
about 3 orders of magnitude larger than the value where roundoff
errors become apparent. */
#define MIDN_TOL 0.00001 /* this is no longer
used -- it was formerly
how close (in days) a julian date has to be to midnight
before a warning flag is printed for the reader. VAX
double precision renders a Julian date considerably
more accurately than this. The day and date are now based
on the same rounding of the julian date, so they should
always agree. */
/* FUNCTION PROTOTYPES and type definitions ....
These are used in breaking the code into function libraries.
They work properly on a strictly ANSI compiler, so they
apparently comply with the ANSI standard format. */
/* these global variables determine whether the program updates the
time and date whenever asked for output. */
#if SYS_CLOCK_OK == 1
int update_on = 0;
double update_delta = 0.;
#endif
struct coord
{
short sign; /* carry sign explicitly since -0 not neg. */
double hh;
double mm;
double ss;
};
struct date_time
{
short y;
short mo;
short d;
short h;
short mn;
float s;
};
FILE *sclogfl = NULL;
double star_tzero, star_terr,
star_period, star_perr; /* for ephemeris calculations ... global */
void oprntf(char *fmt, ...)
/* This routine should look almost exactly like printf in terms of its
arguments (format list, then a variable number of arguments
to be formatted and printed). It is designed to behave just
like printf (though perhaps not all format types are supported yet)
EXCEPT that IF the globally-defined file pointer "sclogfl" is
defined, IT ALSO WRITES TO THAT FILE using fprintf. The skeleton
for this came from Kernighan and Ritchie, 2nd edition, page 156 --
their "minprintf" example. I modified it to include the
entire format string (e.g., %8.2f, %7d) and to write to the
file as well as standard output. */
{
va_list ap; /* see K&R for explanation of these macros */
char *p, *sval;
char outform[10]; /* an item's output format, e.g. %8.2f */
char strout[150];
int ival, i;
short shval;
char cval;
double dval;
va_start(ap,fmt);
for (p = fmt; *p; p++) {
if (*p != '%') {
putchar(*p);
/* overkill to put in these preprocessor flags, perhaps. */
#if LOG_FILES_OK == 1
if(sclogfl != NULL) fputc(*p,sclogfl);
#endif
continue;
}
i = 0;
outform[i] = '%';
p++;
while(*p != 'd' && *p != 'f' && *p != 's' && *p != 'c'
&& *p != 'h') {
outform[++i] = *p++;
}
switch (*p) {
case 'd':
ival = va_arg(ap, int);
outform[++i] = *p;
outform[++i] = '\0';
printf(outform, ival);
#if LOG_FILES_OK == 1
if(sclogfl != NULL)
fprintf(sclogfl,outform,ival);
#endif
break;
case 'h': /* signals short argument ... */
shval = va_arg(ap, int);
outform[++i] = 'd';
outform[++i] = '\0';
++p; /* skip the 'd' in '%hd' */
printf(outform, shval);
#if LOG_FILES_OK == 1
if(sclogfl != NULL)
fprintf(sclogfl,outform,shval);
#endif
break;
case 'c':
/* cval = va_arg(ap, char);
... compiler problem on Sun machines */
cval = va_arg(ap, int);
outform[++i] = *p;
outform[++i] = '\0';
printf(outform, cval);
#if LOG_FILES_OK == 1
if(sclogfl != NULL)
fprintf(sclogfl,outform,cval);
#endif
break;
case 'f':
dval = va_arg(ap, double);
outform[++i] = *p;
outform[++i] = '\0';
printf(outform, dval);
#if LOG_FILES_OK == 1
if(sclogfl != NULL)
fprintf(sclogfl,outform,dval);
#endif
break;
case 's':
outform[++i] = *p;
outform[++i] = '\0';
i = 0;
for (sval = va_arg(ap, char *); *sval; sval++) {
strout[i++] = *sval;
}
strout[i] = '\0';
printf(outform,strout);
#if LOG_FILES_OK == 1
if(sclogfl != NULL) fprintf(sclogfl,outform,strout);
#endif
break;
default:
;
}
}
va_end(ap);
}
/* elements of K&R hp calculator, basis of commands */
char buf[BUFSIZE];
int bufp=0;
char getch() /* get a (possibly pushed back) character */
{
return((bufp > 0) ? buf[--bufp] : getchar());
}
void ungetch(c) /* push character back on input */
int c;
{
if(bufp > BUFSIZE)
printf("Ungetch -- too many characters.\n");
else
buf[bufp++] = c;
}
/* some functions for getting well-tested input. */
int legal_num_part(c)
char c;
{
if((c != '.') && (c != '-') && (c != '+') && (c < '0' || c > '9'))
return(-1); /* not a legal number part */
else return(0);
}
int legal_int_part(c)
char c;
{
if((c != '-') && (c < '0' || c > '9'))
return(-1); /* not a legal number part */
else return(0);
}
int legal_command_char(c)
char c;
{
/* Allows more sophisticated argument checking by seeing if
a character appended to an argument is actually a
legal commmand. */
switch(c) {
case '?': return(1);
break;
case 'i': return(1);
break;
case 'f': return(1);
break;
case 'w': return(1);
break;
case 'r': return(1);
break;
case 'd': return(1);
break;
case 'C': return(1);
break;
case 'y': return(1);
break;
case 't': return(1);
break;
case 'T': return(1);
break;
case 'n': return(1);
break;
case 'g': return(1);
break;
case 'e': return(1);
break;
case 'p': return(1);
break;
case 's': return(1);
break;
case 'l': return(1);
break;
case '=': return(1);
break;
case 'a': return(1);
break;
case 'h': return(1);
break;
case 'o': return(1);
break;
case 'm': return(1);
break;
case 'c': return(1);
break;
case 'x': return(1);
break;
/* let's not allow 'Q' here! */
default: return(0);
}
}
int parsedouble(s,d)
char *s;
double *d;
/* return values 0 = ok, with number, 1 = found a valid command,
but no number, and -1 = an error of some sort (unexpected char)*/
{
short i=0, legal = 0;
while((*(s+i) != '\0') && (legal == 0)) {
if(legal_num_part(*(s+i)) == 0) i++;
else if(legal_command_char(*(s+i)) == 1) {
/* to allow command to follow argument without blanks */
ungetch(s[i]);
*(s+i) = '\0'; /* will terminate on next pass. */
}
else legal = -1;
}
if(legal == 0) {
if(i > 0) {
sscanf(s,"%lf",d);
return(0);
}
else if (i == 0) { /* ran into a command character -- no input */
*d = 0.;
return(1); /* ok, actually */
}
}
else {
printf("%s is not a legal number!! Try again!\n",s);
return(-1);
}
}
int getdouble(d,least,most,errprompt)
double *d,least,most;
char *errprompt;
{
char s[30], buf[200], c;
short success = -1, ndiscard = 0;
scanf("%s",s);
while(success < 0) {
success = parsedouble(s,d);
if((success == 0) && ((*d < least) || (*d > most))) {
printf("%g is out of range; allowed %g to %g -- \n",
*d,least,most);
success = -1;
}
if(success < 0) {
/* if there's error on input, clean out the rest of the line */
ndiscard = 0;
while((c = getchar()) != '\n') {
buf[ndiscard] = c;
ndiscard++;
}
if(ndiscard > 0) {
buf[ndiscard] = '\0'; /* terminate the string */
printf("Rest of input (%s) has been discarded.\n",buf);
}
printf("%s",errprompt);
printf("\nTry again:");
scanf("%s",s);
}
}
return((int) success);
}
int parseshort(s,d)
char *s;
short *d;
{
short i=0, legal = 0;
while((*(s+i) != '\0') && (legal == 0)) {
if(legal_int_part(*(s+i)) == 0) i++;
else if(legal_command_char(*(s+i)) == 1) {
/* to allow command to follow argument without blanks */
ungetch(s[i]);
*(s+i) = '\0'; /* will terminate on next pass. */
}
else legal = -1;
}
if(legal == 0) {
if(i > 0) {
sscanf(s,"%hd",d);
return(0);
}
else if (i == 0) { /* ran into a command character -- no input */
*d = 0.;
return(1); /* didn't get a number, but something else legal */
}
}
else {
printf("%s is not a legal integer number!! Try again!\n",s);
return(-1);
}
}
int getshort(d,least,most,errprompt)
short *d,least,most;
char *errprompt;
{
char s[30];
short success = -1, ndiscard = 0;
char c, buf[200];
scanf("%s",s);
while(success < 0) {
success = parseshort(s,d);
if((success == 0) && ((*d < least) || (*d > most))) {
printf("%d is out of range; allowed %d to %d -- try again.\n",
*d,least,most);
success = -1;
}
if(success < 0) {
/* if there's error on input, clean out the rest of the line */
ndiscard = 0;
while((c = getchar()) != '\n') {
buf[ndiscard] = c;
ndiscard++;
}
if(ndiscard > 0) {
buf[ndiscard] = '\0'; /* cap the string */
printf("Rest of input (%s) has been discarded.\n",buf);
}
printf("%s",errprompt);
printf("Try again:");
scanf("%s",s);
}
}
return( (int) success);
}
double bab_to_dec(bab)
struct coord bab;
/* converts a "babylonian" (sexigesimal) structure into
double-precision floating point ("decimal") number. */
{
double x;
x = bab.sign * (bab.hh + bab.mm / 60. + bab.ss / 3600.);
return(x);
}
void dec_to_bab (deci,bab)
double deci;
struct coord *bab;
/* function for converting decimal to babylonian hh mm ss.ss */
{
int hr_int, min_int;
if (deci >= 0.) bab->sign = 1;
else {
bab->sign = -1;
deci = -1. * deci;
}
hr_int = deci; /* use conversion conventions to truncate */
bab->hh = hr_int;
min_int = 60. * (deci - bab->hh);
bab->mm = min_int;
bab->ss = 3600. * (deci - bab->hh - bab->mm / 60.);
}
short get_line(s)
char *s;
/* gets a line terminated by end-of-line and returns number of characters. */
{
char c;
short i = 0;
c = getchar(); /* get the first character */
/* chew through until you hit non white space */
while((c == '\n') || (c == ' ') || (c == '\t')) c = getchar();
s[i]=c;
i++;
/* keep going til the next newline */
while((c=getchar()) != '\n') {
s[i]=c;
i++;
}
s[i]='\0'; /* terminate with null */
return(i);
}
int is_delimited(char *instrng)
/* Checks to see if the instrng has non-numeric
characters, which are then assumed to be delimiters
(like colons). */
{
int val = 0;
while(*instrng != '\0') {
if((*instrng >= '0' && *instrng <= '9') || *instrng == '-'
|| *instrng == '+') {
instrng++;
}
else return(1);
}
return(0);
}
double conv_delimited_coord(char *instrng)
/* Handed a string instr, converts to a double-precision
coordinate under the assumption that the string is a
continguous, delimiter-separated sexagesimal triplet, e.g.
-0 degr 12m 02.33s would be -0:12:2.33 or -0:12:02.33.
The whole thing has to be continguous (no whitespace!).
*/
{
char substr[20], *place, *substrplace;
int hrs, min, sign = 1;
double secs, val;
place = instrng;
substrplace = substr;
while(*place == ' ' || *place == '\t') place++;
if(*place == '+') {
sign = 1;
place++;
}
if(*place == '-') {
sign = -1;
place++;
}
while(*place >= '0' && *place <= '9') {
*substrplace = *place;
place++; substrplace++;
}
*substrplace = '\0';
sscanf(substr,"%d",&hrs);
substrplace=substr;
place++; /* skip the colon */
while(*place >= '0' && *place <= '9') {
*substrplace = *place;
place++; substrplace++;
}
*substrplace = '\0';
sscanf(substr,"%d",&min);
substrplace=substr;
place++; /* skip the colon */
while((*place >= '0' && *place <= '9') || *place == '.' ) {
*substrplace = *place;