make unit of all temperatures selectable
[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  * $Id$
21  *
22  */
23 #include "config.h"
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <ctype.h>
28 #include <sys/types.h>
29 #include "temphelper.h"
30
31 /* default to output in celsius */
32 static enum TEMP_UNIT output_unit = TEMP_CELSIUS;
33
34 static double
35 fahrenheit_to_celsius(double n)
36 {
37         return ((n - 32) * 5 / 9);
38 }
39
40 static double
41 celsius_to_fahrenheit(double n)
42 {
43         return ((n * 9 / 5) + 32);
44 }
45
46 int
47 set_temp_output_unit(const char *name)
48 {
49         size_t i;
50         int rc = 0;
51         char *buf;
52
53         if (!name)
54                 return 1;
55
56         buf = strdup(name);
57         for (i = 0; i < strlen(name); i++)
58                 buf[i] = tolower(name[i]);
59
60         if (!strcmp(buf, "celsius"))
61                 output_unit = TEMP_CELSIUS;
62         else if (!strcmp(buf, "fahrenheit"))
63                 output_unit = TEMP_FAHRENHEIT;
64         else
65                 rc = 1;
66         free(buf);
67         return rc;
68 }
69
70 static double
71 convert_temp_output(double n, enum TEMP_UNIT input_unit)
72 {
73         if (input_unit == output_unit)
74                 return n;
75
76         switch(output_unit) {
77                 case TEMP_CELSIUS:
78                         return fahrenheit_to_celsius(n);
79                 case TEMP_FAHRENHEIT:
80                         return celsius_to_fahrenheit(n);
81         }
82         /* NOT REACHED */
83         return 0.0;
84 }
85
86 int temp_print(char *p, size_t p_max_size, double n, enum TEMP_UNIT input_unit)
87 {
88         double out, plen;
89
90         out = convert_temp_output(n, input_unit);
91
92         /* Skip decimal for big values but keep padding sane
93          * (i.e. use 4 chars for them)
94          */
95         plen = snprintf(p, p_max_size, ((out > 100.0) ?
96                                         "%4.0lf" : "%2.1lf") , out);
97         return !(plen >= p_max_size);
98 }