##==== HEADER ========================================================================
## 
## Purpose:
## This is a script to plot temperatur data from British Columbia
## Ministry of Forest, Land and Natural Resources Operation
##
## Modification History:
## code generation -- January / Feburary 2013, Hasi
##
## Autors: 
## Hasi (Andreas Hasler), andreas_hasler@gmx.ch, BC Forest Dept.
## 
## Description:		Plots of running annual means are generated for each field site.
##
## Dependencies:		Ttools.R (own toolbox for temperature timeseries treatment,
## 				(contained in STATws.R workspace)
##
## I/O, variables and units:
## input:			STATws.RData workspace (generated by procedure "stat_TTSMAT.R")
##				contains toolbox and different aggregates of time series
##				for details see header of "stat_TTSMAT.R"
##		
## output:			plot of yearly running mean
##
## units:			t is in inported as "mm-dd-yyyy HH:MM:SS AM/PM"
##				t is internaly in R POSIXct
##				temperature is in ?C
##						
##======================================================================================

## clear current workspace to avoid env. dependency
rm(list=ls())

##======================================================================================
##   control variables
##======================================================================================

## time limits (x-axis) for plotting ("yyyy-mm-dd")
pl_beg <- "2009-01-01"
pl_end <- "2013-03-01"

## set plot mode: "png","pdf" or "scr" (for screen)
pl <- "png"

## set RMATexist=TRUE to take existing RMAT data frame,
## otherwise calculates RMAT new from DMT
RMATexist <- TRUE

##======================================================================================
##   preparation
##======================================================================================

## load workspace with all data and tools 
if (!exists("STAWS")) load("RData/STATws.RData")

## get list of sites:
sites <- levels(factor(slist$site))
lsl <- length(sites) ## length of short list

## colour setting
c.palette<-colorRampPalette(c("orange","red","blue","black"),space="Lab")

## convert plot range to posix
pl_beg <- posix(pl_beg)
pl_end <- posix(pl_end)

lwd <-2

##======================================================================================
##======================================================================================
##======================================================================================
##   main loop through sites

for (k in 1:lsl){	
	## get site name	
	site <- sites[k]
	sitn <- (slist$sitename[site==slist$site])[1]

	## geting dataframe of respective sensor assigned to "d"
	if (RMATexist) {  
	  yrm <- get(paste("RMAT_",site,sep=""))
	  d <- yrm$d
	} else {
	  d <- ts.df.runmean(get("DMT_"&site),win=365,qlim = 0.99,end=TRUE)
	}  
	l <- dim(d)[2]

##======================================================================================
##   ploting
##======================================================================================
	## define grafic device size
 	plfn <- paste("plots/RMAT_",site,sep='')
	pldev(x=8,y=4.5,pld=pl,plfn=plfn)

	## make rows and cols on sheet c(rows,cols):
	par(mfrow=c(1,1),xpd=FALSE)

	## ploting variables
	ylim <- c(-4,4)
	xlim <- as.POSIXct(c(pl_beg,pl_end))
	ylab <- "RMAT (°C)"
	xlab <- "time"

	## get order of temperature
	tm <- c(NA,colMeans(d[2:l],na.rm=TRUE))
	ot <- order(-tm)

	##plot settings:
	colr <- c.palette(l)
	lty <- rep(c(1,2,4),times=(ceiling(l/3)))

	## plot first line
	plot(d$t,d[,ot[1]],type="l",xlim=xlim,ylim=ylim,ylab=ylab,xlab=xlab,col=colr[1],lty=lty[1],main=sitn,lwd=lwd)

	##variable names
	vns <- names(d)[ot[1]]
 
	##   loop through the other variables
	for (j in 2:(l-1)){
		## plot other vars
		lines(d$t,d[,ot[j]],col=colr[j],lty=lty[j],lwd=lwd)
		vns <- c(vns,names(d)[ot[j]])
	}
		print(vns)
		print(names(d))

	abline(h=c(-4,-2,0,2,4),lty=2)
	abline(h=0,lty=1)
	legend("topleft",vns,col=colr[1:(l-1)],bg="white",lwd=lwd*0.8, text.col=colr[1:(l-1)],lty=lty[1:(l-1)],cex=0.7)	

	## close ploting dev for png or pdf
	if (pl!="scr") dev.off()
}#   END of main loop through the sites
##======================================================================================
##======================================================================================
##   end
##======================================================================================
