Removing old svn keywords.
[monky] / src / temphelper.c
1 /* temphelper.c:  aid in converting temperature units
2  *
3  * Copyright (C) 2008 Phil Sutter <Phil@nwl.cc>
4  *
5  * This library is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
18  * USA.
19  *
20  */
21 #include "config.h"
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <ctype.h>
26 #include <sys/types.h>
27 #include "temphelper.h"
28
29 /* default to output in celsius */
30 static enum TEMP_UNIT output_unit = TEMP_CELSIUS;
31
32 static double
33 fahrenheit_to_celsius(double n)
34 {
35         return ((n - 32) * 5 / 9);
36 }
37
38 static double
39 celsius_to_fahrenheit(double n)
40 {
41         return ((n * 9 / 5) + 32);
42 }
43
44 int
45 set_temp_output_unit(const char *name)
46 {
47         size_t i;
48         int rc = 0;
49         char *buf;
50
51         if (!name)
52                 return 1;
53
54         buf = strdup(name);
55         for (i = 0; i < strlen(name); i++)
56                 buf[i] = tolower(name[i]);
57
58         if (!strcmp(buf, "celsius"))
59                 output_unit = TEMP_CELSIUS;
60         else if (!strcmp(buf, "fahrenheit"))
61                 output_unit = TEMP_FAHRENHEIT;
62         else
63                 rc = 1;
64         free(buf);
65         return rc;
66 }
67
68 static double
69 convert_temp_output(double n, enum TEMP_UNIT input_unit)
70 {
71         if (input_unit == output_unit)
72                 return n;
73
74         switch(output_unit) {
75                 case TEMP_CELSIUS:
76                         return fahrenheit_to_celsius(n);
77                 case TEMP_FAHRENHEIT:
78                         return celsius_to_fahrenheit(n);
79         }
80         /* NOT REACHED */
81         return 0.0;
82 }
83
84 int temp_print(char *p, size_t p_max_size, double n, enum TEMP_UNIT input_unit)
85 {
86         double out, plen;
87
88         out = convert_temp_output(n, input_unit);
89
90         /* Skip decimal for big values but keep padding sane
91          * (i.e. use 4 chars for them)
92          */
93         plen = snprintf(p, p_max_size, ((out > 100.0) ?
94                                         "%4.0lf" : "%2.1lf") , out);
95         return !(plen >= p_max_size);
96 }