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