#!/bin/env Rscript 

#' grabs version number, release dates and size of the R distribution
#' for each archive on CRAN
releaseDate <- function( 
    urls = sprintf( "http://cran.r-project.org/src/base/R-%d/", 0:2 ), 
    pattern = "" ){
    
    rx <- '^.*(R-.*?gz).*?right">([^\\s>]*?)\\s.*?right">\\s?([^>]*?)<.*$'
    data <- do.call( rbind, lapply( urls, function( url ){
        txt <- grep( rx, readLines( url ), value = TRUE, perl = TRUE )
        parts <- sub( rx, "\\1--\\2--\\3", txt, perl = TRUE )
        do.call( rbind, strsplit( parts, "--" ) )
    } ) )
    colnames( data ) <- c("version", "date", "size")
    data <- data[ ! grepl('recommended', data[,"version"] ),  ] 
    
    data <- within( as.data.frame( data ), {
        version <- sub( "^R-(.*?)\\.t.*$", "\\1", version )
        date    <- as.Date( date, format = "%d-%b-%Y" )
        size    <- local({
            K <- grepl( "K$", size)
            x <- numeric( length( size ) )
            x[ K ]  <- as.numeric(sub( "K", "", size[K] )) / 1024
            x[ !K ] <- as.numeric(sub( "M", "", size[!K] ))
            x
        } )
    } )
    data[ grepl( pattern, data$version ), ]
}
releases <- releaseDate( pattern = "0$" )

#' helper function to draw R releases on the top axis
axis.releases <- function(side, ...) {
    switch(side,
        top = {
            dates <- releases$date
            version <- releases$version
            panel.axis(side = side, outside = TRUE,
                       at = dates, labels = version, rot = 45)
        },
        axis.default(side = side, ...) )
}