#' @title Temperature and precipitation plot 
#' 
#' @description Plot temperature and precipitation data  
#' 
#' @param TPDATA A data frame with temperature and precipitation data 
#' @param units "F" or "C" 
#' @param rc make multiple plots along columns ("col") or rows ("row") 
#' 
#' @return Invisibly returns \code{NULL}.
#' 
#' @author Peter Hoff
#' 
#' @examples 
#' W<-tpdata(RDU,SEA) 
#'  
#' colnames(W) 
#' dim(W) 
#' 
#' tpplot(W) 
#' 
#' @export
tpplot<-function(TPDATA,units="F",rc="col"){ 

  ## rain colors
  blue<-pmin(TPDATA$PRCP/20,1) 
  rcols<-rgb(1-blue,1-blue,1,alpha=1) 

  ## temp colors 
  tgr<-(TPDATA$TAVG+12)/(38+12) 
  tgr<-pmax(0,pmin(1,tgr))  
  tcols<-rgb(tgr,0,1-tgr,alpha=1) 

  ## stations
  stations<-unique(TPDATA$STATION) 

  ## convert to F  
  ylab<-expression(paste("temperature(",degree*C,")"))
  if(units=="F"){ 
    TPDATA[,3:5]<- 32 + TPDATA[,3:5] * 1.8 
    ylab<-expression(paste("temperature(",degree*F,")"))
  } 
  ylab<-c(ylab,rep("",length(stations)-1)) 
  yaxt<-c("s",rep("n",length(stations)-1)) 

  ## save old value for `par` and revert to it on exit
  oldpar <- par(no.readonly = TRUE) 
  on.exit(par(oldpar)) 

  ## plot data for each station 
  if(rc=="row") { par(mfrow=c(1,length(stations)),mar=c(3,3,1.25,1),mgp=c(1.75,.75,0),
                  oma=c(0,0,0,0)) } 

  if(rc=="col"){  par(mfrow=c(length(stations),1),mar=c(3,3,1.25,1),mgp=c(1.75,.75,0),
                  oma=c(0,0,0,0)) } 

  for(i in 1:length(stations)){  
    istat<-which(TPDATA$STATION==stations[i])
    TPS<-TPDATA[istat,]

    plot(c(-3,nrow(TPS)+3),range(TPDATA[,c("TMIN","TMAX")] ),type="n",
    xlab=TPS$STATION[1],xaxt="n",ylab=ylab[i],yaxt=yaxt[i],xaxs="i") 

    ## boundaries 
    month<-as.numeric(substr(TPS$DATE,6,7) )    
    year<-as.numeric(substr(TPS$DATE,1,4) )   
    
    mswitch<-which(diff(month)!=0)
    yswitch<-which(diff(year)!=0) 
    switch<-sort(unique(c(mswitch,yswitch))) 

    ## boundaries 
    abline(v=mswitch,col="gray")  
    abline(v=yswitch,col="gray",lwd=3)  

    ## month labels  
    mloc<-(c(0,mswitch)+c(mswitch,nrow(TPS)))/2
    mlab<- c("J","F","M","A","M","J",
	     "J","A","S","O","N","D")[month[round(mloc)]]
    axis(1, (c(0,mswitch)+c(mswitch,nrow(TPS)))/2,labels=mlab)

    ## temperature
    segments(1:nrow(TPS),TPS$TMAX,1:nrow(TPS),TPS$TMIN,col=tcols[istat]) 
    points(1:nrow(TPS),TPS$TAVG,col=tcols[istat],cex=.5,pch=16) 

    ## rain
    points(1:nrow(TPS),rep(min(TPDATA[,3:5])-(9/5)^(units=="F"),nrow(TPS)),
	    col=rcols[istat], pch=15 ) 
    abline(h=min(TPDATA[,3:5])-.25*(9/5)^(units=="F")) 

    ## year and station  
    jans<-mloc[ month[round(mloc)]==1  ]
    if(length(jans)>0){text(jans,max(TPDATA[,3:5]),year[jans],adj=.5)} else 
                      { text( 15,max(TPDATA[,3:5]),year[1],adj=.5) } 

  }

}





