aboutsummaryrefslogtreecommitdiff
path: root/src/rtodms.cpp
blob: 674cebdf9e0db5bef9d5dc4b216582292c5e4008 (plain)
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
/* Convert radian argument to DMS ascii format */

#include <math.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>

#include "projects.h"

/*
** RES is fractional second figures
** RES60 = 60 * RES
** CONV = 180 * 3600 * RES / PI (radians to RES seconds)
*/
	static double
RES = 1000.,
RES60 = 60000.,
CONV = 206264806.24709635516;
	static char
format[50] = "%dd%d'%.3f\"%c";
	static int
dolong = 0;
	void
set_rtodms(int fract, int con_w) {
	int i;

	if (fract >= 0 && fract < 9 ) {
		RES = 1.;
		/* following not very elegant, but used infrequently */
		for (i = 0; i < fract; ++i)
			RES *= 10.;
		RES60 = RES * 60.;
		CONV = 180. * 3600. * RES / M_PI;
		if (! con_w)
			(void)sprintf(format,"%%dd%%d'%%.%df\"%%c", fract);
		else
			(void)sprintf(format,"%%dd%%02d'%%0%d.%df\"%%c",
				fract+2+(fract?1:0), fract);
		dolong = con_w;
	}
}
	char *
rtodms(char *s, double r, int pos, int neg) {
	int deg, min, sign;
	char *ss = s;
	double sec;

	if (r < 0) {
		r = -r;
		if  (!pos) { *ss++ = '-'; sign = 0; }
		else sign = neg;
	} else
		sign = pos;
	r = floor(r * CONV + .5);
	sec = fmod(r / RES, 60.);
	r = floor(r / RES60);
	min = (int)fmod(r, 60.);
	r = floor(r / 60.);
	deg = (int)r;

	if (dolong)
		(void)sprintf(ss,format,deg,min,sec,sign);
	else if (sec != 0.0) {
		char *p, *q;
		/* double prime + pos/neg suffix (if included) + NUL */
		size_t suffix_len = sign ? 3 : 2;

		(void)sprintf(ss,format,deg,min,sec,sign);
                /* Replace potential decimal comma by decimal point for non C locale */
                for( p = ss; *p != '\0'; ++p ) {
                    if( *p == ',' ) {
                        *p = '.';
                        break;
                    }
                }
		for (q = p = ss + strlen(ss) - suffix_len; *p == '0'; --p) ;
		if (*p != '.')
			++p;
		if (++q != p)
			(void)memmove(p, q, suffix_len);
	} else if (min)
		(void)sprintf(ss,"%dd%d'%c",deg,min,sign);
	else
		(void)sprintf(ss,"%dd%c",deg, sign);
	return s;
}