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