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