prep for 1.2rc3 release
[rrdtool.git] / src / rrd_first.c
1 /*****************************************************************************
2  * RRDtool 1.2rc3  Copyright by Tobi Oetiker, 1997-2005
3  *****************************************************************************
4  * rrd_first Return
5  *****************************************************************************
6  * Initial version by Burton Strauss, ntopSupport.com - 3/2005
7  *****************************************************************************/
8
9 #include "rrd_tool.h"
10
11
12 time_t
13 rrd_first(int argc, char **argv)
14 {
15     int target_rraindex=0;
16     char *endptr;
17
18     while (1){
19         static struct option long_options[] =
20         {
21             {"rraindex", required_argument, 0, 129},
22             {0,0,0,0}
23         };
24         int option_index = 0;
25         int opt;
26         opt = getopt_long(argc, argv, "", long_options, &option_index);
27
28         if(opt == EOF)
29             break;
30
31         switch(opt) {
32           case 129:
33             target_rraindex=strtol(optarg,&endptr,0);
34             if(target_rraindex < 0) {
35                 rrd_set_error("invalid rraindex number");
36                 return(-1);
37             }
38             break;
39           default:
40             rrd_set_error("usage rrdtool %s [--rraindex number] file.rrd", argv[0]);
41             return(-1);
42         }
43     }
44
45     if(optind >= argc){
46         rrd_set_error("not enough arguments");
47         return -1;       
48     }     
49
50     return(rrd_first_r(argv[optind], target_rraindex));
51 }
52
53
54 time_t
55 rrd_first_r(const char *filename, const int rraindex)
56 {
57     long rra_start,
58          timer;
59     time_t then;
60     FILE *in_file;
61     rrd_t rrd;
62
63     if(rrd_open(filename,&in_file,&rrd, RRD_READONLY)==-1){
64         rrd_set_error("could not open RRD");
65         return(-1);
66     }
67
68     if((rraindex < 0) || (rraindex >= (int)rrd.stat_head->rra_cnt)) {
69         rrd_set_error("invalid rraindex number");
70         return(-1);
71     }
72
73     rra_start = ftell(in_file);    
74     fseek(in_file,
75           (rra_start +
76            (rrd.rra_ptr[rraindex].cur_row+1) *
77            rrd.stat_head->ds_cnt *
78            sizeof(rrd_value_t)),
79           SEEK_SET);
80     timer = - (rrd.rra_def[rraindex].row_cnt-1);
81     if (rrd.rra_ptr[rraindex].cur_row + 1 > rrd.rra_def[rraindex].row_cnt) {
82       fseek(in_file,rra_start,SEEK_SET);
83     }
84     then = (rrd.live_head->last_up -
85             rrd.live_head->last_up %
86             (rrd.rra_def[rraindex].pdp_cnt*rrd.stat_head->pdp_step)) +
87            (timer * 
88             rrd.rra_def[rraindex].pdp_cnt*rrd.stat_head->pdp_step);
89
90     rrd_free(&rrd);
91     fclose(in_file);
92     return(then);
93 }
94
95
96
97