fixed indenting
[rrdtool.git] / src / rrd_rpncalc.c
1 /****************************************************************************
2  * RRDtool 1.2.23  Copyright by Tobi Oetiker, 1997-2007
3  ****************************************************************************
4  * rrd_rpncalc.c  RPN calculator functions
5  ****************************************************************************/
6
7 #include "rrd_tool.h"
8 #include "rrd_rpncalc.h"
9 #include "rrd_graph.h"
10 #include <limits.h>
11 #include <locale.h>
12
13 short     addop2str(
14     enum op_en op,
15     enum op_en op_type,
16     char *op_str,
17     char **result_str,
18     unsigned short *offset);
19 int       tzoffset(
20     time_t);            /* used to implement LTIME */
21
22 short rpn_compact(
23     rpnp_t *rpnp,
24     rpn_cdefds_t **rpnc,
25     short *count)
26 {
27     short     i;
28
29     *count = 0;
30     /* count the number of rpn nodes */
31     while (rpnp[*count].op != OP_END)
32         (*count)++;
33     if (++(*count) > DS_CDEF_MAX_RPN_NODES) {
34         rrd_set_error("Maximum %d RPN nodes permitted",
35                       DS_CDEF_MAX_RPN_NODES);
36         return -1;
37     }
38
39     /* allocate memory */
40     *rpnc = (rpn_cdefds_t *) calloc(*count, sizeof(rpn_cdefds_t));
41     for (i = 0; rpnp[i].op != OP_END; i++) {
42         (*rpnc)[i].op = (char) rpnp[i].op;
43         if (rpnp[i].op == OP_NUMBER) {
44             /* rpnp.val is a double, rpnc.val is a short */
45             double    temp = floor(rpnp[i].val);
46
47             if (temp < SHRT_MIN || temp > SHRT_MAX) {
48                 rrd_set_error
49                     ("constants must be integers in the interval (%d, %d)",
50                      SHRT_MIN, SHRT_MAX);
51                 free(*rpnc);
52                 return -1;
53             }
54             (*rpnc)[i].val = (short) temp;
55         } else if (rpnp[i].op == OP_VARIABLE || rpnp[i].op == OP_PREV_OTHER) {
56             (*rpnc)[i].val = (short) rpnp[i].ptr;
57         }
58     }
59     /* terminate the sequence */
60     (*rpnc)[(*count) - 1].op = OP_END;
61     return 0;
62 }
63
64 rpnp_t   *rpn_expand(
65     rpn_cdefds_t *rpnc)
66 {
67     short     i;
68     rpnp_t   *rpnp;
69
70     /* DS_CDEF_MAX_RPN_NODES is small, so at the expense of some wasted
71      * memory we avoid any reallocs */
72     rpnp = (rpnp_t *) calloc(DS_CDEF_MAX_RPN_NODES, sizeof(rpnp_t));
73     if (rpnp == NULL)
74         return NULL;
75     for (i = 0; rpnc[i].op != OP_END; ++i) {
76         rpnp[i].op = (long) rpnc[i].op;
77         if (rpnp[i].op == OP_NUMBER) {
78             rpnp[i].val = (double) rpnc[i].val;
79         } else if (rpnp[i].op == OP_VARIABLE || rpnp[i].op == OP_PREV_OTHER) {
80             rpnp[i].ptr = (long) rpnc[i].val;
81         }
82     }
83     /* terminate the sequence */
84     rpnp[i].op = OP_END;
85     return rpnp;
86 }
87
88 /* rpn_compact2str: convert a compact sequence of RPN operator nodes back
89  * into a CDEF string. This function is used by rrd_dump.
90  * arguments:
91  *  rpnc: an array of compact RPN operator nodes
92  *  ds_def: a pointer to the data source definition section of an RRD header
93  *   for lookup of data source names by index
94  *  str: out string, memory is allocated by the function, must be freed by the
95  *   the caller */
96 void rpn_compact2str(
97     rpn_cdefds_t *rpnc,
98     ds_def_t *ds_def,
99     char **str)
100 {
101     unsigned short i, offset = 0;
102     char      buffer[7];    /* short as a string */
103
104     for (i = 0; rpnc[i].op != OP_END; i++) {
105         if (i > 0)
106             (*str)[offset++] = ',';
107
108 #define add_op(VV,VVV) \
109           if (addop2str(rpnc[i].op, VV, VVV, str, &offset) == 1) continue;
110
111         if (rpnc[i].op == OP_NUMBER) {
112             /* convert a short into a string */
113 #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__)
114             _itoa(rpnc[i].val, buffer, 10);
115 #else
116             sprintf(buffer, "%d", rpnc[i].val);
117 #endif
118             add_op(OP_NUMBER, buffer)
119         }
120
121         if (rpnc[i].op == OP_VARIABLE) {
122             char     *ds_name = ds_def[rpnc[i].val].ds_nam;
123
124             add_op(OP_VARIABLE, ds_name)
125         }
126
127         if (rpnc[i].op == OP_PREV_OTHER) {
128             char     *ds_name = ds_def[rpnc[i].val].ds_nam;
129
130             add_op(OP_VARIABLE, ds_name)
131         }
132 #undef add_op
133
134 #define add_op(VV,VVV) \
135           if (addop2str(rpnc[i].op, VV, #VVV, str, &offset) == 1) continue;
136
137         add_op(OP_ADD, +)
138             add_op(OP_SUB, -)
139             add_op(OP_MUL, *)
140             add_op(OP_DIV, /)
141             add_op(OP_MOD, %)
142             add_op(OP_SIN, SIN)
143             add_op(OP_COS, COS)
144             add_op(OP_LOG, LOG)
145             add_op(OP_FLOOR, FLOOR)
146             add_op(OP_CEIL, CEIL)
147             add_op(OP_EXP, EXP)
148             add_op(OP_DUP, DUP)
149             add_op(OP_EXC, EXC)
150             add_op(OP_POP, POP)
151             add_op(OP_LT, LT)
152             add_op(OP_LE, LE)
153             add_op(OP_GT, GT)
154             add_op(OP_GE, GE)
155             add_op(OP_EQ, EQ)
156             add_op(OP_IF, IF)
157             add_op(OP_MIN, MIN)
158             add_op(OP_MAX, MAX)
159             add_op(OP_LIMIT, LIMIT)
160             add_op(OP_UNKN, UNKN)
161             add_op(OP_UN, UN)
162             add_op(OP_NEGINF, NEGINF)
163             add_op(OP_NE, NE)
164             add_op(OP_PREV, PREV)
165             add_op(OP_INF, INF)
166             add_op(OP_ISINF, ISINF)
167             add_op(OP_NOW, NOW)
168             add_op(OP_LTIME, LTIME)
169             add_op(OP_TIME, TIME)
170             add_op(OP_ATAN2, ATAN2)
171             add_op(OP_ATAN, ATAN)
172             add_op(OP_SQRT, SQRT)
173             add_op(OP_SORT, SORT)
174             add_op(OP_REV, REV)
175             add_op(OP_TREND, TREND)
176             add_op(OP_TRENDNAN, TRENDNAN)
177             add_op(OP_RAD2DEG, RAD2DEG)
178             add_op(OP_DEG2RAD, DEG2RAD)
179             add_op(OP_AVG, AVG)
180             add_op(OP_ABS, ABS)
181 #undef add_op
182     }
183     (*str)[offset] = '\0';
184
185 }
186
187 short addop2str(
188     enum op_en op,
189     enum op_en op_type,
190     char *op_str,
191     char **result_str,
192     unsigned short *offset)
193 {
194     if (op == op_type) {
195         short     op_len;
196
197         op_len = strlen(op_str);
198         *result_str = (char *) rrd_realloc(*result_str,
199                                            (op_len + 1 +
200                                             *offset) * sizeof(char));
201         if (*result_str == NULL) {
202             rrd_set_error("failed to alloc memory in addop2str");
203             return -1;
204         }
205         strncpy(&((*result_str)[*offset]), op_str, op_len);
206         *offset += op_len;
207         return 1;
208     }
209     return 0;
210 }
211
212 void parseCDEF_DS(
213     const char *def,
214     rrd_t *rrd,
215     int ds_idx)
216 {
217     rpnp_t   *rpnp = NULL;
218     rpn_cdefds_t *rpnc = NULL;
219     short     count, i;
220
221     rpnp = rpn_parse((void *) rrd, def, &lookup_DS);
222     if (rpnp == NULL) {
223         rrd_set_error("failed to parse computed data source");
224         return;
225     }
226     /* Check for OP nodes not permitted in COMPUTE DS.
227      * Moved this check from within rpn_compact() because it really is
228      * COMPUTE DS specific. This is less efficient, but creation doesn't
229      * occur too often. */
230     for (i = 0; rpnp[i].op != OP_END; i++) {
231         if (rpnp[i].op == OP_TIME || rpnp[i].op == OP_LTIME ||
232             rpnp[i].op == OP_PREV || rpnp[i].op == OP_COUNT) {
233             rrd_set_error
234                 ("operators time, ltime, prev and count not supported with DS COMPUTE");
235             free(rpnp);
236             return;
237         }
238     }
239     if (rpn_compact(rpnp, &rpnc, &count) == -1) {
240         free(rpnp);
241         return;
242     }
243     /* copy the compact rpn representation over the ds_def par array */
244     memcpy((void *) &(rrd->ds_def[ds_idx].par[DS_cdef]),
245            (void *) rpnc, count * sizeof(rpn_cdefds_t));
246     free(rpnp);
247     free(rpnc);
248 }
249
250 /* lookup a data source name in the rrd struct and return the index,
251  * should use ds_match() here except:
252  * (1) need a void * pointer to the rrd
253  * (2) error handling is left to the caller
254  */
255 long lookup_DS(
256     void *rrd_vptr,
257     char *ds_name)
258 {
259     unsigned int i;
260     rrd_t    *rrd;
261
262     rrd = (rrd_t *) rrd_vptr;
263
264     for (i = 0; i < rrd->stat_head->ds_cnt; ++i) {
265         if (strcmp(ds_name, rrd->ds_def[i].ds_nam) == 0)
266             return i;
267     }
268     /* the caller handles a bad data source name in the rpn string */
269     return -1;
270 }
271
272 /* rpn_parse : parse a string and generate a rpnp array; modified
273  * str2rpn() originally included in rrd_graph.c
274  * arguments:
275  * key_hash: a transparent argument passed to lookup(); conceptually this
276  *    is a hash object for lookup of a numeric key given a variable name
277  * expr: the string RPN expression, including variable names
278  * lookup(): a function that retrieves a numeric key given a variable name
279  */
280 rpnp_t   *rpn_parse(
281     void *key_hash,
282     const char *const expr_const,
283     long      (*lookup) (void *,
284                          char *))
285 {
286     int       pos = 0;
287     char     *expr;
288     long      steps = -1;
289     rpnp_t   *rpnp;
290     char      vname[MAX_VNAME_LEN + 10];
291     char     *old_locale;
292
293     old_locale = setlocale(LC_NUMERIC, "C");
294
295     rpnp = NULL;
296     expr = (char *) expr_const;
297
298     while (*expr) {
299         if ((rpnp = (rpnp_t *) rrd_realloc(rpnp, (++steps + 2) *
300                                            sizeof(rpnp_t))) == NULL) {
301             setlocale(LC_NUMERIC, old_locale);
302             return NULL;
303         }
304
305         else if ((sscanf(expr, "%lf%n", &rpnp[steps].val, &pos) == 1)
306                  && (expr[pos] == ',')) {
307             rpnp[steps].op = OP_NUMBER;
308             expr += pos;
309         }
310 #define match_op(VV,VVV) \
311         else if (strncmp(expr, #VVV, strlen(#VVV))==0 && ( expr[strlen(#VVV)] == ',' || expr[strlen(#VVV)] == '\0' )){ \
312             rpnp[steps].op = VV; \
313             expr+=strlen(#VVV); \
314         }
315
316 #define match_op_param(VV,VVV) \
317         else if (sscanf(expr, #VVV "(" DEF_NAM_FMT ")",vname) == 1) { \
318           int length = 0; \
319           if ((length = strlen(#VVV)+strlen(vname)+2, \
320               expr[length] == ',' || expr[length] == '\0') ) { \
321              rpnp[steps].op = VV; \
322              rpnp[steps].ptr = (*lookup)(key_hash,vname); \
323              if (rpnp[steps].ptr < 0) { \
324                            free(rpnp); \
325                            return NULL; \
326                          } else expr+=length; \
327           } \
328         }
329
330         match_op(OP_ADD, +)
331             match_op(OP_SUB, -)
332             match_op(OP_MUL, *)
333             match_op(OP_DIV, /)
334             match_op(OP_MOD, %)
335             match_op(OP_SIN, SIN)
336             match_op(OP_COS, COS)
337             match_op(OP_LOG, LOG)
338             match_op(OP_FLOOR, FLOOR)
339             match_op(OP_CEIL, CEIL)
340             match_op(OP_EXP, EXP)
341             match_op(OP_DUP, DUP)
342             match_op(OP_EXC, EXC)
343             match_op(OP_POP, POP)
344             match_op(OP_LTIME, LTIME)
345             match_op(OP_LT, LT)
346             match_op(OP_LE, LE)
347             match_op(OP_GT, GT)
348             match_op(OP_GE, GE)
349             match_op(OP_EQ, EQ)
350             match_op(OP_IF, IF)
351             match_op(OP_MIN, MIN)
352             match_op(OP_MAX, MAX)
353             match_op(OP_LIMIT, LIMIT)
354             /* order is important here ! .. match longest first */
355             match_op(OP_UNKN, UNKN)
356             match_op(OP_UN, UN)
357             match_op(OP_NEGINF, NEGINF)
358             match_op(OP_NE, NE)
359             match_op(OP_COUNT, COUNT)
360             match_op_param(OP_PREV_OTHER, PREV)
361             match_op(OP_PREV, PREV)
362             match_op(OP_INF, INF)
363             match_op(OP_ISINF, ISINF)
364             match_op(OP_NOW, NOW)
365             match_op(OP_TIME, TIME)
366             match_op(OP_ATAN2, ATAN2)
367             match_op(OP_ATAN, ATAN)
368             match_op(OP_SQRT, SQRT)
369             match_op(OP_SORT, SORT)
370             match_op(OP_REV, REV)
371             match_op(OP_TREND, TREND)
372             match_op(OP_TRENDNAN, TRENDNAN)
373             match_op(OP_RAD2DEG, RAD2DEG)
374             match_op(OP_DEG2RAD, DEG2RAD)
375             match_op(OP_AVG, AVG)
376             match_op(OP_ABS, ABS)
377 #undef match_op
378             else if ((sscanf(expr, DEF_NAM_FMT "%n", vname, &pos) == 1)
379                      && ((rpnp[steps].ptr = (*lookup) (key_hash, vname)) !=
380                          -1)) {
381             rpnp[steps].op = OP_VARIABLE;
382             expr += pos;
383         }
384
385         else {
386             setlocale(LC_NUMERIC, old_locale);
387             free(rpnp);
388             return NULL;
389         }
390
391         if (*expr == 0)
392             break;
393         if (*expr == ',')
394             expr++;
395         else {
396             setlocale(LC_NUMERIC, old_locale);
397             free(rpnp);
398             return NULL;
399         }
400     }
401     rpnp[steps + 1].op = OP_END;
402     setlocale(LC_NUMERIC, old_locale);
403     return rpnp;
404 }
405
406 void rpnstack_init(
407     rpnstack_t *rpnstack)
408 {
409     rpnstack->s = NULL;
410     rpnstack->dc_stacksize = 0;
411     rpnstack->dc_stackblock = 100;
412 }
413
414 void rpnstack_free(
415     rpnstack_t *rpnstack)
416 {
417     if (rpnstack->s != NULL)
418         free(rpnstack->s);
419     rpnstack->dc_stacksize = 0;
420 }
421
422 static int rpn_compare_double(
423     const void *x,
424     const void *y)
425 {
426     double    diff = *((const double *) x) - *((const double *) y);
427
428     return (diff < 0) ? -1 : (diff > 0) ? 1 : 0;
429 }
430
431 /* rpn_calc: run the RPN calculator; also performs variable substitution;
432  * moved and modified from data_calc() originally included in rrd_graph.c 
433  * arguments:
434  * rpnp : an array of RPN operators (including variable references)
435  * rpnstack : the initialized stack
436  * data_idx : when data_idx is a multiple of rpnp.step, the rpnp.data pointer
437  *   is advanced by rpnp.ds_cnt; used only for variable substitution
438  * output : an array of output values; OP_PREV assumes this array contains
439  *   the "previous" value at index position output_idx-1; the definition of
440  *   "previous" depends on the calling environment
441  * output_idx : an index into the output array in which to store the output
442  *   of the RPN calculator
443  * returns: -1 if the computation failed (also calls rrd_set_error)
444  *           0 on success
445  */
446 short rpn_calc(
447     rpnp_t *rpnp,
448     rpnstack_t *rpnstack,
449     long data_idx,
450     rrd_value_t *output,
451     int output_idx)
452 {
453     int       rpi;
454     long      stptr = -1;
455
456     /* process each op from the rpn in turn */
457     for (rpi = 0; rpnp[rpi].op != OP_END; rpi++) {
458         /* allocate or grow the stack */
459         if (stptr + 5 > rpnstack->dc_stacksize) {
460             /* could move this to a separate function */
461             rpnstack->dc_stacksize += rpnstack->dc_stackblock;
462             rpnstack->s = rrd_realloc(rpnstack->s,
463                                       (rpnstack->dc_stacksize) *
464                                       sizeof(*(rpnstack->s)));
465             if (rpnstack->s == NULL) {
466                 rrd_set_error("RPN stack overflow");
467                 return -1;
468             }
469         }
470 #define stackunderflow(MINSIZE)                         \
471         if(stptr<MINSIZE){                              \
472             rrd_set_error("RPN stack underflow");       \
473             return -1;                                  \
474         }
475
476         switch (rpnp[rpi].op) {
477         case OP_NUMBER:
478             rpnstack->s[++stptr] = rpnp[rpi].val;
479             break;
480         case OP_VARIABLE:
481         case OP_PREV_OTHER:
482             /* Sanity check: VDEFs shouldn't make it here */
483             if (rpnp[rpi].ds_cnt == 0) {
484                 rrd_set_error("VDEF made it into rpn_calc... aborting");
485                 return -1;
486             } else {
487                 /* make sure we pull the correct value from
488                  * the *.data array. Adjust the pointer into
489                  * the array acordingly. Advance the ptr one
490                  * row in the rra (skip over non-relevant
491                  * data sources)
492                  */
493                 if (rpnp[rpi].op == OP_VARIABLE) {
494                     rpnstack->s[++stptr] = *(rpnp[rpi].data);
495                 } else {
496                     if ((output_idx) <= 0) {
497                         rpnstack->s[++stptr] = DNAN;
498                     } else {
499                         rpnstack->s[++stptr] =
500                             *(rpnp[rpi].data - rpnp[rpi].ds_cnt);
501                     }
502
503                 }
504                 if (data_idx % rpnp[rpi].step == 0) {
505                     rpnp[rpi].data += rpnp[rpi].ds_cnt;
506                 }
507             }
508             break;
509         case OP_COUNT:
510             rpnstack->s[++stptr] = (output_idx + 1);    /* Note: Counter starts at 1 */
511             break;
512         case OP_PREV:
513             if ((output_idx) <= 0) {
514                 rpnstack->s[++stptr] = DNAN;
515             } else {
516                 rpnstack->s[++stptr] = output[output_idx - 1];
517             }
518             break;
519         case OP_UNKN:
520             rpnstack->s[++stptr] = DNAN;
521             break;
522         case OP_INF:
523             rpnstack->s[++stptr] = DINF;
524             break;
525         case OP_NEGINF:
526             rpnstack->s[++stptr] = -DINF;
527             break;
528         case OP_NOW:
529             rpnstack->s[++stptr] = (double) time(NULL);
530             break;
531         case OP_TIME:
532             /* HACK: this relies on the data_idx being the time,
533              ** which the within-function scope is unaware of */
534             rpnstack->s[++stptr] = (double) data_idx;
535             break;
536         case OP_LTIME:
537             rpnstack->s[++stptr] =
538                 (double) tzoffset(data_idx) + (double) data_idx;
539             break;
540         case OP_ADD:
541             stackunderflow(1);
542             rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
543                 + rpnstack->s[stptr];
544             stptr--;
545             break;
546         case OP_SUB:
547             stackunderflow(1);
548             rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
549                 - rpnstack->s[stptr];
550             stptr--;
551             break;
552         case OP_MUL:
553             stackunderflow(1);
554             rpnstack->s[stptr - 1] = (rpnstack->s[stptr - 1])
555                 * (rpnstack->s[stptr]);
556             stptr--;
557             break;
558         case OP_DIV:
559             stackunderflow(1);
560             rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
561                 / rpnstack->s[stptr];
562             stptr--;
563             break;
564         case OP_MOD:
565             stackunderflow(1);
566             rpnstack->s[stptr - 1] = fmod(rpnstack->s[stptr - 1]
567                                           , rpnstack->s[stptr]);
568             stptr--;
569             break;
570         case OP_SIN:
571             stackunderflow(0);
572             rpnstack->s[stptr] = sin(rpnstack->s[stptr]);
573             break;
574         case OP_ATAN:
575             stackunderflow(0);
576             rpnstack->s[stptr] = atan(rpnstack->s[stptr]);
577             break;
578         case OP_RAD2DEG:
579             stackunderflow(0);
580             rpnstack->s[stptr] = 57.29577951 * rpnstack->s[stptr];
581             break;
582         case OP_DEG2RAD:
583             stackunderflow(0);
584             rpnstack->s[stptr] = 0.0174532952 * rpnstack->s[stptr];
585             break;
586         case OP_ATAN2:
587             stackunderflow(1);
588             rpnstack->s[stptr - 1] = atan2(rpnstack->s[stptr - 1],
589                                            rpnstack->s[stptr]);
590             stptr--;
591             break;
592         case OP_COS:
593             stackunderflow(0);
594             rpnstack->s[stptr] = cos(rpnstack->s[stptr]);
595             break;
596         case OP_CEIL:
597             stackunderflow(0);
598             rpnstack->s[stptr] = ceil(rpnstack->s[stptr]);
599             break;
600         case OP_FLOOR:
601             stackunderflow(0);
602             rpnstack->s[stptr] = floor(rpnstack->s[stptr]);
603             break;
604         case OP_LOG:
605             stackunderflow(0);
606             rpnstack->s[stptr] = log(rpnstack->s[stptr]);
607             break;
608         case OP_DUP:
609             stackunderflow(0);
610             rpnstack->s[stptr + 1] = rpnstack->s[stptr];
611             stptr++;
612             break;
613         case OP_POP:
614             stackunderflow(0);
615             stptr--;
616             break;
617         case OP_EXC:
618             stackunderflow(1);
619             {
620                 double    dummy;
621
622                 dummy = rpnstack->s[stptr];
623                 rpnstack->s[stptr] = rpnstack->s[stptr - 1];
624                 rpnstack->s[stptr - 1] = dummy;
625             }
626             break;
627         case OP_EXP:
628             stackunderflow(0);
629             rpnstack->s[stptr] = exp(rpnstack->s[stptr]);
630             break;
631         case OP_LT:
632             stackunderflow(1);
633             if (isnan(rpnstack->s[stptr - 1]));
634             else if (isnan(rpnstack->s[stptr]))
635                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
636             else
637                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] <
638                     rpnstack->s[stptr] ? 1.0 : 0.0;
639             stptr--;
640             break;
641         case OP_LE:
642             stackunderflow(1);
643             if (isnan(rpnstack->s[stptr - 1]));
644             else if (isnan(rpnstack->s[stptr]))
645                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
646             else
647                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] <=
648                     rpnstack->s[stptr] ? 1.0 : 0.0;
649             stptr--;
650             break;
651         case OP_GT:
652             stackunderflow(1);
653             if (isnan(rpnstack->s[stptr - 1]));
654             else if (isnan(rpnstack->s[stptr]))
655                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
656             else
657                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] >
658                     rpnstack->s[stptr] ? 1.0 : 0.0;
659             stptr--;
660             break;
661         case OP_GE:
662             stackunderflow(1);
663             if (isnan(rpnstack->s[stptr - 1]));
664             else if (isnan(rpnstack->s[stptr]))
665                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
666             else
667                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] >=
668                     rpnstack->s[stptr] ? 1.0 : 0.0;
669             stptr--;
670             break;
671         case OP_NE:
672             stackunderflow(1);
673             if (isnan(rpnstack->s[stptr - 1]));
674             else if (isnan(rpnstack->s[stptr]))
675                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
676             else
677                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] ==
678                     rpnstack->s[stptr] ? 0.0 : 1.0;
679             stptr--;
680             break;
681         case OP_EQ:
682             stackunderflow(1);
683             if (isnan(rpnstack->s[stptr - 1]));
684             else if (isnan(rpnstack->s[stptr]))
685                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
686             else
687                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] ==
688                     rpnstack->s[stptr] ? 1.0 : 0.0;
689             stptr--;
690             break;
691         case OP_IF:
692             stackunderflow(2);
693             rpnstack->s[stptr - 2] = rpnstack->s[stptr - 2] != 0.0 ?
694                 rpnstack->s[stptr - 1] : rpnstack->s[stptr];
695             stptr--;
696             stptr--;
697             break;
698         case OP_MIN:
699             stackunderflow(1);
700             if (isnan(rpnstack->s[stptr - 1]));
701             else if (isnan(rpnstack->s[stptr]))
702                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
703             else if (rpnstack->s[stptr - 1] > rpnstack->s[stptr])
704                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
705             stptr--;
706             break;
707         case OP_MAX:
708             stackunderflow(1);
709             if (isnan(rpnstack->s[stptr - 1]));
710             else if (isnan(rpnstack->s[stptr]))
711                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
712             else if (rpnstack->s[stptr - 1] < rpnstack->s[stptr])
713                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
714             stptr--;
715             break;
716         case OP_LIMIT:
717             stackunderflow(2);
718             if (isnan(rpnstack->s[stptr - 2]));
719             else if (isnan(rpnstack->s[stptr - 1]))
720                 rpnstack->s[stptr - 2] = rpnstack->s[stptr - 1];
721             else if (isnan(rpnstack->s[stptr]))
722                 rpnstack->s[stptr - 2] = rpnstack->s[stptr];
723             else if (rpnstack->s[stptr - 2] < rpnstack->s[stptr - 1])
724                 rpnstack->s[stptr - 2] = DNAN;
725             else if (rpnstack->s[stptr - 2] > rpnstack->s[stptr])
726                 rpnstack->s[stptr - 2] = DNAN;
727             stptr -= 2;
728             break;
729         case OP_UN:
730             stackunderflow(0);
731             rpnstack->s[stptr] = isnan(rpnstack->s[stptr]) ? 1.0 : 0.0;
732             break;
733         case OP_ISINF:
734             stackunderflow(0);
735             rpnstack->s[stptr] = isinf(rpnstack->s[stptr]) ? 1.0 : 0.0;
736             break;
737         case OP_SQRT:
738             stackunderflow(0);
739             rpnstack->s[stptr] = sqrt(rpnstack->s[stptr]);
740             break;
741         case OP_SORT:
742             stackunderflow(0);
743             {
744                 int       spn = (int) rpnstack->s[stptr--];
745
746                 stackunderflow(spn - 1);
747                 qsort(rpnstack->s + stptr - spn + 1, spn, sizeof(double),
748                       rpn_compare_double);
749             }
750             break;
751         case OP_REV:
752             stackunderflow(0);
753             {
754                 int       spn = (int) rpnstack->s[stptr--];
755                 double   *p, *q;
756
757                 stackunderflow(spn - 1);
758
759                 p = rpnstack->s + stptr - spn + 1;
760                 q = rpnstack->s + stptr;
761                 while (p < q) {
762                     double    x = *q;
763
764                     *q-- = *p;
765                     *p++ = x;
766                 }
767             }
768             break;
769         case OP_TREND:
770         case OP_TRENDNAN:
771             stackunderflow(1);
772             if ((rpi < 2) || (rpnp[rpi - 2].op != OP_VARIABLE)) {
773                 rrd_set_error("malformed trend arguments");
774                 return -1;
775             } else {
776                 time_t    dur = (time_t) rpnstack->s[stptr];
777                 time_t    step = (time_t) rpnp[rpi - 2].step;
778
779                 if (output_idx > (int) ceil((float) dur / (float) step)) {
780                     int       ignorenan = (rpnp[rpi].op == OP_TREND);
781                     double    accum = 0.0;
782                     int       i = 0;
783                     int       count = 0;
784
785                     do {
786                         double    val =
787                             rpnp[rpi - 2].data[rpnp[rpi - 2].ds_cnt * i--];
788                         if (ignorenan || !isnan(val)) {
789                             accum += val;
790                             ++count;
791                         }
792
793                         dur -= step;
794                     } while (dur > 0);
795
796                     rpnstack->s[--stptr] =
797                         (count == 0) ? DNAN : (accum / count);
798                 } else
799                     rpnstack->s[--stptr] = DNAN;
800             }
801             break;
802         case OP_AVG:
803             stackunderflow(0);
804             {
805                 int       i = (int) rpnstack->s[stptr--];
806                 double    sum = 0;
807                 int       count = 0;
808
809                 stackunderflow(i - 1);
810                 while (i > 0) {
811                     double    val = rpnstack->s[stptr--];
812
813                     i--;
814                     if (isnan(val)) {
815                         continue;
816                     }
817                     count++;
818                     sum += val;
819                 }
820                 /* now push the result back on stack */
821                 if (count > 0) {
822                     rpnstack->s[++stptr] = sum / count;
823                 } else {
824                     rpnstack->s[++stptr] = DNAN;
825                 }
826             }
827             break;
828         case OP_ABS:
829             stackunderflow(0);
830             rpnstack->s[stptr] = fabs(rpnstack->s[stptr]);
831             break;
832         case OP_END:
833             break;
834         }
835 #undef stackunderflow
836     }
837     if (stptr != 0) {
838         rrd_set_error("RPN final stack size != 1");
839         return -1;
840     }
841
842     output[output_idx] = rpnstack->s[0];
843     return 0;
844 }
845
846 /* figure out what the local timezone offset for any point in
847    time was. Return it in seconds */
848 int tzoffset(
849     time_t now)
850 {
851     int       gm_sec, gm_min, gm_hour, gm_yday, gm_year,
852         l_sec, l_min, l_hour, l_yday, l_year;
853     struct tm t;
854     int       off;
855
856     gmtime_r(&now, &t);
857     gm_sec = t.tm_sec;
858     gm_min = t.tm_min;
859     gm_hour = t.tm_hour;
860     gm_yday = t.tm_yday;
861     gm_year = t.tm_year;
862     localtime_r(&now, &t);
863     l_sec = t.tm_sec;
864     l_min = t.tm_min;
865     l_hour = t.tm_hour;
866     l_yday = t.tm_yday;
867     l_year = t.tm_year;
868     off =
869         (l_sec - gm_sec) + (l_min - gm_min) * 60 + (l_hour - gm_hour) * 3600;
870     if (l_yday > gm_yday || l_year > gm_year) {
871         off += 24 * 3600;
872     } else if (l_yday < gm_yday || l_year < gm_year) {
873         off -= 24 * 3600;
874     }
875     return off;
876 }