#' @title Temperature and precipitation data 
#' 
#' @description Extract and combine temperature and precipitation data  
#' 
#' @param \ldots either a list or sequence of data matrices obtained from `weatherStats`
#'
#' @return a data frame 
#'
#' @author Peter Hoff
#'
#' @examples 
#' W<-tpdata(RDU,SEA) 
#'  
#' colnames(W) 
#' dim(W) 
#' 
#' tpplot(W) 
#'
#' @export
tpdata <- function(...)
{
  WDAT<-list(...)  

  TP<-NULL 
  for (k in 1:length(WDAT)) {  

    W<-WDAT[[k]]      

    ## min, avg and max temperature  
    if ( !any(colnames(W)=="TAVG") ) { W$TAVG<-NA }     
    temp<-W[, c("TMIN","TAVG","TMAX")]  
    if ( any(is.na(temp[, 2])) ) { 
      i <- which(is.na(temp[, 2]))
      temp[i, 2] <- .5 * (temp[i, 1] + temp[i, 3]) 
    }

    ## precipitation
    prcp<-W[, c("PRCP")]  

    ## non-missing data frame
    tpdata<-data.frame(STATION = W$STATION, DATE = W$DATE,
                       TMIN = temp$TMIN, TAVG = temp$TAVG, TMAX = temp$TMAX,
                       PRCP = prcp)  
    i <- apply(tpdata, 1, function (x) { !any(is.na(x)) } ) 
    tpdata <- tpdata[i, ] 
  
    TP <- rbind(TP ,tpdata)
  } 

  TP <- TP[order(TP$DATE), ] 
  TP <- TP[order(TP$STATION), ] 

TP
}

