altos: Add telerepeat-v1.0
[fw/altos] / src / kernel / ao_convert_pa.c
1 /*
2  * Copyright © 2012 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 #if !defined(AO_CONVERT_TEST) && !defined(AO_FLIGHT_TEST)
19 #include "ao.h"
20 #endif
21
22 #ifndef AO_CONST_ATTRIB
23 #define AO_CONST_ATTRIB
24 #endif
25
26 static const alt_t altitude_table[] AO_CONST_ATTRIB = {
27 #if AO_SMALL_ALTITUDE_TABLE
28 #include "altitude-pa-small.h"
29 #else
30 #include "altitude-pa.h"
31 #endif
32 };
33
34 #ifndef FETCH_ALT
35 #define FETCH_ALT(o)    altitude_table[o]
36 #endif
37
38 #define ALT_SCALE       (1 << ALT_SHIFT)
39 #define ALT_MASK        (ALT_SCALE - 1)
40
41 alt_t
42 ao_pa_to_altitude(pres_t pa)
43 {
44         int16_t o;
45         int16_t part;
46         alt_t low, high;
47
48         if (pa < 0)
49                 pa = 0;
50         if (pa > 120000L)
51                 pa = 120000L;
52         o = pa >> ALT_SHIFT;
53         part = pa & ALT_MASK;
54
55         low = (alt_t) FETCH_ALT(o) * (ALT_SCALE - part);
56         high = (alt_t) FETCH_ALT(o+1) * part + (ALT_SCALE >> 1);
57         return (low + high) >> ALT_SHIFT;
58 }
59
60 #ifdef AO_CONVERT_TEST
61 pres_t
62 ao_altitude_to_pa(alt_t alt)
63 {
64         alt_t   span, sub_span;
65         uint16_t        l, h, m;
66         int32_t         pa;
67
68         l = 0;
69         h = NALT - 1;
70         while ((h - l) != 1) {
71                 m = (l + h) >> 1;
72                 if (altitude_table[m] < alt)
73                         h = m;
74                 else
75                         l = m;
76         }
77         span = altitude_table[l] - altitude_table[h];
78         sub_span = altitude_table[l] - alt;
79         pa = ((((alt_t) l * (span - sub_span) + (alt_t) h * sub_span) << ALT_SHIFT) + (span >> 1)) / span;
80         if (pa > 120000)
81                 pa = 120000;
82         if (pa < 0)
83                 pa = 0;
84         return pa;
85 }
86 #endif