##Terminate the process 'MRS.exe' if the program was not properly quitted in the previous run.
tskls<-system("tasklist",intern=TRUE)
pid<-NULL
for (i in 1:length(tskls)) {
	if (substr(tskls[i],1,7)=="MRS.exe") {pid<-as.numeric(substr(tskls[i],26,34))}
	}
if (length(pid)>0){
	system(sprintf('taskkill /pid %d /f',pid),intern=TRUE)
}
##Function to install the required packages if haven't been installed
install.or.not <- function(mypkg){
	x<-is.element(mypkg, installed.packages()[,1]) 
	if(x==FALSE) {install.packages(mypkg)}
}
#Install required libraries
install.or.not("RGtk2")
install.or.not("tcltk")
install.or.not("gWidgets")
install.or.not("zoo")
install.or.not("cairoDevice")
install.or.not("grDevices")
install.or.not("graphics")
library(tcltk)
library(RGtk2)
library(gWidgets)
library(zoo)
library(cairoDevice)
library(grDevices)
library(graphics)
##Main window
main_window<-gtkWindow(show = TRUE)
main_window["title"] <- "Multisite Rainfall Simulator"
main_window$setDefaultSize(1500,1500)
#Menubar
menubar<-gtkMenuBar()
file_menu<-gtkMenu()
file_item<-gtkMenuItemNewWithMnemonic(label="File")
file_item$setSubmenu(file_menu)
menubar$append(file_item)
open_item<-gtkMenuItemNewWithMnemonic("Open Script")
gSignalConnect(open_item,"activate", function(item) {
	file.show(tk_choose.files(default="",caption = "Open script",
	multi = FALSE,filters = matrix(c("R files",".r"),1,2,byrow = TRUE)))
})					
file_menu$append(open_item)
quit_item<-gtkMenuItemNewWithMnemonic("Quit")
gSignalConnect(quit_item,"activate",function(item){main_window$destroy()})
file_menu$append(quit_item)
help_menu<-gtkMenu()
help_item<-gtkMenuItemNewWithMnemonic(label="Help")
help_item$setSubmenu(help_menu)
menubar$append(help_item)
userGuide_item<-gtkMenuItemNewWithMnemonic("User Guide")
#Open Help PDF
help_menu$append(userGuide_item)
gSignalConnect(userGuide_item,"activate",function(item){
	shell.exec(file.path(getwd(), "Multisite Rainfall Simulator Help.pdf"))
})
vbox<-gtkVBox()
main_window$add(vbox)
vbox$packStart(menubar,FALSE,FALSE)
#Add notebook
notebook<-gtkNotebook()
notebook['tab-pos']<-"left"
vbox$packStart(notebook,TRUE,TRUE)
##Input rainfall page
inputRfTable<-gtkTable(rows=3,columns=1,homogeneous=FALSE)
notebook$appendPage(inputRfTable,gtkLabel("Input Rainfall"))

openButton<-gtkButtonNewWithLabel(" Open ")
inputRfPlotButton<-gtkButton(" Plot ")
inputRfPlotSaveButton<-gtkButtonNewWithLabel(" Save Plot ")
gSignalConnect(openButton,"clicked",function(openButton,event,data){
	File<-tk_choose.files(default="",caption = "Select input rainfall data file",
	multi = FALSE,
	filters =matrix(c("Text",".txt","R data", ".data","Dat",".dat"),3,2,byrow = TRUE))
})		
SelectRfFileOptionFrame<-gtkFrame("Select Input Rainfall Data File")
SelectRfFileOptionLabels<-c("Use example rainfall data","Use your own rainfall data")
SelectRfFileOptionRadioGp<-list() 
SelectRfFileOptionRadioGp [[SelectRfFileOptionLabels[1]]]<-gtkRadioButton(label=SelectRfFileOptionLabels[1])
for(label in SelectRfFileOptionLabels [-1])
SelectRfFileOptionRadioGp[[label]]<-gtkRadioButton(SelectRfFileOptionRadioGp,label=label)
SelectRfFileOptionHBox<-gtkHBox(homogeneous = NULL,spacing = NULL,show = TRUE)
SelectRfFileOptionFrame$add(SelectRfFileOptionHBox)
sapply(SelectRfFileOptionRadioGp,gtkBoxPackStart,object=SelectRfFileOptionHBox)
SelectRfFileOptionHBox[[1]]$setActive(TRUE) #Set using example rainfall data as initial option
sapply(SelectRfFileOptionRadioGp,'[',"active")
sapply(SelectRfFileOptionRadioGp,gSignalConnect,"toggled",function(button,data){
	if(button['active']){
		#message("",button$getLabel(),"\n")
		list_data_fi=readLines("data.dat")
		selRfFileOpt<-button$getLabel()
		if (selRfFileOpt=="Use example rainfall data"){
			list_data_fi[8]<-"rain.dat"
			writeLines(list_data_fi,"data.dat")
		}
		else if (selRfFileOpt=="Use your own rainfall data"){
			selRfFile<-tk_choose.files(default="",caption = "Select input rainfall data file",
						multi = FALSE,filters =matrix(c("Text",".txt","R data", ".data","Dat",".dat"),3,2,byrow = TRUE))
			if(length(selRfFile)==0){
				errMessage<-"The input rainfall data file was not selected. "
				errMesgFun(errMessage)
				selRfFile<-tk_choose.files(default="",caption = "Select input rainfall data file",
						multi = FALSE,filters =matrix(c("Text",".txt","R data", ".data","Dat",".dat"),3,2,byrow = TRUE))
			}
			else if (selRfFile!=""){
				list_data_fi[8]<-selRfFile
				writeLines(list_data_fi,"data.dat")
			}
		}
	}
})	
inputRfTable$attach(SelectRfFileOptionFrame,left.attach=0,1,
	top.attach=0,1,xoptions=c("expand","fill"),yoptions="")
inputRfPlotFrame<-gtkFrame("Plot Input Rainfall Data")	
inputRfTable$attach(inputRfPlotFrame,left.attach=0,1,
	top.attach=1,2,xoptions=c("expand","fill"),yoptions="")
inputRfPlotTable<-gtkTable(rows=2,columns=3,homogeneous=FALSE)
inputRfPlotFrame$add(inputRfPlotTable)
inputRfPlotTable$attach(inputRfPlotButton,left.attach=0,1,top.attach=0,1,
	xoptions=c("shrink","fill"),yoptions=c("shrink","fill"))
inputRfPlotTable$attach(inputRfPlotSaveButton,left.attach=2,3,top.attach=0,1,
	xoptions=c("shrink","fill"),yoptions=c("shrink","fill"))
#Add graphic device to input rainfall page
inputRfPlotDevice<-gtkDrawingArea()
inputRfPlotDevice$setSizeRequest(600,800)
asCairoDevice(inputRfPlotDevice)
inputRfPlotTable$attach(inputRfPlotDevice,left.attach=1,2,top.attach=2,3,
	xoptions=c("shrink","fill"),yoptions="")
#Input rainfall plot function
inputRfPlotFunction<-function(fontsize){
	list_data_fi=readLines("data.dat")
	inputRfFile<-list_data_fi[8]
	inputRf<-read.table(inputRfFile,skip=3)
	#Check the validity of the first three columns yyyy,mon,day
	if (sum(inputRf[,1:3]%%1)>0 |inputRf[,2]<1 | inputRf[,2]>12 | inputRf[,3]<1 | inputRf[,3]>31 | !is.numeric(as.matrix(inputRf))){
		errMessage<-"Invalid format for input rainfall data file. "
			errMesgFun(errMessage)
	}
	else {
		rainfall<-apply(inputRf[1:nrow(inputRf),4:ncol(inputRf)],1,mean)
		x.Date<-as.Date(ISOdate(inputRf[1,1],inputRf[1,2],inputRf[1,3]))+0:(nrow(inputRf)-1)  
		rainfall.z<-zoo(rainfall,x.Date)
		par(pty="s")
		plot(rainfall.z,xlab="Date",ylab="mm",
			main="Monthly observed rainfall amount",
			cex.main=fontsize,cex.lab=fontsize, cex.axis=fontsize,cex=fontsize)
    }
}		
gSignalConnect(inputRfPlotButton,"clicked",function(inputRfPlotButton,event,data){
	if (length(dev.list()>1)) dev.off()
    #Add graphic device to input rainfall page
	inputRfPlotDevice<-gtkDrawingArea()
	inputRfPlotDevice$setSizeRequest(600,800)
	asCairoDevice(inputRfPlotDevice)
	inputRfPlotTable$attach(inputRfPlotDevice,left.attach=1,2,top.attach=2,3,
		xoptions=c("shrink","fill"),yoptions="")
	fontsize<-1.5
	inputRfPlotFunction(fontsize)
})
#Function to save figures
savePlotFileAs<-function(){plotFile<-tclvalue(tkgetSaveFile
	(initialfile="*.pdf",defaultextension = c(".pdf",".png",".bmp",".tif",
	".tiff",".jpg",".jpeg",".eps","emf"),filetypes=" {{Pdf files} {.pdf}}
	{{Png files} {.png}} {{Bmp files} {.bmp}} {{TIFF files} {.tif .tiff}}
	{{Jpeg files} {.jpg .jpeg}} {{Postscript files} {.eps}} {{Metafiles}
	{.emf}}"))
	return(plotFile)
}
#Function to save tables
saveGridFileAs<-function(){gridFile<-tclvalue(tkgetSaveFile(
	initialfile="*.txt",defaultextension = c(".txt",".dat",".out"),
	filetypes=" {{Text files} {.txt}} {{DAT files} {.dat}} {{OUT files}
	{.out}}"))
	return(gridFile)
}
getExt<-function(path)
	{
	 parts<-unlist(strsplit(path, "\\."))
     extention<-parts[length(parts)]
	 return(extention)
	}	
filenameExt<-function(path)
	{
	 parts<-unlist(strsplit(path, "\\/"))
     filename<-parts[length(parts)]
	 return(filename)
	}
#Save input rainfall plot 
gSignalConnect(inputRfPlotSaveButton, "clicked", function(
	inputRfPlotSaveButton,event,data){
		plotFile<-savePlotFileAs()
		if (plotFile!=""){
			dev.new()
			fontsize<-1.5
			inputRfPlotFunction(fontsize)
			savePlot(filename=plotFile,type = getExt(plotFile),
				device = dev.cur(),restoreConsole = TRUE)
			dev.off()
		}
	}
)				
##Data parameters page 
dataParameterFrame<-gtkFrame("Data Parameters")
notebook$appendPage(dataParameterFrame,gtkLabel("Data Parameters"))
dataParameterTable<-gtkTable(rows=15,columns=4,homogeneous=FALSE)
dataParameterFrame$add(dataParameterTable)
previousLagFrame<-gtkFrame("number of previous lags for nLon")
previousLagTable<-gtkTable(rows=3,columns=10,homogeneous=FALSE)
previousLagFrame$add(previousLagTable)
nYrLabel<-gtkLabel("number of years (ob.): ")
yrStartLabel<-gtkLabel("start year (ob.): ")
bandLabel<-gtkLabel("band: ")
gtkWidgetSetTooltipText(bandLabel,
	'The width of moving window equals to band*2+1.')
nStationLabel<-gtkLabel("number of stations: ")
nSimLabel<-gtkLabel("number of simulations: ")
nLonLabel<-gtkLabel("nLon: ")
gtkWidgetSetTooltipText(nLonLabel,'number of time periods for previous time lags (in days) for long term dependence')
lagLabel<-gtkLabel("lag: ")
nYrSimLabel<-gtkLabel("number of years (sim.): ")
yrStartSimLabel<-gtkLabel("start year (sim.): ")
localLabel<-gtkLabel("local: ")
gtkWidgetSetTooltipText(localLabel,'0 for no local wetness considered
1 for addition of a variable in the conditioning vector
2 for formation of subset from the data')
inclSpatialCheckButtonLabel<-gtkLabel("include spatial dependence matrix ")
rfOccOnlyCheckButtonLabel<-gtkLabel("simulate rainfall occurrence only ")
previousLagFromLabel<-gtkLabel("from: ")
previousLagToLabel<-gtkLabel("to: ")
saveParaButton<-gtkButton(" Save Data Parameters ")
runButton<-gtkButton(" Run ")
nYrSpin<-gtkSpinButtonNew()
yrStartSpin<-gtkSpinButtonNew()
bandSpin<-gtkSpinButtonNew()
nStationSpin<-gtkSpinButtonNew()
nYrSimSpin<-gtkSpinButtonNew()
nLonSpin<-gtkSpinButtonNew()
lagSpin<-gtkSpinButtonNew()
nSimSpin<-gtkSpinButtonNew()
yrStartSimSpin<-gtkSpinButtonNew()
localSpin<-gtkSpinButtonNew()
genSpatialCheckButton<-gtkCheckButton()
genSpatialCheckButton$setActive(TRUE)
inclSpatialCheckButton<-gtkCheckButton()
inclSpatialCheckButton$setActive(TRUE)
rfOccOnlyCheckButton<-gtkCheckButton()
rfOccOnlyCheckButton$setActive(FALSE)
previousLagFromSpin<-list()
previousLagToSpin<-list()
#max(nLon)=3
for (i in 1:3)
	{
	 previousLagFromSpin[[i]]<-gtkSpinButtonNew()
	 previousLagToSpin[[i]]<-gtkSpinButtonNew() 
    }	
#Function to set spin button
spinSetFun<-function(spin,mini,maxi,initial,pg){	 	 
	gtkSpinButtonSetNumeric(spin,TRUE)
	gtkSpinButtonSetSnapToTicks(spin,TRUE)
	gtkSpinButtonSetWrap(spin,TRUE)
	gtkSpinButtonSetDigits(spin,0)
	gtkSpinButtonSetRange(spin,mini,maxi)
	#gtkSpinButtonSetIncrements(object, step, page)
	gtkSpinButtonSetIncrements(spin,1,pg)
	gtkSpinButtonSetValue(spin,initial)
}	
#Attach widgets to model parameters page
dataParameterTable$attach(nYrLabel,left.attach=0,1,top.attach=0,1,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(yrStartLabel,left.attach=0,1,top.attach=1,2,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(nStationLabel,left.attach=0,1,top.attach=2,3,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(bandLabel,left.attach=0,1,top.attach=3,4,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(lagLabel,left.attach=0,1,top.attach=4,5,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(localLabel,left.attach=0,1,top.attach=5,6,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(nLonLabel,left.attach=0,1,top.attach=6,7,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(nYrSimLabel,left.attach=2,3,top.attach=0,1,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(yrStartSimLabel,left.attach=2,3,top.attach=1,2,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(nSimLabel,left.attach=2,3,top.attach=2,3,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(rfOccOnlyCheckButtonLabel,left.attach=2,3,
	top.attach=3,4,xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(inclSpatialCheckButtonLabel,left.attach=2,3,
	top.attach=4,5,xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(nYrSpin,left.attach=1,2,top.attach=0,1,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(yrStartSpin,left.attach=1,2,top.attach=1,2,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(nStationSpin,left.attach=1,2,top.attach=2,3,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(bandSpin,left.attach=1,2,top.attach=3,4,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(lagSpin,left.attach=1,2,top.attach=4,5,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(localSpin,left.attach=1,2,top.attach=5,6,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(nLonSpin,left.attach=1,2,top.attach=6,7,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(nYrSimSpin,left.attach=3,4,top.attach=0,1,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(yrStartSimSpin,left.attach=3,4,top.attach=1,2,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(nSimSpin,left.attach=3,4,top.attach=2,3,
	xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(rfOccOnlyCheckButton,left.attach=3,4,
	top.attach=3,4,xoptions=c("expand","fill"),yoptions="")
dataParameterTable$attach(inclSpatialCheckButton,left.attach=3,4,
	top.attach=4,5,xoptions=c("expand","fill"),yoptions="")
#Previous time lags frame
dataParameterTable$attach(previousLagFrame,left.attach=0,4,
	top.attach=7,10,xoptions=c("expand","fill"),yoptions="")
previousLagTable$attach(previousLagFromLabel,left.attach=0,1,
	top.attach=0,1,xoptions=c("shrink","fill"),yoptions="")
previousLagTable$attach(previousLagToLabel,left.attach=0,1,
	top.attach=1,2,xoptions=c("shrink","fill"),yoptions="")
previousLagTable$attach(previousLagFromSpin[[1]],left.attach=1,2,
	top.attach=0,1,xoptions=c("shrink","fill"),yoptions="")
previousLagTable$attach(previousLagToSpin[[1]],left.attach=1,2,
	top.attach=1,2,xoptions=c("shrink","fill"),yoptions="")
#Create dummy progress bar
progressBar<-gtkProgressBar()
progressBar$setText("Estimate Multisite Rainfall")
#All data parameters are stored in file 'data.dat'
para_file="data.dat"
#Use the parameter in the file 'data.dat' as the initial value in RGUI
#if the file exists
if (file.exists(para_file)){
	#parameters are written in tab delimited format
	parameters<-read.table(para_file, header =FALSE, sep = "\t", nrows =1,skip = 2,strip.white = FALSE)
	prev_lags<-read.table(para_file, header =FALSE, sep = "\t", nrows =2,skip = 4,strip.white = FALSE)
	rf_input_file<-read.table(para_file, header =FALSE, sep = "\t", nrows =1,skip = 7,strip.white = FALSE)
	rf_output_file<-read.table(para_file, header =FALSE, sep = "\t", nrows =1,skip = 9,strip.white = FALSE)
	corr_occ_file<-read.table(para_file, header =FALSE, sep = "\t", nrows =1,skip = 11,strip.white = FALSE)
	corr_amt_file<-read.table(para_file, header =FALSE, sep = "\t", nrows =1,skip = 13,strip.white = FALSE)
	dist_file<-read.table(para_file, header =FALSE, sep = "\t", nrows =1,skip = 15,strip.white = FALSE)
	
	nYr<-as.numeric(parameters[1])
	yrStart<-as.numeric(parameters[2])
	band<-as.numeric(parameters[3])
	nStation<-as.numeric(parameters[4])	  
	nSim<-as.numeric(parameters[5])
	nLon<-as.numeric(parameters[6])
	lag<-as.numeric(parameters[7])
	nYrSim<-as.numeric(parameters[8])
	yrStartSim<-as.numeric(parameters[9])
	amt<-as.numeric(parameters[10])
	local<-as.numeric(parameters[11])
	genSpatial<-as.numeric(parameters[12])
	inclSpatial<-as.numeric(parameters[13])
	#Set minimum, maximum and initial values for spin buttons
	spinSetFun(spin=nYrSpin,mini=5,maxi=180,initial=nYr,pg=5)
	spinSetFun(spin=yrStartSpin,mini=1,maxi=2100,initial=yrStart,pg=5)
	spinSetFun(spin=nStationSpin,mini=1,maxi=180,initial=nStation,pg=5)
	spinSetFun(spin=bandSpin,mini=1,maxi=21,initial=band,pg=5)
	spinSetFun(spin=lagSpin,mini=0,maxi=1,initial=lag,pg=1)
	spinSetFun(spin=nLonSpin,mini=1,maxi=3,initial=nLon,pg=1)#max(nLon)=3
	spinSetFun(spin=nYrSimSpin,mini=1,maxi=180,initial=nYrSim,pg=5) #nYrSim < nYr
	spinSetFun(spin=yrStartSimSpin,mini=1,maxi=2100,initial=yrStartSim,pg=5)
	spinSetFun(spin=nSimSpin,mini=1,maxi=100,initial=nSim,pg=10)
	spinSetFun(spin=localSpin,mini=0,maxi=2,initial=local,pg=1)	
	spinSetFun(spin=previousLagFromSpin[[1]],mini=0,maxi=900,initial=prev_lags[1,1],pg=1)	
	spinSetFun(spin=previousLagToSpin[[1]],mini=0,maxi=900,initial=prev_lags[2,1],pg=1)	
	
	#Add additional spinbutton according to the number of pre_lags
	if (nLon==2){
		previousLagTable$attach(previousLagFromSpin[[2]],left.attach=2,3,
			top.attach=0,1,xoptions=c("shrink","fill"),yoptions="")
		previousLagTable$attach(previousLagToSpin[[2]],left.attach=2,3,
			top.attach=1,2,xoptions=c("shrink","fill"),yoptions="")
		spinSetFun(spin=previousLagFromSpin[[2]],mini=0,maxi=900,initial=prev_lags[1,2],pg=1)	
		spinSetFun(spin=previousLagToSpin[[2]],mini=0,maxi=900,initial=prev_lags[2,2],pg=1)	
	
	}
	else if (nLon==3){
		previousLagTable$attach(previousLagFromSpin[[2]],left.attach=2,3,
			top.attach=0,1,xoptions=c("shrink","fill"),yoptions="")
		previousLagTable$attach(previousLagToSpin[[2]],left.attach=2,3,
			top.attach=1,2,xoptions=c("shrink","fill"),yoptions="")
		previousLagTable$attach(previousLagFromSpin[[3]],left.attach=3,4,
			top.attach=0,1,xoptions=c("shrink","fill"),yoptions="")
		previousLagTable$attach(previousLagToSpin[[3]],left.attach=3,4,
			top.attach=1,2,xoptions=c("shrink","fill"),yoptions="")	
		spinSetFun(spin=previousLagFromSpin[[2]],mini=0,maxi=900,initial=prev_lags[1,2],pg=1)	
		spinSetFun(spin=previousLagToSpin[[2]],mini=0,maxi=900,initial=prev_lags[2,2],pg=1)
		spinSetFun(spin=previousLagFromSpin[[3]],mini=0,maxi=900,initial=prev_lags[1,3],pg=1)	
		spinSetFun(spin=previousLagToSpin[[3]],mini=0,maxi=900,initial=prev_lags[2,3],pg=1)	
	}
} else {
	#If the file 'data.dat' does not exist, then create it
	spinSetFun(spin=nYrSpin,mini=1,maxi=180,initial=15,pg=5)
	spinSetFun(spin=yrStartSpin,mini=1,maxi=2100,initial=1979,pg=5)
	spinSetFun(spin=nStationSpin,mini=1,maxi=180,initial=10,pg=5)
	spinSetFun(spin=bandSpin,mini=1,maxi=21,initial=15,pg=5)
	spinSetFun(spin=lagSpin,mini=0,maxi=1,initial=1,pg=1)
	spinSetFun(spin=nLonSpin,mini=1,maxi=3,initial=1,pg=1)#max(nLon)=3
	spinSetFun(spin=nYrSimSpin,mini=1,maxi=180,initial=15,pg=5) #nYrSim < nYr
	spinSetFun(spin=yrStartSimSpin,mini=1,maxi=2100,initial=1979,pg=5)
	spinSetFun(spin=nSimSpin,mini=1,maxi=100,initial=10,pg=10)
	spinSetFun(spin=localSpin,mini=0,maxi=2,initial=2,pg=1)
	spinSetFun(spin=previousLagFromSpin[[1]],mini=0,maxi=900,initial=2,pg=1)	
	spinSetFun(spin=previousLagToSpin[[1]],mini=0,maxi=900,initial=180,pg=1)
}
gSignalConnect(nLonSpin,"changed",function(nLonSpin,event,data){
		lapply(previousLagFromSpin, function(x) previousLagTable$remove(x))
		lapply(previousLagToSpin, function(x) previousLagTable$remove(x)) 	
		previousLagTable$attach(previousLagFromLabel,left.attach=0,1,
			top.attach=0,1,xoptions=c("shrink","fill"),yoptions="")
		previousLagTable$attach(previousLagToLabel,left.attach=0,1,
			top.attach=1,2,xoptions=c("shrink","fill"),yoptions="")
		nLon<-grab_int_value(nLonSpin)	   
		for (i in 1:nLon){
			spinSetFun(spin=previousLagFromSpin[[i]],mini=0,maxi=900,initial=prev_lags[1,i],pg=1)	
			spinSetFun(spin=previousLagToSpin[[i]],mini=0,maxi=900,initial=prev_lags[2,i],pg=1)		
			previousLagTable$attach(previousLagFromSpin[[i]],
				left.attach=i,i+1,top.attach=0,1,xoptions=c("shrink","fill"),
				yoptions="")
			previousLagTable$attach(previousLagToSpin[[i]],left.attach=i,i+1,
				top.attach=1,2,xoptions=c("shrink","fill"),yoptions="")	 
		}		 					
	})		

dataParameterTable$attach(saveParaButton,left.attach=0,1,
	top.attach=10,11,xoptions=c("expand","fill"),yoptions="",xpadding=0,
	ypadding=10)	
dataParameterTable$attach(runButton,left.attach=3,4,
	top.attach=10,11,xoptions=c("expand","fill"),yoptions="",xpadding=0,
	ypadding=10)
dataParameterTable$attach(progressBar,left.attach=0,4,top.attach=12,13,
	xoptions=c("expand","fill"),yoptions="",xpadding=5, ypadding=10)
notRespondingLabel<-gtkLabelNew("")
##Function to retrieve the spin button value
grab_int_value<-function(a_spinner,user_data){
   return(a_spinner$getValueAsInt())
}
##Function to show error message
errMesgFun<-function(errMessage){
	errWindow<-gtkWindow(show=FALSE)
	errWindow$setDefaultSize(500,50)
	errWindow["title"] <- "Error Message"
	errLabel<-gtkLabel(errMessage)		 
	errLabel$setLineWrap(TRUE)
	errLabel$setWidthChars(100)
	errWindow$add(errLabel)
	errWindow$show()
}
#Function to plot replicates
replPlotFun<-function(nSim,yrStartSim,nYrSim,amt,replOptionSel,fontsize){
	for (sim.index in 1:nSim){
		if(length(replOptionSel$getSelectedRows()$retval)==1){
			if (replOptionSel$getSelectedRows()$retval[[1]]$getIndices()==(sim.index-1)){
				nLine<-ISOdate(yrStartSim+nYrSim,1,1)-ISOdate(yrStartSim,1,1)
				replRf<-read.table(file="rf_amt_lon.out",header=FALSE,skip=(sim.index-1)*(nLine+1),nrows=nLine)
				if (nStation==1) {
					replRfMeanOfAllStns<-replRf[1:nrow(replRf),4:ncol(replRf)]
				}
				else {
					replRfMeanOfAllStns<-apply(replRf[1:nrow(replRf),4:ncol(replRf)],1,mean)	
				}
				x.Date<-as.Date(ISOdate(replRf[1,1],replRf[1,2],replRf[1,3]))+0:(nrow(replRf)-1)
				if (amt==1){
				replRfMeanOfAllStns.z<-zoo(replRfMeanOfAllStns,x.Date)							
				par(pty="s")
				plot(replRfMeanOfAllStns.z,xlab="Date",ylab="mm",main=paste("Monthly rainfall amount (sim.",sim.index,")"),
					cex.main=fontsize,cex.lab=fontsize, cex.axis=fontsize,cex=fontsize)	
				}
			}
		}
	}
	

}
writeDataFun<-function(nYr,yrStart,band,nStation,nSim,nLon,lag,nYrSim,yrStartSim,amt,local,genSpatial,inclSpatial,inputRfFile,distFile){
	#Function to write 'data.dat'
	outputDataFile<-"rf_amt_lon.out"
	parameters<-file("data.dat")
	writeLines(c("Wilks main data file to supply values of input parameters & names of data files",
			"NO	Yst(O)	BAND	NSTN	NSIM	NLON	LAG	NG	YST(G)	AMT	LOCAL	SPATIAL	CROSS"), parameters)
	cat(nYr,yrStart,band,nStation,nSim,nLon,lag,nYrSim,yrStartSim,amt,local,genSpatial,inclSpatial,"\n",sep="\t",file="data.dat",append=TRUE)
	cat("Number of previous time lags (in days) for nLon","\n",file="data.dat",append=TRUE)	  
	previousLagFrom<-list()
	previousLagTo<-list()
	#Grab user input values and write into file 'data.dat'
	if (nLon==1){
		previousLagFrom[[1]]<-grab_int_value(previousLagFromSpin[[1]])
		cat(previousLagFrom[[1]],"\n",file="data.dat",append=TRUE)
		previousLagTo[[1]]<-grab_int_value(previousLagToSpin[[1]])
		cat(previousLagTo[[1]],"\n",file="data.dat",append=TRUE)
	}
	if (nLon==2){
		previousLagFrom[[1]]<-grab_int_value(previousLagFromSpin[[1]])
		previousLagFrom[[2]]<-grab_int_value(previousLagFromSpin[[2]])
		cat(previousLagFrom[[1]],previousLagFrom[[2]],sep="\t",file="data.dat",append=TRUE)
		cat("\n",file="data.dat",append=TRUE)
		previousLagTo[[1]]<-grab_int_value(previousLagToSpin[[1]])
		previousLagTo[[2]]<-grab_int_value(previousLagToSpin[[2]])
		cat(previousLagTo[[1]],previousLagTo[[2]],sep="\t",file="data.dat",append=TRUE)
		cat("\n",file="data.dat",append=TRUE)
	}
	if (nLon==3){
		previousLagFrom[[1]]<-grab_int_value(previousLagFromSpin[[1]])
		previousLagFrom[[2]]<-grab_int_value(previousLagFromSpin[[2]])
		previousLagFrom[[3]]<-grab_int_value(previousLagFromSpin[[3]])
		cat(previousLagFrom[[1]],previousLagFrom[[2]],previousLagFrom[[3]],sep="\t",file="data.dat",append=TRUE)
		cat("\n",file="data.dat",append=TRUE)
		previousLagTo[[1]]<-grab_int_value(previousLagToSpin[[1]])
		previousLagTo[[2]]<-grab_int_value(previousLagToSpin[[2]])
		previousLagTo[[3]]<-grab_int_value(previousLagToSpin[[3]])
		cat(previousLagTo[[1]],previousLagTo[[2]],previousLagTo[[3]],sep="\t",file="data.dat",append=TRUE)
		cat("\n",file="data.dat",append=TRUE)
	}	 
	cat("Name of rainfall data file","\n",file="data.dat",append=TRUE)
	cat(inputRfFile,"\n",file="data.dat",append=TRUE)
	cat("Name of output data file","\n",file="data.dat",append=TRUE)
	cat(outputDataFile,"\n",file="data.dat",append=TRUE)
	cat("Name of random number correlation file for occurrences","\n",file="data.dat",append=TRUE)
	cat("cor_occr.dat","\n",file="data.dat",append=TRUE)
	cat("Name of random number correlation file for amount","\n",file="data.dat",append=TRUE)
	cat("cor_amt.dat","\n",file="data.dat",append=TRUE)
	cat("Name of distance file","\n",file="data.dat",append=TRUE)
	cat(distFile,"\n",file="data.dat",append=TRUE)
	close(parameters)			
}
#Function to retrieve user defined parameters from Data Parameters Page and overwrite the file "data.dat"
#Then produce plots for replicates and also enable to save the plots
replFun<-function(nYr,yrStart,band,nStation,nSim,nLon,lag,nYrSim,yrStartSim,amt,local,genSpatial,inclSpatial,inputRfFile,distFile){
	#Function to write user input into file 'data.dat'
	writeDataFun(nYr,yrStart,band,nStation,nSim,nLon,lag,nYrSim,yrStartSim,amt,local,genSpatial,inclSpatial,inputRfFile,distFile)
	progressBar$setFraction(1/100)
	Sys.sleep(0.1 )
	info <- sprintf("%d%% completed",1)
	progressBar$setText(sprintf("Estimate Multisite Rainfall (%s)",info))
	  
	i=2			 
	progressBar$setFraction(2/100)
	Sys.sleep(0.1 )
	info <- sprintf("%d%% completed",2)
	progressBar$setText(sprintf("Estimate Multisite Rainfall (%s)",info))
						  	
	i=3			 	 
	progressBar$setFraction(15/100)
	Sys.sleep(0.1 )
	info <- sprintf("%d%% completed",15)
	progressBar$setText(sprintf("Estimate Multisite Rainfall (%s)",info))
					  
	i=4			 
	dataParameterTable$attach(notRespondingLabel,left.attach=0,4,top.attach=13,14,
		xoptions=c("expand","fill"),yoptions="",xpadding = 5, ypadding = 10)
	notRespondingLabel$setMarkup(paste('<span foreground="red" gravity="west" size="xx-large">','Program is running ...','</span>',sep=""))
	progressBar$setFraction(20/100)
	Sys.sleep(0.1 )
	info <- sprintf("%d%% completed",20)
	progressBar$setText(sprintf("Estimate Multisite Rainfall (%s)",info))
						  
	i=5
	system(shQuote("MRS.exe" , type = "cmd" ))
	progressBar$setFraction(60/100)
	Sys.sleep(0.1 )
	info <- sprintf("%d%% completed", 60)
	progressBar$setText(sprintf("Estimate Multisite Rainfall (%s)",info))

	i=6
	#Read data parameters from file 'data.dat'
	parameters<-scan(file="data.dat",skip=2,nline=1,quiet = TRUE)
	nYr<-parameters[1]
	yrStart<-parameters[2]
	band<-parameters[3]
	nStation<-parameters[4]	  
	nSim<-parameters[5]
	nLon<-parameters[6]
	lag<-parameters[7]
	nYrSim<-parameters[8]
	yrStartSim<-parameters[9]
	amt<-parameters[10]
	local<-parameters[11]
	genSpatial<-parameters[12]
	inclSpatial<-parameters[13]
	
	#Set simulation options
	child_simulationOptionFrame<-simulationOptionFrame[[1]]
	simulationOptionFrame$remove(child_simulationOptionFrame)
	replScrolledWindow <- gtkScrolledWindow()
	replScrolledWindow$setSizeRequest(200,800)
	
	simulationList <- data.frame(sim.index=1:nSim,sim.name=paste("sim.",1:nSim,sep=""))	
	replModel<-rGtkDataFrame(simulationList)
	replView<-gtkTreeView(replModel)
	replView$getSelection()$setMode("browse")
	replColumn<-gtkTreeViewColumn("simulation      ",gtkCellRendererText(),text=1)
	replView$appendColumn(replColumn)  
	replScrolledWindow$add(replView)	  	
	simulationOptionFrame$add(replScrolledWindow)
	
	replOptionSel<-replView$getSelection()
	gSignalConnect(replOptionSel,"changed",function(replOptionSel,event,data){
		if (length(dev.list()>1)) dev.off()	
		#Add graphic device to view simulation page			 
		replPlotDevice<-gtkDrawingArea()
		replPlotDevice$setSizeRequest(600,800)
		asCairoDevice(replPlotDevice)
		viewsimulationsTable$attach(replPlotDevice,left.attach=1,2,top.attach=0,1,
			xoptions=c("expand","fill"),yoptions="",ypadding=0)
		Sys.sleep(.1)	
		fontsize<-1.5
		replPlotFun(nSim,yrStartSim,nYrSim,amt,replOptionSel,fontsize)
	})
	#Save simulation
	gSignalConnect(saveReplButton, "clicked", function(saveReplButton,event,data){
		ReplPlot<-savePlotFileAs()
		if (ReplPlot!=""){
			dev.new()
			fontsize<-1.6
			replPlotFun(nSim,yrStartSim,nYrSim,amt,replOptionSel,fontsize)
			savePlot(filename=ReplPlot,type = getExt(ReplPlot),device = dev.cur(),restoreConsole = TRUE)
			dev.off()
		}
	})
}

# Function to rip trailing whitespace of a string
trim.trailing <- function (x) sub("\\s+$", "", x)			
estimateFun<-function(){
	i=0
	progressBar$setFraction(0/100)
	Sys.sleep(0.1 )
	info <- sprintf("%d%% completed",0)
	progressBar$setText(sprintf("Estimate Multisite Rainfall (%s)",info))
	parameters<-scan(file="data.dat",skip=2,nline=1,quiet = TRUE)
    nStationPre<-parameters[4]#previous value of nStation	  				 
	i=1
	nYr<-grab_int_value(nYrSpin)
	yrStart<-grab_int_value(yrStartSpin)
	band<-grab_int_value(bandSpin)
	nStation<-grab_int_value(nStationSpin)
	nSim<-grab_int_value(nSimSpin)
	nYrSim<-grab_int_value(nYrSimSpin)
	yrStartSim<-grab_int_value(yrStartSimSpin)
	lag<-grab_int_value(lagSpin)
	nLon<-grab_int_value(nLonSpin)
	ifelse(rfOccOnlyCheckButton$getActive()==TRUE,amt<-0,amt<-1)
	local<-grab_int_value(localSpin)
	nLon<-grab_int_value(nLonSpin)
	#nStation<-30, 11346;#nStation<-29, 10980 
	nlineCorPre<-length(count.fields("cor_occr.dat")) 
	nlineCor<-366*(nStation+1)  
	ifelse(inclSpatialCheckButton$getActive()==TRUE,inclSpatial<-1,inclSpatial<-0)
	ifelse(nlineCor==nlineCorPre,genSpatial<-0,genSpatial<-1)
	#if(genSpatialCheckButton$getActive()==TRUE) {genSpatial<-1}
	list_data_fi=readLines("data.dat")
	inputRfFile<-list_data_fi[8]
	#Parameter validation test
	#Input data file is not selected
	if (inputRfFile==""){	
		 errMessage<-"The input rainfall data file was not selected. "
		 errMesgFun(errMessage)
	}
	#Input data file is selected, but is not "rain.dat" file
	#In this case, the user needs to select a distance file
	else if(trim.trailing(filenameExt(inputRfFile))!= "rain.dat"){
		distFile<-tk_choose.files(default="",caption = paste("Select distance file"),
        multi = FALSE, filters =matrix(c("Text",".txt","R data", ".data","Dat",".dat"),3, 2, byrow = TRUE)) 
		if(distFile==""){
			errMessage<-"Distance file was not selected. "
			errMesgFun(errMessage)
		}
		else{
			genSpatial<-1		
			#Function to retrieve user defined parameters from Model Parameters Page and write into a file "data.dat"
			#Then produce plots for replicates and also enable to save the plots
			replFun(nYr,yrStart,band,nStation,nSim,nLon,lag,nYrSim,yrStartSim,amt,local,genSpatial,inclSpatial,inputRfFile,distFile)
		}
	}
	#input file is "rain.dat"
	else{		 
		inputRf<-read.table(inputRfFile,skip=3)
		yrStartMin<-inputRf[1,1]
		yrStartMax<-inputRf[nrow(inputRf)-1,1]
		nStationMax<-ncol(inputRf)-3			  
		if (yrStart<yrStartMin | yrStart>yrStartMax){	
			errMessage<-"'Start year (ob.)' exceeds the time period of the input rainfall data file. "
			errMesgFun(errMessage)
		}
		else if (yrStartSim<yrStart){
			errMessage<-"'Start year (sim.)' is ealier than 'start year (ob.)'. "
			errMesgFun(errMessage)
		}
		else if ((nYr+yrStart-1)>yrStartMax){
			errMessage<-"The sum of 'start year (ob.)' and 'number of years (ob.)' exceeds the time period of the input rainfall data file. "
			errMesgFun(errMessage)
		}		
		else if ((nYrSim+yrStartSim-1)>yrStartMax){
			errMessage<-"The sum of 'start year (sim.)' and 'number of years (sim.)' exceeds the time period of the input rainfall data file. "
			errMesgFun(errMessage)
		}
		else if (nStation>nStationMax){
			errMessage<-"'Number of stations' exceeds the number of stations in the input rainfall data file. "
			errMesgFun(errMessage)
		}
		else if (nStation>nStationMax){
			errMessage<-"'Number of stations' exceeds the number of stations in the input rainfall data file. "
			errMesgFun(errMessage)
		}	
		#input file is "rain.dat" and nStation<=30		
		else{			
			distFile<-"dist.dat"
			#Function to retrieve user defined parameters from Model Parameters Page and write into a file "data.dat"
			#Then produce plots for replicates and also enable to save the plots
			replFun(nYr,yrStart,band,nStation,nSim,nLon,lag,nYrSim,yrStartSim,amt,local,genSpatial,inclSpatial,inputRfFile,distFile)
		}
		stnNumber<-read.table(inputRfFile,nrows=1)[2:(nStation+1)]
		#max(nStation)=30
		for (i in 0:30){
			rfAmtStnCombo$removeText(0)
		}
		sapply(c("All stations",stnNumber),rfAmtStnCombo$appendText)
		rfAmtStnCombo$setActive(0)
		for (i in 0:30){
			rfOccStnCombo$removeText(0)
		}		
		sapply(c("All stations",stnNumber),rfOccStnCombo$appendText)
		rfOccStnCombo$setActive(0)
		progressBar$setFraction(100/100)
		Sys.sleep(0.1 )
		info <- sprintf("%d%% completed", 100)
		progressBar$setText(sprintf("Estimate Multisite Rainfall (%s)",info))
	}
	dataParameterTable$remove(notRespondingLabel)
}									
gSignalConnect(runButton,"clicked",function(runButton,event,data){
	list<-readLines("option.dat")
	list<-sub(list[2],"0",list)
	writeLines(list,"option.dat") 
	estimateFun()
	list<-readLines("option.dat")
	list<-sub(list[2],"1",list)
	writeLines(list,"option.dat") 
})	

saveParaFun<-function(){
	parameters<-scan(file="data.dat",skip=2,nline=1,quiet = TRUE)
    nStationPre<-parameters[4]#previous value of nStation
	#Read user input
	nYr<-grab_int_value(nYrSpin)
	yrStart<-grab_int_value(yrStartSpin)
	band<-grab_int_value(bandSpin)
	nStation<-grab_int_value(nStationSpin)
	nSim<-grab_int_value(nSimSpin)
	nYrSim<-grab_int_value(nYrSimSpin)
	yrStartSim<-grab_int_value(yrStartSimSpin)
	lag<-grab_int_value(lagSpin)
	nLon<-grab_int_value(nLonSpin)
	ifelse(rfOccOnlyCheckButton$getActive()==TRUE,amt<-0,amt<-1)
	local<-grab_int_value(localSpin)
	nLon<-grab_int_value(nLonSpin)
	#nStation<-30, 11346;#nStation<-29, 10980 
	nlineCorPre<-length(count.fields("cor_occr.dat")) 
	nlineCor<-366*(nStation+1)  
	ifelse(inclSpatialCheckButton$getActive()==TRUE,inclSpatial<-1,inclSpatial<-0)
	ifelse(nlineCor==nlineCorPre,genSpatial<-0,genSpatial<-1)
	#if(genSpatialCheckButton$getActive()==TRUE) {genSpatial<-1}
	list_data_fi=readLines("data.dat")
	inputRfFile<-list_data_fi[8]
	#Parameter validation test
	#Input data file is not selected
	if (inputRfFile==""){	
		 errMessage<-"The input rainfall data file was not selected. "
		 errMesgFun(errMessage)
	}
	#Input data file is selected, but is not "rain.dat" file
	#In this case, the user needs to select a distance file
	else if(trim.trailing(filenameExt(inputRfFile))!= "rain.dat"){
		distFile<-tk_choose.files(default="",caption = paste("Select distance file"),
        multi = FALSE, filters =matrix(c("Text",".txt","R data", ".data","Dat",".dat"),3, 2, byrow = TRUE)) 
		if(distFile==""){
			errMessage<-"Distance file was not selected. "
			errMesgFun(errMessage)
		}
		else{
			genSpatial<-1
			writeDataFun(nYr,yrStart,band,nStation,nSim,nLon,lag,nYrSim,yrStartSim,amt,local,genSpatial,inclSpatial,inputRfFile,distFile)	
		} 
	}
	#input file is "rain.dat"
	else{		 
		inputRf<-read.table(inputRfFile,skip=3)
		yrStartMin<-inputRf[1,1]
		yrStartMax<-inputRf[nrow(inputRf)-1,1]
		nStationMax<-ncol(inputRf)-3			  
		if (yrStart<yrStartMin | yrStart>yrStartMax){	
			errMessage<-"'Start year (ob.)' exceeds the time period of the input rainfall data file. "
			errMesgFun(errMessage)
		}
		else if (yrStartSim<yrStart){
			errMessage<-"'Start year (sim.)' is earlier than 'start year (ob.)'. "
			errMesgFun(errMessage)
		}
		else if ((nYr+yrStart-1)>yrStartMax){
			errMessage<-"'start year (ob.)' and/or 'number of years (ob.)' exceeds the time period of the input rainfall data file. "
			errMesgFun(errMessage)
		}		
		else if ((nYrSim+yrStartSim-1)>yrStartMax){
			errMessage<-"'start year (sim.)' and/or 'number of years (sim.)' exceeds the time period of the input rainfall data file. "
			errMesgFun(errMessage)
		}
		else if (nStation>nStationMax){
			errMessage<-"'Number of stations' exceeds the number of stations in the input rainfall data file. "
			errMesgFun(errMessage)
		}
		else if (nStation>nStationMax){
			errMessage<-"'Number of stations' exceeds the number of stations in the input rainfall data file. "
			errMesgFun(errMessage)
		}	
		#input file is "rain.dat" and nStation<=30		
		else{			
			distFile<-"dist.dat"
			#Function to write 'data.dat'
			writeDataFun(nYr,yrStart,band,nStation,nSim,nLon,lag,nYrSim,yrStartSim,amt,local,genSpatial,inclSpatial,inputRfFile,distFile)
	
		}	
	}
}							
gSignalConnect(saveParaButton,"clicked",function(runButton,event,data){
	saveParaFun()
})				
#View simulations page
viewsimulationsTable<-gtkTable(rows=2,columns=2,homogeneous=FALSE)
notebook$appendPage(viewsimulationsTable,gtkLabel("View Simulations"))
simulationOptionFrame<-gtkFrame("Simulation Option")
viewsimulationsTable$attach(simulationOptionFrame,left.attach=0,1,
	top.attach=0,1,xoptions=c("shrink","fill"),yoptions="",ypadding=0)
saveReplButton<-gtkButtonNewWithLabel("Save Simulation")
viewsimulationsTable$attach(saveReplButton,left.attach=0,1,top.attach=1,2,
	xoptions=c("shrink","fill"),yoptions="",ypadding=0)
replScrolledWindow <- gtkScrolledWindow()
replScrolledWindow$setSizeRequest(200,800)
simulationOptionFrame$add(replScrolledWindow)		
#Statistics page
statisticOptionTable<-gtkTable(rows=1,columns=1,homogeneous=FALSE)
notebook$appendPage(statisticOptionTable,gtkLabel("Statistics"))
statVbox<-gtkVBox()
statisticOptionTable$attach(statVbox,left.attach=0,1,top.attach=0,1,
	xoptions=c("expand","fill"),yoptions=c("expand","fill"),ypadding=0)
notebookStat<-gtkNotebook()
notebookStat['tab-pos']<-"top"
statVbox$packStart(notebookStat,TRUE,TRUE)
rfAmtTable<-gtkTable(rows=3,columns=2,homogeneous=FALSE)

#
xy_scale=c(0.95,1.05)
#Plot the statistics of the variables having the same format as the Mean of Annual Rainfall Amount
#annualStat=rfAmtAnnualSeasonalMean; main="Mean of Annual Rainfall Amount"
annualStatPlotFun<-function(annualStat,main,nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength){					 
	if (rfStatSelStn=="All stations"){
		ColIndex<-seq(from=6,to=1+nStation*5,by=5)
		if (nSim==1){
			Rep<-annualStat[2:(nSim+1),ColIndex]
		}
		else if (nStation==1){
			Rep<-mean(annualStat[2:(nSim+1),ColIndex])
		}
		else{
			Rep<-apply(annualStat[2:(nSim+1),ColIndex],2,mean)#Equivalent to MATLAB mean(annualStat(2:(nSim+1),ColIndex),1)
		}
		Ob<-annualStat[1,ColIndex]
		qq<-qqplot(Ob,Rep, plot.it = FALSE)		
		par(pty="s")
		plot(qq$x,qq$y,xlim=xy_scale*range(qq$x,qq$y),ylim=xy_scale*range(qq$x,qq$y),
		  xlab = "Observed",ylab = "Simulated",main=paste(main),lwd=linewidth,
		  cex.main=fontsize,cex.lab=fontsize, cex.axis=fontsize,
		  cex=fontsize,asp=1)
	    #fit <- lm(Rep ~ Ob, data = qq)
		#abline(fit,lty=3,cex=1.2)
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)		
	}
	else{ 
		selStnNumber<-as.numeric(rfStatSelStn)
		selStn<-which(stnNumber==selStnNumber)
		annualStatSelStn<-annualStat[,1+selStn*5]
		ymax<-max(annualStatSelStn)
		ymin<-min(annualStatSelStn)
		yext<-(ymax-ymin)*0.05		
		par(mar=c(5.5,4.5,3,4),xpd=TRUE,pty="s")
		if (mainLength>30){
			boxplot(annualStatSelStn[2:(nSim+1)],ylim=c(ymin-yext,ymax+yext),xaxt='n',
				main=paste(main,"\nat station",rfStatSelStn),lwd=linewidth,
				xlab="",ylab="Statistic Value",cex.main=fontsize,cex.lab=fontsize,
				cex.axis=fontsize,cex=fontsize)
		}
		else {
			boxplot(annualStatSelStn[2:(nSim+1)],ylim=c(ymin-yext,ymax+yext),xaxt='n',
				main=paste(main,"at station",rfStatSelStn),lwd=linewidth,
				xlab="",ylab="Statistic Value",cex.main=fontsize,cex.lab=fontsize,
				cex.axis=fontsize,cex=fontsize)
		}
		points(annualStatSelStn[1],col="red",pch=21,cex=fontsize)									 
		par(mfg=c(1,1))
		boxplot(mean(annualStatSelStn[2:(nSim+1)]),ylim=c(ymin-yext,ymax+yext),border=2,lwd=linewidth,
			yaxt='n',cex.main=fontsize,cex.lab=fontsize,cex.axis=fontsize,cex=fontsize)				
		legend("bottom", inset=c(-0.15,-0.15),
			legend = c("observed","simulations mean"),col=c("red","red"),
			lty=c(0,1),lwd=c(linewidth,linewidth+1),pch=c(21,NA),bg = "white", horiz=TRUE,
			cex=fontsize, bty = "n" )									 
	}
}
seasonalStatPlotFun<-function(seasonalStat,main,nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength){
	if (rfStatSelStn=="All stations"){
		SpringColIndex<-seq(from=4,to=1+nStation*5,by=5)
		SummerColIndex<-seq(from=5,to=1+nStation*5,by=5)
		AutumnColIndex<-seq(from=2,to=1+nStation*5,by=5)
		WinterColIndex<-seq(from=3,to=1+nStation*5,by=5)
		if (nSim==1){
			SpringRep<-seasonalStat[2:(nSim+1),SpringColIndex]
			SummerRep<-seasonalStat[2:(nSim+1),SummerColIndex]
			AutumnRep<-seasonalStat[2:(nSim+1),AutumnColIndex]
			WinterRep<-seasonalStat[2:(nSim+1),WinterColIndex]
		}
		else if (nStation==1){
			SpringRep<-mean(seasonalStat[2:(nSim+1),SpringColIndex])
			SummerRep<-mean(seasonalStat[2:(nSim+1),SummerColIndex])
			AutumnRep<-mean(seasonalStat[2:(nSim+1),AutumnColIndex])
			WinterRep<-mean(seasonalStat[2:(nSim+1),WinterColIndex])
		}
		else{
			SpringRep<-apply(seasonalStat[2:(nSim+1),SpringColIndex],2,mean)
			SummerRep<-apply(seasonalStat[2:(nSim+1),SummerColIndex],2,mean)
			AutumnRep<-apply(seasonalStat[2:(nSim+1),AutumnColIndex],2,mean)
			WinterRep<-apply(seasonalStat[2:(nSim+1),WinterColIndex],2,mean)
		}
		SpringOb<-seasonalStat[1,SpringColIndex]
		SummerOb<-seasonalStat[1,SummerColIndex]
		AutumnOb<-seasonalStat[1,AutumnColIndex]
		WinterOb<-seasonalStat[1,WinterColIndex]							 		
		par(mfrow = c(2,2),mar = c(4,4,2,1),oma=c(1.5,1.5,3,1),xpd=FALSE,pty="s")	
        qq_au<-qqplot(AutumnOb, AutumnRep, plot.it = FALSE)
		plot(qq_au$x,qq_au$y,xlim=xy_scale*range(qq_au$x,qq_au$y),ylim=xy_scale*range(qq_au$x,qq_au$y),
		  xlab="",ylab="",asp=1,cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)
		#fit_au <- lm(AutumnRep ~ AutumnOb, data = qq_au)
		#abline(fit_au,lty=3)		
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)		 
		mtext(side = 3, text = "Autumn", line = 0.5,cex=fontsize)
		mtext(side = 1, text = "Observed", line = 3,cex=fontsize)
		mtext(side = 2, text = "Simulated", line = 3,cex=fontsize)
	    qq_wi<-qqplot(WinterOb, WinterRep, plot.it = FALSE)
		plot(qq_wi$x,qq_wi$y,xlim=xy_scale*range(qq_wi$x,qq_wi$y),ylim=xy_scale*range(qq_wi$x,qq_wi$y),
		  xlab="",ylab="",asp=1,cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)
		#fit_wi <- lm(WinterRep ~ WinterOb, data = qq_wi)
		#abline(fit_wi,lty=3)
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)		 		 
		mtext(side = 3, text = "Winter", line = 0.5,cex=fontsize)
		mtext(side = 1, text = "Observed", line = 3,cex=fontsize)
  	    mtext(side = 2, text = "Simulated", line = 3,cex=fontsize)							 
	    qq_sp<-qqplot(SpringOb, SpringRep, plot.it = FALSE)
		plot(qq_sp$x,qq_sp$y,xlim=xy_scale*range(qq_sp$x,qq_sp$y),ylim=xy_scale*range(qq_sp$x,qq_sp$y),
		  xlab="",ylab="",asp=1,cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)
		#fit_sp <- lm(SpringRep ~ SpringOb, data = qq_sp)
		#abline(fit_sp,lty=3)	
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)		 		 
		mtext(side = 3, text = "Spring", line = 0.5,cex=fontsize)
		mtext(side = 1, text = "Observed", line = 3,cex=fontsize)
		mtext(side = 2, text = "Simulated", line = 3,cex=fontsize)							 
		qq_su<-qqplot(SummerOb, SummerRep, plot.it = FALSE)
		plot(qq_su$x,qq_su$y,xlim=xy_scale*range(qq_su$x,qq_su$y),ylim=xy_scale*range(qq_su$x,qq_su$y),
		  xlab="",ylab="",asp=1,cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)
		#fit_su <- lm(SummerRep ~ SummerOb, data = qq_su)
		#abline(fit_su,lty=3)	
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)		 		 
		mtext(side = 3, text = "Summer", line = 0.5,cex=fontsize)
		mtext(side = 1, text = "Observed", line = 3,cex=fontsize)
		mtext(side = 2, text = "Simulated", line = 3,cex=fontsize)						 
		par(mfrow = c(1,1),mar = c(0,0,0,0),oma=c(0,0,2,0),xpd=TRUE)
		title(main=paste(main),outer = T,cex.main=fontsize+0.3) 							 	
	}
	else{ 
		selStnNumber<-as.numeric(rfStatSelStn)
		selStn<-which(stnNumber==selStnNumber)
		#Spring statistics at selected stations
		SpringSelStn<-seasonalStat[,4+(selStn-1)*5]
		SummerSelStn<-seasonalStat[,5+(selStn-1)*5]
		AutumnSelStn<-seasonalStat[,2+(selStn-1)*5]
		WinterSelStn<-seasonalStat[,3+(selStn-1)*5]
		ymax_sp<-max(SpringSelStn)								
		ymin_sp<-min(SpringSelStn)
		yext_sp<-(ymax_sp-ymin_sp)*0.05
		ymax_su<-max(SummerSelStn)								
		ymin_su<-min(SummerSelStn)
		yext_su<-(ymax_su-ymin_su)*0.05							 
		ymax_au<-max(AutumnSelStn)								
		ymin_au<-min(AutumnSelStn)
		yext_au<-(ymax_au-ymin_au)*0.05							 
		ymax_wi<-max(WinterSelStn)								
		ymin_wi<-min(WinterSelStn)
		yext_wi<-(ymax_wi-ymin_wi)*0.05						
		
		par(mfrow = c(2,2),mar = c(1.5,2.5,1,1),oma=c(7,2,7,1),xpd=TRUE,pty="s")
		boxplot(AutumnSelStn[2:(nSim+1)],ylim=c(ymin_au-yext_au,ymax_au+yext_au),
			 xaxt='n',cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)		
        mtext(side = 1, text = "Autumn", line = 0.5,cex=fontsize)									
		points(AutumnSelStn[1],col="red",pch=21,xaxt='n',cex=fontsize)		
        boxplot(WinterSelStn[2:(nSim+1)],ylim=c(ymin_wi-yext_wi,ymax_wi+yext_wi),
			xaxt='n',cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)	
		mtext(side = 1, text = "Winter", line = 0.5,cex=fontsize)
		points(WinterSelStn[1],col="red",pch=21,xaxt='n',cex=fontsize)								 	 		 																	 
		boxplot(SpringSelStn[2:(nSim+1)],ylim=c(ymin_sp-yext_sp,ymax_sp+yext_sp),
			xaxt='n',cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)	
		mtext(side = 1, text = "Spring", line = 0.5,cex=fontsize)
		points(SpringSelStn[1],col="red",pch=21,xaxt='n',cex=fontsize)	
		boxplot(SummerSelStn[2:(nSim+1)],ylim=c(ymin_su-yext_su,ymax_su+yext_su),
			 xaxt='n',cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)	
		mtext(side = 1, text = "Summer", line = 0.5,cex=fontsize)
		points(SummerSelStn[1],col="red",pch=21,xaxt='n',cex=fontsize)								 
        par(mfg=c(1,1))
		boxplot(mean(AutumnSelStn[2:(nSim+1)]),ylim=c(ymin_au-yext_au,ymax_au+yext_au),border=2,lwd=0.5,yaxt='n')
		boxplot(mean(WinterSelStn[2:(nSim+1)]),ylim=c(ymin_wi-yext_wi,ymax_wi+yext_wi),border=2,lwd=0.5,yaxt='n')
		boxplot(mean(SpringSelStn[2:(nSim+1)]),ylim=c(ymin_sp-yext_sp,ymax_sp+yext_sp),border=2,lwd=0.5,yaxt='n')							 
		boxplot(mean(SummerSelStn[2:(nSim+1)]),ylim=c(ymin_su-yext_su,ymax_su+yext_su),border=2,lwd=0.5,yaxt='n')
		par(mfrow = c(1,1),mar = c(0,0,0,0),oma=c(0,0,5,0),xpd=TRUE)
		if (mainLength>30) {
			title(main=paste(main,"\nat station",rfStatSelStn),outer = T,cex.main=fontsize+0.3)
		}
		else {
			title(main=paste(main,"at station",rfStatSelStn),outer = T,cex.main=fontsize+0.3)
		}
		legend("bottom", inset=c(-0.05,-0.05),legend = c("observed","simulations mean"),
			col=c("red","red"),lty=c(0,1),lwd=c(0,linewidth),pch=c(21,NA),
			bg = "white", horiz=TRUE,cex=fontsize,bty="n")							 
		
	}
}
seasonalStatPlotSaveFun<-function(seasonalStat,main,nSim,nStation,rfStatSelStn,stnNumber){
	if (rfStatSelStn=="All stations"){
		SpringColIndex<-seq(from=4,to=1+nStation*5,by=5)
		SummerColIndex<-seq(from=5,to=1+nStation*5,by=5)
		AutumnColIndex<-seq(from=2,to=1+nStation*5,by=5)
		WinterColIndex<-seq(from=3,to=1+nStation*5,by=5)
		if (nSim==1){
			SpringRep<-seasonalStat[2:(nSim+1),SpringColIndex]
			SummerRep<-seasonalStat[2:(nSim+1),SummerColIndex]
			AutumnRep<-seasonalStat[2:(nSim+1),AutumnColIndex]
			WinterRep<-seasonalStat[2:(nSim+1),WinterColIndex]
		}
		else if (nStation==1){
			SpringRep<-mean(seasonalStat[2:(nSim+1),SpringColIndex])
			SummerRep<-mean(seasonalStat[2:(nSim+1),SummerColIndex])
			AutumnRep<-mean(seasonalStat[2:(nSim+1),AutumnColIndex])
			WinterRep<-mean(seasonalStat[2:(nSim+1),WinterColIndex])
		}
		else{
			SpringRep<-apply(seasonalStat[2:(nSim+1),SpringColIndex],2,mean)
			SummerRep<-apply(seasonalStat[2:(nSim+1),SummerColIndex],2,mean)
			AutumnRep<-apply(seasonalStat[2:(nSim+1),AutumnColIndex],2,mean)
			WinterRep<-apply(seasonalStat[2:(nSim+1),WinterColIndex],2,mean)
		}
		SpringOb<-seasonalStat[1,SpringColIndex]
		SummerOb<-seasonalStat[1,SummerColIndex]
		AutumnOb<-seasonalStat[1,AutumnColIndex]
		WinterOb<-seasonalStat[1,WinterColIndex]							 		
		par(mfrow = c(2,2),mar = c(3.5,3.5,2,1),oma=c(1.5,1.5,3,1),xpd=FALSE,pty="s")	
        qq_au<-qqplot(AutumnOb, AutumnRep, plot.it = FALSE)
		plot(qq_au$x,qq_au$y,xlim=xy_scale*range(qq_au$x,qq_au$y),ylim=xy_scale*range(qq_au$x,qq_au$y),
		  xlab="",ylab="",asp=1)
		#fit_au <- lm(AutumnRep ~ AutumnOb, data = qq_au)
		#abline(fit_au,lty=3)	
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=1.2)		 		 
		mtext(side = 3, text = "Autumn", line = 0.5,cex=1)
		mtext(side = 1, text = "Observed", line = 2,cex=1)
		mtext(side = 2, text = "Simulated", line = 2,cex=1)
	    qq_wi<-qqplot(WinterOb, WinterRep, plot.it = FALSE)
		plot(qq_wi$x,qq_wi$y,xlim=xy_scale*range(qq_wi$x,qq_wi$y),ylim=xy_scale*range(qq_wi$x,qq_wi$y),
		  xlab="",ylab="",asp=1)
		#fit_wi <- lm(WinterRep ~ WinterOb, data = qq_wi)
		#abline(fit_wi,lty=3)	
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=1.2)		 		 
		mtext(side = 3, text = "Winter", line = 0.5,cex=1)
		mtext(side = 1, text = "Observed", line = 2,cex=1)
  	    mtext(side = 2, text = "Simulated", line = 2,cex=1)							 
	    qq_sp<-qqplot(SpringOb, SpringRep, plot.it = FALSE)
		plot(qq_sp$x,qq_sp$y,xlim=xy_scale*range(qq_sp$x,qq_sp$y),ylim=xy_scale*range(qq_sp$x,qq_sp$y),
		  xlab="",ylab="",asp=1)
		#fit_sp <- lm(SpringRep ~ SpringOb, data = qq_sp)
		#abline(fit_sp,lty=3)
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=1.2)		 		 
		mtext(side = 3, text = "Spring", line = 0.5,cex=1)
		mtext(side = 1, text = "Observed", line = 2,cex=1)
		mtext(side = 2, text = "Simulated", line = 2,cex=1)							 
		qq_su<-qqplot(SummerOb, SummerRep, plot.it = FALSE)
		plot(qq_su$x,qq_su$y,xlim=xy_scale*range(qq_su$x,qq_su$y),ylim=xy_scale*range(qq_su$x,qq_su$y),
		  xlab="",ylab="",asp=1)
		#fit_su <- lm(SummerRep ~ SummerOb, data = qq_su)
		#abline(fit_su,lty=3)	
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=1.2)		 		 
		mtext(side = 3, text = "Summer", line = 0.5,cex=1)
		mtext(side = 1, text = "Observed", line = 2,cex=1)
		mtext(side = 2, text = "Simulated", line = 2,cex=1)						 
		par(mfrow = c(1,1),mar = c(0,0,0,0),oma=c(0,0,2,0),xpd=TRUE)
		title(main=paste(main),outer = T,cex.main=1) 							 		
	}
	else{ 
		selStnNumber<-as.numeric(rfStatSelStn)
		selStn<-which(stnNumber==selStnNumber)
		#Spring statistics at selected stations
		SpringSelStn<-seasonalStat[,4+(selStn-1)*5]
		SummerSelStn<-seasonalStat[,5+(selStn-1)*5]
		AutumnSelStn<-seasonalStat[,2+(selStn-1)*5]
		WinterSelStn<-seasonalStat[,3+(selStn-1)*5]
		ymax_sp<-max(SpringSelStn)								
		ymin_sp<-min(SpringSelStn)
		yext_sp<-(ymax_sp-ymin_sp)*0.05
		ymax_su<-max(SummerSelStn)								
		ymin_su<-min(SummerSelStn)
		yext_su<-(ymax_su-ymin_su)*0.05							 
		ymax_au<-max(AutumnSelStn)								
		ymin_au<-min(AutumnSelStn)
		yext_au<-(ymax_au-ymin_au)*0.05							 
		ymax_wi<-max(WinterSelStn)								
		ymin_wi<-min(WinterSelStn)
		yext_wi<-(ymax_wi-ymin_wi)*0.05								
		par(mfrow = c(2,2),mar = c(2,2,1,0.5),oma=c(4,1,2,0.5),xpd=FALSE,pty="s")
		boxplot(AutumnSelStn[2:(nSim+1)],ylim=c(ymin_au-yext_au,ymax_au+yext_au),
			 xaxt='n')		
        mtext(side = 1, text = "Autumn", line = 0.5,cex=1)									
		points(AutumnSelStn[1],col="red",pch=21,xaxt='n')	
        boxplot(WinterSelStn[2:(nSim+1)],ylim=c(ymin_wi-yext_wi,ymax_wi+yext_wi),
			xaxt='n')
		mtext(side = 1, text = "Winter", line = 0.5,cex=1)
		points(WinterSelStn[1],col="red",pch=21,xaxt='n')							 	 		 																	 
		boxplot(SpringSelStn[2:(nSim+1)],ylim=c(ymin_sp-yext_sp,ymax_sp+yext_sp),
			xaxt='n')
		mtext(side = 1, text = "Spring", line = 0.5,cex=1)
		points(SpringSelStn[1],col="red",pch=21,xaxt='n')
		boxplot(SummerSelStn[2:(nSim+1)],ylim=c(ymin_su-yext_su,ymax_su+yext_su),
			 xaxt='n')
		mtext(side = 1, text = "Summer", line = 0.5,cex=1)
		points(SummerSelStn[1],col="red",pch=21,xaxt='n')								 
        par(mfg=c(1,1))
		boxplot(mean(AutumnSelStn[2:(nSim+1)]),ylim=c(ymin_au-yext_au,ymax_au+yext_au),border=2,lwd=0.5,yaxt='n')
		boxplot(mean(WinterSelStn[2:(nSim+1)]),ylim=c(ymin_wi-yext_wi,ymax_wi+yext_wi),border=2,lwd=0.5,yaxt='n')
		boxplot(mean(SpringSelStn[2:(nSim+1)]),ylim=c(ymin_sp-yext_sp,ymax_sp+yext_sp),border=2,lwd=0.5,yaxt='n')							 
		boxplot(mean(SummerSelStn[2:(nSim+1)]),ylim=c(ymin_su-yext_su,ymax_su+yext_su),border=2,lwd=0.5,yaxt='n')
		par(mfrow = c(1,1),mar = c(0,0,0,0),oma=c(0,0,2,0),xpd=TRUE)
		title(main=paste(main,"at station",rfStatSelStn),outer = T,cex.main=1) 
		legend("bottom", inset=c(-0.1,-0.1),legend = c("observed","simulations mean"),
			col=c("red","red"),lty=c(0,1),lwd=c(0,1),pch=c(21,NA),
			bg = "white", horiz=TRUE,cex=1,bty="n")							 		
	}
}
monthlyStatPlotFun<-function(monthlyStat,main,nSim,nStation,rfStatSelStn,stnNumber,mainLength){	 
	if (rfStatSelStn=="All stations"){
		Ob<-monthlyStat[1,]
	    stn_Ob<-Ob[2:13]#Grab data in Station 1
		if (nSim==1){
			Rep<-monthlyStat[2:(nSim+1),]
			stn_Rep<-Rep[2:13]#Grab data in Station 1	
		}
		else if (nStation==1) {
			Rep<-apply(monthlyStat[2:(nSim+1),],2,mean)#mean of all simulations
			stn_Rep<-Rep[2:13]#Grab data in Station 1	
		}
		else {	
			Rep<-apply(monthlyStat[2:(nSim+1),],2,mean)#mean of all simulations
			stn_Rep<-Rep[2:13]#Grab data in Station 1
			for (iStn in 2:nStation){
				istn_Ob<-Ob[(2+(iStn-1)*12):(13+(iStn-1)*12)]
				istn_Rep<-Rep[(2+(iStn-1)*12):(13+(iStn-1)*12)]
				stn_Rep<-rbind(stn_Rep,istn_Rep)
				stn_Ob<-rbind(stn_Ob,istn_Ob)
			}
		}		
		par(mfrow = c(4,3),mar = c(3,3,2,1),oma=c(2,1,3,0.5),xpd=FALSE,pty="s")							 
		for (i in 1:12){
			if (nStation==1){
				qq <-qqplot(stn_Ob[i], stn_Rep[i], plot.it = FALSE)
			}
			else if (nStation>1){
				qq <-qqplot(stn_Ob[,i], stn_Rep[,i], plot.it = FALSE)
			}

			plot(qq$x,qq$y,xlim=xy_scale*range(qq$x,qq$y),ylim=xy_scale*range(qq$x,qq$y)
			,xlab="",ylab="",asp=1,cex.lab=0.8, cex.axis=1,cex=1)
			#fit <- lm(stn_Rep[,i] ~ stn_Ob[,i], data = qq)
			#abline(fit,lty=3,cex=1)	
			#Add a diagonal line to the scatter plot
			lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=1.2)		 			 
			mtext(side = 3, text = substitute(exp, list(exp = month.abb[i])), line = 0.5,cex=0.8)
			mtext(side = 1, text = "Observed", line = 2,cex=0.8)
			mtext(side = 2, text = "Simulated", line = 2,cex=0.8)
		}
		par(mfrow = c(1,1),mar = c(0,0,0,0),xpd=TRUE)
		title(main=paste(main),outer = T,cex.main=1.2) 							 		
	}							
	else{ 
		selStnNumber<-as.numeric(rfStatSelStn)
		selStn<-which(stnNumber==selStnNumber)
		monthlyStatSelStn<-monthlyStat[,(2+(selStn-1)*12):(13+(selStn-1)*12)]
        ymax<-max(monthlyStatSelStn)
	    ymin<-min(monthlyStatSelStn)
	    yext<-(ymax-ymin)*0.05	    
        par(mar=c(7,4.5,3,2),oma=c(2,1,1,0.5),xpd=TRUE,pty="s")
		if (mainLength>30) {
			if(nSim==1){
				boxplot.matrix(rbind(monthlyStatSelStn[2:(1+nSim),],monthlyStatSelStn[2:(1+nSim),]),
					use.cols = TRUE,ylim=c(ymin-yext,ymax+yext),
					xaxt='n',main=paste(main, "\nat station",rfStatSelStn),
					xlab="",ylab="Statistic Value",cex=1.2,cex.lab=1.2,cex.axis=1.2,cex.main=1.2)
			}
			else{
				boxplot.matrix(monthlyStatSelStn[2:(1+nSim),],use.cols = TRUE,ylim=c(ymin-yext,ymax+yext),
					xaxt='n',main=paste(main, "\nat station",rfStatSelStn),
					xlab="",ylab="Statistic Value",cex=1.2,cex.lab=1.2,cex.axis=1.2,cex.main=1.2)
			}			
		}
		else{
			if(nSim==1){
				boxplot.matrix(rbind(monthlyStatSelStn[2:(1+nSim),],monthlyStatSelStn[2:(1+nSim),]),
					use.cols = TRUE,ylim=c(ymin-yext,ymax+yext),
					xaxt='n',main=paste(main, "at station",rfStatSelStn),
					xlab="",ylab="Statistic Value",cex=1.2,cex.lab=1.2,cex.axis=1.2,cex.main=1.2)
			}
			else{
				boxplot.matrix(monthlyStatSelStn[2:(1+nSim),],use.cols = TRUE,ylim=c(ymin-yext,ymax+yext),
					xaxt='n',main=paste(main, "at station",rfStatSelStn),
					xlab="",ylab="Statistic Value",cex=1.2,cex.lab=1.2,cex.axis=1.2,cex.main=1.2)
			}

		}
		axis(1, at = 1:12, labels =month.abb,cex.axis=1.2)
		points(1:12,monthlyStatSelStn[1,],col="red",pch=21,cex=1.2,cex.lab=1.2,cex.axis=1.2)									 							  
		par(mfg=c(1,1))
		if(nSim==1){
			boxplot.matrix(matrix(apply(rbind(monthlyStatSelStn[2:(1+nSim),],monthlyStatSelStn[2:(1+nSim),]),2,mean),nrow=1,ncol=12),
				use.cols = TRUE,ylim=c(ymin-yext,ymax+yext),border=2,lwd=0.5,xaxt='n',xlab="",ylab="",cex=1.2,cex.axis=1.2)	
		}
		else{
			boxplot.matrix(matrix(apply(monthlyStatSelStn[2:(1+nSim),],2,mean),nrow=1,ncol=12),use.cols = TRUE,
				ylim=c(ymin-yext,ymax+yext),border=2,lwd=0.5,xaxt='n',xlab="",ylab="",cex=1.2,cex.axis=1.2)	
		}
					  
	    legend("bottom", inset=c(-0.25,-0.25),legend = c("observed","simulations mean"),col=c("red","red"),
			lty=c(0,1),lwd=c(0,1),pch=c(21,NA),bg = "white", horiz=TRUE,cex=1.2,bty="n")			
	}
}	
monthlyStatPlotSaveFun<-function(monthlyStat,main,nSim,nStation,rfStatSelStn,stnNumber,mainLength){	 
	if (rfStatSelStn=="All stations"){
		Ob<-monthlyStat[1,]
	    stn_Ob<-Ob[2:13]#Grab data in Station 1
		if (nSim==1){
			Rep<-monthlyStat[2:(nSim+1),]
			stn_Rep<-Rep[2:13]#Grab data in Station 1	
		}
		else if (nStation==1) {
			Rep<-apply(monthlyStat[2:(nSim+1),],2,mean)#mean of all simulations
			stn_Rep<-Rep[2:13]#Grab data in Station 1	
		}
		else {	
			Rep<-apply(monthlyStat[2:(nSim+1),],2,mean)#mean of all simulations
			stn_Rep<-Rep[2:13]#Grab data in Station 1
			for (iStn in 2:nStation){
				istn_Ob<-Ob[(2+(iStn-1)*12):(13+(iStn-1)*12)]
				istn_Rep<-Rep[(2+(iStn-1)*12):(13+(iStn-1)*12)]
				stn_Rep<-rbind(stn_Rep,istn_Rep)
				stn_Ob<-rbind(stn_Ob,istn_Ob)
			}
		}		
		par(mfrow = c(4,3),mar = c(3,3,2,1),oma=c(0,1,3,0.5),xpd=FALSE,pty="s")							 
		for (i in 1:12){
			if (nStation==1){
				qq <-qqplot(stn_Ob[i], stn_Rep[i], plot.it = FALSE)
			}
			else if (nStation>1){
				qq <-qqplot(stn_Ob[,i], stn_Rep[,i], plot.it = FALSE)
			}
			plot(qq$x,qq$y,xlim=xy_scale*range(qq$x,qq$y),ylim=xy_scale*range(qq$x,qq$y)
			,xlab="",ylab="",asp=1,cex.lab=0.8, cex.axis=1,cex=1)
			#fit <- lm(stn_Rep[,i] ~ stn_Ob[,i], data = qq)
			#abline(fit,lty=3,cex=1)	
			#Add a diagonal line to the scatter plot
			lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=1.2)		 			 
			mtext(side = 3, text = substitute(exp, list(exp = month.abb[i])), line = 0.5,cex=0.8)
			mtext(side = 1, text = "Observed", line = 2,cex=0.8)
			mtext(side = 2, text = "Simulated", line = 2,cex=0.8)
		}
		par(mfrow = c(1,1),mar = c(0,0,0,0),xpd=TRUE)
		title(main=paste(main),outer = T,cex.main=1.2) 							 		
	}							
	else{ 
		selStnNumber<-as.numeric(rfStatSelStn)
		selStn<-which(stnNumber==selStnNumber)
		monthlyStatSelStn<-monthlyStat[,(2+(selStn-1)*12):(13+(selStn-1)*12)]
        ymax<-max(monthlyStatSelStn)
	    ymin<-min(monthlyStatSelStn)
	    yext<-(ymax-ymin)*0.05	    
        par(mar=c(6,4.5,3,2),oma=c(1,1,1,0.5),xpd=TRUE,pty="s")
		if (mainLength>30){
			if(nSim==1){
				boxplot.matrix(rbind(monthlyStatSelStn[2:(1+nSim),],monthlyStatSelStn[2:(1+nSim),]),
					use.cols = TRUE,ylim=c(ymin-yext,ymax+yext),
					xaxt='n',main=paste(main, "\nat station",rfStatSelStn),
					xlab="",ylab="Statistic Value",cex=1.2,cex.lab=1.2,cex.axis=1.2,cex.main=1.2)
			}
			else{
				boxplot.matrix(monthlyStatSelStn[2:(1+nSim),],use.cols = TRUE,ylim=c(ymin-yext,ymax+yext),
					xaxt='n',main=paste(main, "\nat station",rfStatSelStn),
					xlab="",ylab="Statistic Value",cex=1.2,cex.lab=1.2,cex.axis=1.2,cex.main=1.2)
			}
			

		}
		else {
			if(nSim==1){
				boxplot.matrix(rbind(monthlyStatSelStn[2:(1+nSim),],monthlyStatSelStn[2:(1+nSim),]),
					use.cols = TRUE,ylim=c(ymin-yext,ymax+yext),
					xaxt='n',main=paste(main, "at station",rfStatSelStn),
					xlab="",ylab="Statistic Value",cex=1.2,cex.lab=1.2,cex.axis=1.2,cex.main=1.2)
			}
			else{
				boxplot.matrix(monthlyStatSelStn[2:(1+nSim),],use.cols = TRUE,ylim=c(ymin-yext,ymax+yext),
					xaxt='n',main=paste(main, "at station",rfStatSelStn),
					xlab="",ylab="Statistic Value",cex=1.2,cex.lab=1.2,cex.axis=1.2,cex.main=1.2)
			}

		}
		axis(1, at = 1:12, labels =month.abb,cex.axis=1.2)
		points(1:12,monthlyStatSelStn[1,],col="red",pch=21,cex=1.2,cex.lab=1.2,cex.axis=1.2)									 							  
		par(mfg=c(1,1))
		if(nSim==1){
			boxplot.matrix(matrix(apply(rbind(monthlyStatSelStn[2:(1+nSim),],monthlyStatSelStn[2:(1+nSim),]),2,mean),nrow=1,ncol=12),
				use.cols = TRUE,ylim=c(ymin-yext,ymax+yext),border=2,lwd=0.5,xaxt='n',xlab="",ylab="",cex=1.2,cex.axis=1.2)		
		}
		else{
			boxplot.matrix(matrix(apply(monthlyStatSelStn[2:(1+nSim),],2,mean),nrow=1,ncol=12),use.cols = TRUE,
				ylim=c(ymin-yext,ymax+yext),border=2,lwd=0.5,xaxt='n',xlab="",ylab="",cex=1.2,cex.axis=1.2)		
		}
				  
	    legend("bottom", inset=c(-0.25,-0.25),legend = c("observed","simulations mean"),col=c("red","red"),
			lty=c(0,1),lwd=c(0,1),pch=c(21,NA),bg = "white", horiz=TRUE,cex=1.2,bty="n")			
	}
}	
totRfAmtInWSPlotFun<-function(totRfAmtInWS,text1,text2,text3,text4,main,nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth){
	ColInd_1<-seq(from=2,to=1+nStation*4,by=4) #length = 1 day 
	ColInd_2<-seq(from=3,to=1+nStation*4,by=4) #length = 2-4 days 
	ColInd_3<-seq(from=4,to=1+nStation*4,by=4) #length = 5-7 days 
	ColInd_4<-seq(from=5,to=1+nStation*4,by=4) #length >7 days 
	if (nSim==1){
		Rep_1<-totRfAmtInWS[2:(nSim+1),ColInd_1]
		Rep_2<-totRfAmtInWS[2:(nSim+1),ColInd_2]
		Rep_3<-totRfAmtInWS[2:(nSim+1),ColInd_3]
		Rep_4<-totRfAmtInWS[2:(nSim+1),ColInd_4]		
	}
	else if (nStation==1){
		Rep_1<-mean(totRfAmtInWS[2:(nSim+1),ColInd_1])
		Rep_2<-mean(totRfAmtInWS[2:(nSim+1),ColInd_2])
		Rep_3<-mean(totRfAmtInWS[2:(nSim+1),ColInd_3])
		Rep_4<-mean(totRfAmtInWS[2:(nSim+1),ColInd_4])		
	}
	else{
		Rep_1<-apply(totRfAmtInWS[2:(nSim+1),ColInd_1],2,mean)
		Rep_2<-apply(totRfAmtInWS[2:(nSim+1),ColInd_2],2,mean)
		Rep_3<-apply(totRfAmtInWS[2:(nSim+1),ColInd_3],2,mean)
		Rep_4<-apply(totRfAmtInWS[2:(nSim+1),ColInd_4],2,mean)		
	}			 
	Ob_1<-totRfAmtInWS[1,ColInd_1]
	Ob_2<-totRfAmtInWS[1,ColInd_2]
	Ob_3<-totRfAmtInWS[1,ColInd_3]
	Ob_4<-totRfAmtInWS[1,ColInd_4]
	if (rfStatSelStn=="All stations"){		
		par(mfrow = c(2,2),mar = c(4,4,2,1),oma=c(1.5,1.5,3,1),xpd=FALSE,pty="s")
	    qq_1<-qqplot(Ob_1, Rep_1, plot.it = FALSE)
		plot(qq_1$x,qq_1$y,xlim=xy_scale*range(qq_1$x,qq_1$y),ylim=xy_scale*range(qq_1$x,qq_1$y),
		  xlab="",ylab="",asp=1,cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)	
		#fit_1 <- lm(Rep_1 ~ Ob_1, data = qq_1)
		#abline(fit_1,lty=3)		
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)		 		 
		mtext(side = 3, text = paste(text1), line = 0.5,cex=fontsize)
		mtext(side = 1, text = "Observed", line = 3,cex=fontsize)
		mtext(side = 2, text = "Simulated", line = 3,cex=fontsize)							 
	    qq_2<-qqplot(Ob_2, Rep_2, plot.it = FALSE)
		plot(qq_2$x,qq_2$y,xlim=xy_scale*range(qq_2$x,qq_2$y),ylim=xy_scale*range(qq_2$x,qq_2$y),
		  xlab="",ylab="",asp=1,cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)	
		#fit_2 <- lm(Rep_2 ~ Ob_2, data = qq_2)
		#abline(fit_2,lty=3)
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)		 		 
		mtext(side = 3, text = paste(text2), line = 0.5,cex=fontsize)	
		mtext(side = 1, text = "Observed", line = 3,cex=fontsize)
		mtext(side = 2, text = "Simulated", line = 3,cex=fontsize)							 
   	    qq_3<-qqplot(Ob_3, Rep_3, plot.it = FALSE)
		plot(qq_3$x,qq_3$y,xlim=xy_scale*range(qq_3$x,qq_3$y),ylim=xy_scale*range(qq_3$x,qq_3$y),
		  xlab="",ylab="",asp=1,cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)	
		#fit_3 <- lm(Rep_3 ~ Ob_3, data = qq_3)
		#abline(fit_3,lty=3)
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)		 		 
		mtext(side = 3, text = paste(text3), line = 0.5,cex=fontsize)	
		mtext(side = 1, text = "Observed", line = 3,cex=fontsize)
		mtext(side = 2, text = "Simulated", line = 3,cex=fontsize)							 
		qq_4<-qqplot(Ob_4, Rep_4, plot.it = FALSE)
		plot(qq_4$x,qq_4$y,xlim=xy_scale*range(qq_4$x,qq_4$y),ylim=xy_scale*range(qq_4$x,qq_4$y),
		  xlab="",ylab="",asp=1,cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)	
		#fit_4 <- lm(Rep_4 ~ Ob_4, data = qq_4)
		#abline(fit_4,lty=3)		
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)		 		 
		mtext(side = 3, text = paste(text4), line = 0.5,cex=fontsize)								 
		mtext(side = 1, text = "Observed", line = 3,cex=fontsize)
		mtext(side = 2, text = "Simulated", line = 3,cex=fontsize)								 
		par(mfrow = c(1,1),mar = c(0,0,0,0),oma=c(0,0,2,0),xpd=TRUE)
		title(main=paste(main),outer = T,cex.main=fontsize+0.3) 							 								  						 												 
	}
	else{ 
		selStnNumber<-as.numeric(rfStatSelStn)
		selStn<-which(stnNumber==selStnNumber)
		SelStn_1<-totRfAmtInWS[,2+(selStn-1)*4]
		SelStn_2<-totRfAmtInWS[,3+(selStn-1)*4]
		SelStn_3<-totRfAmtInWS[,4+(selStn-1)*4]
		SelStn_4<-totRfAmtInWS[,5+(selStn-1)*4]
		ymax_1<-max(SelStn_1)								
		ymin_1<-min(SelStn_1)
		yext_1<-(ymax_1-ymin_1)*0.05							 
		ymax_2<-max(SelStn_2)								
		ymin_2<-min(SelStn_2)
		yext_2<-(ymax_2-ymin_2)*0.05							 
		ymax_3<-max(SelStn_3)								
		ymin_3<-min(SelStn_3)
		yext_3<-(ymax_3-ymin_3)*0.05							 
		ymax_4<-max(SelStn_4)								
		ymin_4<-min(SelStn_4)
		yext_4<-(ymax_4-ymin_4)*0.05			
		par(mfrow = c(2,2),mar = c(1.5,2,1,1),oma=c(7,2,7,1),xpd=TRUE,pty="s")						 	 		 																	 
		boxplot(SelStn_1[2:(nSim+1)],ylim=c(ymin_1-yext_1,ymax_1+yext_1),
			 xaxt='n',cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)	
		mtext(side = 1, text = paste(text1), line = 0.5,cex=fontsize)
		points(SelStn_1[1],col="red",pch=21,xaxt='n',cex=fontsize)
		boxplot(SelStn_2[2:(nSim+1)],ylim=c(ymin_2-yext_2,ymax_2+yext_2),
			 xaxt='n',cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)	
		mtext(side = 1, text = paste(text2), line = 0.5,cex=fontsize)
		points(SelStn_2[1],col="red",pch=21,xaxt='n',cex=fontsize)								 							 
		boxplot(SelStn_3[2:(nSim+1)],ylim=c(ymin_3-yext_3,ymax_3+yext_3),
			 xaxt='n',cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)		
        mtext(side = 1, text = paste(text3), line = 0.5,cex=fontsize)									
		points(SelStn_3[1],col="red",pch=21,xaxt='n',cex=fontsize)
        boxplot(SelStn_4[2:(nSim+1)],ylim=c(ymin_4-yext_4,ymax_4+yext_4),
			 xaxt='n',cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)	
		mtext(side = 1, text = paste(text4), line = 0.5,cex=fontsize)
		points(SelStn_4[1],col="red",pch=21,xaxt='n',cex=fontsize)
		par(mfg=c(1,1))
		boxplot(mean(SelStn_1[2:(nSim+1)]),ylim=c(ymin_1-yext_1,ymax_1+yext_1),border=2,lwd=0.5,yaxt='n')							 
		boxplot(mean(SelStn_2[2:(nSim+1)]),ylim=c(ymin_2-yext_2,ymax_2+yext_2),border=2,lwd=0.5,yaxt='n')
		boxplot(mean(SelStn_3[2:(nSim+1)]),ylim=c(ymin_3-yext_3,ymax_3+yext_3),border=2,lwd=0.5,yaxt='n')
		boxplot(mean(SelStn_4[2:(nSim+1)]),ylim=c(ymin_4-yext_4,ymax_4+yext_4),border=2,lwd=0.5,yaxt='n')							 
		par(mfrow = c(1,1),mar = c(0,0,0,0),oma=c(0,0,5,0),xpd=TRUE)
		title(main=paste(main, "\nat station",rfStatSelStn),outer = T,cex.main=fontsize+0.3) 							 
		legend("bottom", inset=c(-0.05,-0.05),legend = c("observed","simulations mean"),
			col=c("red","red"),lty=c(0,1),lwd=c(0,linewidth),pch=c(21,NA),
			bg = "white", horiz=TRUE,cex=fontsize,bty="n")		
	}
}			
totRfAmtInWSPlotSaveFun<-function(totRfAmtInWS,text1,text2,text3,text4,main,nSim,nStation,rfStatSelStn,stnNumber){
	ColInd_1<-seq(from=2,to=1+nStation*4,by=4) #length = 1 day 
	ColInd_2<-seq(from=3,to=1+nStation*4,by=4) #length = 2-4 days 
	ColInd_3<-seq(from=4,to=1+nStation*4,by=4) #length = 5-7 days 
	ColInd_4<-seq(from=5,to=1+nStation*4,by=4) #length >7 days 
	if (nSim==1){
		Rep_1<-totRfAmtInWS[2:(nSim+1),ColInd_1]
		Rep_2<-totRfAmtInWS[2:(nSim+1),ColInd_2]
		Rep_3<-totRfAmtInWS[2:(nSim+1),ColInd_3]
		Rep_4<-totRfAmtInWS[2:(nSim+1),ColInd_4]
	}
	else if (nStation==1){
		Rep_1<-mean(totRfAmtInWS[2:(nSim+1),ColInd_1])
		Rep_2<-mean(totRfAmtInWS[2:(nSim+1),ColInd_2])
		Rep_3<-mean(totRfAmtInWS[2:(nSim+1),ColInd_3])
		Rep_4<-mean(totRfAmtInWS[2:(nSim+1),ColInd_4])
	}
	else{
		Rep_1<-apply(totRfAmtInWS[2:(nSim+1),ColInd_1],2,mean)
		Rep_2<-apply(totRfAmtInWS[2:(nSim+1),ColInd_2],2,mean)
		Rep_3<-apply(totRfAmtInWS[2:(nSim+1),ColInd_3],2,mean)
		Rep_4<-apply(totRfAmtInWS[2:(nSim+1),ColInd_4],2,mean)
	}						 
	Ob_1<-totRfAmtInWS[1,ColInd_1]
	Ob_2<-totRfAmtInWS[1,ColInd_2]
	Ob_3<-totRfAmtInWS[1,ColInd_3]
	Ob_4<-totRfAmtInWS[1,ColInd_4]
	if (rfStatSelStn=="All stations"){		
		par(mfrow = c(2,2),mar = c(3.5,3.5,2,1),oma=c(1.5,1.5,3,1),xpd=FALSE,pty="s")
	    qq_1<-qqplot(Ob_1, Rep_1, plot.it = FALSE)
		plot(qq_1$x,qq_1$y,xlim=xy_scale*range(qq_1$x,qq_1$y),ylim=xy_scale*range(qq_1$x,qq_1$y),
		  xlab="",ylab="",asp=1)
		#fit_1 <- lm(Rep_1 ~ Ob_1, data = qq_1)
		#abline(fit_1,lty=3)	
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=1.2)		 		 
		mtext(side = 3, text = paste(text1), line = 0.5,cex=1)
		mtext(side = 1, text = "Observed", line = 2,cex=1)
		mtext(side = 2, text = "Simulated", line = 2,cex=1)							 
	    qq_2<-qqplot(Ob_2, Rep_2, plot.it = FALSE)
		plot(qq_2$x,qq_2$y,xlim=xy_scale*range(qq_2$x,qq_2$y),ylim=xy_scale*range(qq_2$x,qq_2$y),
		  xlab="",ylab="",asp=1)
		#fit_2 <- lm(Rep_2 ~ Ob_2, data = qq_2)
		#abline(fit_2,lty=3)	
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=1.2)		 		 
		mtext(side = 3, text = paste(text2), line = 0.5,cex=1)	
		mtext(side = 1, text = "Observed", line = 2,cex=1)
		mtext(side = 2, text = "Simulated", line = 2,cex=1)							 
   	    qq_3<-qqplot(Ob_3, Rep_3, plot.it = FALSE)
		plot(qq_3$x,qq_3$y,xlim=xy_scale*range(qq_3$x,qq_3$y),ylim=xy_scale*range(qq_3$x,qq_3$y),
		  xlab="",ylab="",asp=1)
		#fit_3 <- lm(Rep_3 ~ Ob_3, data = qq_3)
		#abline(fit_3,lty=3)
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=1.2)		 		 
		mtext(side = 3, text = paste(text3), line = 0.5,cex=1)	
		mtext(side = 1, text = "Observed", line = 2,cex=1)
		mtext(side = 2, text = "Simulated", line = 2,cex=1)							 
		qq_4<-qqplot(Ob_4, Rep_4, plot.it = FALSE)
		plot(qq_4$x,qq_4$y,xlim=xy_scale*range(qq_4$x,qq_4$y),ylim=xy_scale*range(qq_4$x,qq_4$y),
		  xlab="",ylab="",asp=1)
		#fit_4 <- lm(Rep_4 ~ Ob_4, data = qq_4)
		#abline(fit_4,lty=3)
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=1.2)		 		 
		mtext(side = 3, text = paste(text4), line = 0.5,cex=1)								 
		mtext(side = 1, text = "Observed", line = 2,cex=1)
		mtext(side = 2, text = "Simulated", line = 2,cex=1)								 
		par(mfrow = c(1,1),mar = c(0,0,0,0),oma=c(0,0,2,0),xpd=TRUE)
		title(main=paste(main),outer = T,cex.main=1) 							 								  						 												 
	}
	else{ 
		selStnNumber<-as.numeric(rfStatSelStn)
		selStn<-which(stnNumber==selStnNumber)
		SelStn_1<-totRfAmtInWS[,2+(selStn-1)*4]
		SelStn_2<-totRfAmtInWS[,3+(selStn-1)*4]
		SelStn_3<-totRfAmtInWS[,4+(selStn-1)*4]
		SelStn_4<-totRfAmtInWS[,5+(selStn-1)*4]
		ymax_1<-max(SelStn_1)								
		ymin_1<-min(SelStn_1)
		yext_1<-(ymax_1-ymin_1)*0.05							 
		ymax_2<-max(SelStn_2)								
		ymin_2<-min(SelStn_2)
		yext_2<-(ymax_2-ymin_2)*0.05							 
		ymax_3<-max(SelStn_3)								
		ymin_3<-min(SelStn_3)
		yext_3<-(ymax_3-ymin_3)*0.05							 
		ymax_4<-max(SelStn_4)								
		ymin_4<-min(SelStn_4)
		yext_4<-(ymax_4-ymin_4)*0.05			
		par(mfrow = c(2,2),mar = c(2,2,1,0.5),oma=c(4,1,2,0.5),xpd=TRUE,pty="s")					 	 		 																	 
		boxplot(SelStn_1[2:(nSim+1)],ylim=c(ymin_1-yext_1,ymax_1+yext_1),
			 xaxt='n')
		mtext(side = 1, text = paste(text1), line = 0.5,cex=1)
		points(SelStn_1[1],col="red",pch=21,xaxt='n')
		boxplot(SelStn_2[2:(nSim+1)],ylim=c(ymin_2-yext_2,ymax_2+yext_2),
			 xaxt='n')
		mtext(side = 1, text = paste(text2), line = 0.5,cex=1)
		points(SelStn_2[1],col="red",pch=21,xaxt='n')							 							 
		boxplot(SelStn_3[2:(nSim+1)],ylim=c(ymin_3-yext_3,ymax_3+yext_3),
			 xaxt='n')		
        mtext(side = 1, text = paste(text3), line = 0.5,cex=1)									
		points(SelStn_3[1],col="red",pch=21,xaxt='n')	
        boxplot(SelStn_4[2:(nSim+1)],ylim=c(ymin_4-yext_4,ymax_4+yext_4),
			 xaxt='n')
		mtext(side = 1, text = paste(text4), line = 0.5,cex=1)
		points(SelStn_4[1],col="red",pch=21,xaxt='n')
		par(mfg=c(1,1))
		boxplot(mean(SelStn_1[2:(nSim+1)]),ylim=c(ymin_1-yext_1,ymax_1+yext_1),border=2,lwd=0.5,yaxt='n')							 
		boxplot(mean(SelStn_2[2:(nSim+1)]),ylim=c(ymin_2-yext_2,ymax_2+yext_2),border=2,lwd=0.5,yaxt='n')
		boxplot(mean(SelStn_3[2:(nSim+1)]),ylim=c(ymin_3-yext_3,ymax_3+yext_3),border=2,lwd=0.5,yaxt='n')
		boxplot(mean(SelStn_4[2:(nSim+1)]),ylim=c(ymin_4-yext_4,ymax_4+yext_4),border=2,lwd=0.5,yaxt='n')							 
		par(mfrow = c(1,1),mar = c(0,0,0,0),oma=c(0,0,2,0),xpd=TRUE)
		title(main=paste(main, "at station",rfStatSelStn),outer = T,cex.main=1) 							 
		legend("bottom", inset=c(-0.1,-0.1),legend = c("observed","simulations mean"),col=c("red","red"),lty=c(0,1),lwd=c(0,1),pch=c(21,NA),
			bg = "white", horiz=TRUE,cex=1,bty="n")		
	}
}
rfStatInAYearPlotFun<-function(scanIndex1,scanIndex2,scanIndex3,main,nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength){
	 #scanIndex1<-1;scanIndex2<-0;scanIndex3<-2 for number of wet days in a year
	 #scanIndex1<-3;scanIndex2<-0;scanIndex3<-2 for maximum wet spell length in a year
	 #scanIndex1<-5;scanIndex2<-0;scanIndex3<-1 for maximum dry spell length in a year
	 #scanIndex1<-4;scanIndex2<-0;scanIndex3<-2 for average number of wet spells>1 in a year
	 #scanIndex1<-5;scanIndex1<-0;scanIndex3<-1 for average number of dry spells >1 in a year
	 #scanIndex1<-0;scanIndex2<-0;scanIndex3<-2 for max rf amt in a year
	 #scanIndex1<-2;scanIndex2<-0;scanIndex3<-2 for avg rf amt in a year
	 if (rfStatSelStn=="All stations"){
		if (nStation==1){
			iStn<-1
			med_RfStat<-apply(matrix(scan(file=statFile,
				skip=(iStn-1)*(5*(nYrStat+2)+2*(nYrStat+1))+11*(nSim+2)+3*(nSim+3)+6+scanIndex1*(nYrStat+2)+scanIndex2*(nYrStat+1)+scanIndex3,nlines=2,quiet = TRUE),nrow=2,ncol=8,byrow=TRUE),2,median)
			med_RfStatRep<-med_RfStat[7]
			med_RfStatOb<-med_RfStat[5]
		}
		else {
			iStn<-1
			med_RfStat<-apply(matrix(scan(file=statFile,
				skip=(iStn-1)*(5*(nYrStat+2)+2*(nYrStat+1))+11*(nSim+2)+3*(nSim+3)+(2+(nStation-1)*nStation-sum(1:(nStation-1)))+4*(1+(nStation-1)*nStation-sum(1:(nStation-1)))+scanIndex1*(nYrStat+2)+scanIndex2*(nYrStat+1)+scanIndex3,nlines=2,quiet = TRUE),nrow=2,ncol=8,byrow=TRUE),2,median)
					  
			for (iStn in 2:nStation){ 
				imed_RfStat<-apply(matrix(scan(file=statFile,
						skip=(iStn-1)*(5*(nYrStat+2)+2*(nYrStat+1))+11*(nSim+2)+3*(nSim+3)+(2+(nStation-1)*nStation-sum(1:(nStation-1)))+4*(1+(nStation-1)*nStation-sum(1:(nStation-1)))+scanIndex1*(nYrStat+2)+scanIndex2*(nYrStat+1)+scanIndex3,nlines=2,quiet = TRUE),
						nrow=2,ncol=8,byrow=TRUE),2,median)								   
				med_RfStat<-rbind(med_RfStat,imed_RfStat)						
			}
			med_RfStatRep<-med_RfStat[,7]
			med_RfStatOb<-med_RfStat[,5]
		}		

		qq<-qqplot(med_RfStatOb, med_RfStatRep, plot.it = FALSE)		
		par(pty="s")
		plot(qq$x,qq$y,xlim=xy_scale*range(qq$x,qq$y),ylim=xy_scale*range(qq$x,qq$y),
		  xlab = "Median of Observed",ylab = "Simulated",lwd=linewidth,
		  main=paste(main),asp=1,cex.main=fontsize,
		  cex.lab=fontsize, cex.axis=fontsize,cex=fontsize)
		#fit <- lm(med_RfStatRep ~ med_RfStatOb, data = qq)
		#abline(fit,lty=3,cex=1.2)
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,lwd=linewidth,cex=fontsize)		 		
	}
	else{ 
		selStnNumber<-as.numeric(rfStatSelStn)
		selStn<-which(stnNumber==selStnNumber)
		if (nStation==1){
			RfStatInAYearSelStn<-matrix(scan(file=statFile,
				skip=(selStn-1)*(5*(nYrStat+2)+2*(nYrStat+1))+11*(nSim+2)+3*(nSim+3)+6+scanIndex1*(nYrStat+2)+scanIndex2*(nYrStat+1)+scanIndex3,nlines=nYrStat,quiet = TRUE),
				nrow=nYrStat,ncol=8,byrow=TRUE)
		}
		else {
			RfStatInAYearSelStn<-matrix(scan(file=statFile,
				skip=(selStn-1)*(5*(nYrStat+2)+2*(nYrStat+1))+11*(nSim+2)+3*(nSim+3)+(2+(nStation-1)*nStation-sum(1:(nStation-1)))+4*(1+(nStation-1)*nStation-sum(1:(nStation-1)))+scanIndex1*(nYrStat+2)+scanIndex2*(nYrStat+1)+scanIndex3,nlines=nYrStat,quiet = TRUE),
				nrow=nYrStat,ncol=8,byrow=TRUE)
		}

		ymax<-max(RfStatInAYearSelStn[,5:8])
		ymin<-min(RfStatInAYearSelStn[,5:8])
		yRange<-ymax-ymin	
		xmax<-max(RfStatInAYearSelStn[,3:4])
		xmin<-min(RfStatInAYearSelStn[,3:4])														 
        par(mar=c(6,3,4,2),xpd=TRUE,pty="s")
		if (mainLength>30) {
			plot(RfStatInAYearSelStn[,3],RfStatInAYearSelStn[,5],xlim=c(xmin,xmax),ylim=c(ymin-0.05*yRange,ymax+0.07*yRange),
				col="black",pch=21,xaxt='n',lwd=linewidth,main=paste(main,"\nat station",rfStatSelStn),
				xlab="Cumulative Probability (%)",ylab="",cex.main=fontsize,cex.lab=fontsize, cex.axis=fontsize,cex=fontsize)
		}
		else {
			plot(RfStatInAYearSelStn[,3],RfStatInAYearSelStn[,5],xlim=c(xmin,xmax),ylim=c(ymin-0.05*yRange,ymax+0.07*yRange),
				col="black",pch=21,xaxt='n',lwd=linewidth,main=paste(main,"at station",rfStatSelStn),
				xlab="Cumulative Probability (%)",ylab="",cex.main=fontsize,cex.lab=fontsize, cex.axis=fontsize,cex=fontsize)
		}
		lines(RfStatInAYearSelStn[,4],RfStatInAYearSelStn[,6],col="red",lty=2,lwd=linewidth,xaxt='n',cex=fontsize)
		lines(RfStatInAYearSelStn[,4],RfStatInAYearSelStn[,7],col="black",lty=1,lwd=linewidth,xaxt='n',cex=fontsize)
		lines(RfStatInAYearSelStn[,4],RfStatInAYearSelStn[,8],col="red",lty=2,lwd=linewidth,xaxt='n',cex=fontsize)
		xTickLocation<-ceiling(xmin*10):floor(xmax*10)
		axis(1, at = xTickLocation/10, labels =paste(xTickLocation*10,"%"),cex=fontsize,cex.axis=fontsize)	
		legend("topright", legend = c("observed","5%th simulated","50%th simulated","95%th simulated"),
			col=c("black","red","black","red"),lty=c(0,2,1,2),lwd=c(linewidth,linewidth,linewidth,linewidth),
			pch=c(21,NA,NA,NA),bg = "white",ncol=1,cex=fontsize,bty="n")
		
	}
}	
#Plot maxm wet & dry spell lengths & 5th% rf amt 
maxSpelllength5thRfAmtPlotFun<-function(maxSpelllength5thRfAmt,fromCol,main,nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength){
	#plot the maxm wet & dry spell length
	#fromCol=2 for maximum wet spell length
	#fromCol=3 for maxium dry spell length
	#fromCol=4 for 5th rf amt
	if (rfStatSelStn=="All stations"){
		#ColIndex<-seq(from=2,to=1+nStation*3,by=3)#maximum wet spell length
		#ColIndex<-seq(from=3,to=1+nStation*3,by=3)#maximum dry spell length
		#ColIndex<-seq(from=4,to=1+nStation*3,by=3)#5th rf amt
		ColIndex<-seq(from=fromCol,to=1+nStation*3,by=3)
		if (nSim==1){
			Rep<-maxSpelllength5thRfAmt[2:(nSim+1),ColIndex]
		}
		else if (nStation==1){
			Rep<-mean(maxSpelllength5thRfAmt[2:(nSim+1),ColIndex])
		}
		else{
			Rep<-apply(maxSpelllength5thRfAmt[2:(nSim+1),ColIndex],2,mean)	
		}
		Ob<-maxSpelllength5thRfAmt[1,ColIndex]						 
		qq<-qqplot(Ob, Rep, plot.it = FALSE)		
		par(pty="s")
		plot(qq$x,qq$y,xlim=xy_scale*range(qq$x,qq$y),ylim=xy_scale*range(qq$x,qq$y),
		 xlab = "Observed",ylab = "Simulated",main=main,asp=1,lwd=linewidth,
		 cex.main=fontsize,cex.lab=fontsize, cex.axis=fontsize,cex=fontsize)
		#fit <- lm(Rep ~ Ob, data = qq)
		#abline(fit,lty=3,cex=1.2)	
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)		 		 		
	}
	else{ 
		selStnNumber<-as.numeric(rfStatSelStn)
		selStn<-which(stnNumber==selStnNumber)		 
		#maxSpelllengthSelStn<-maxSpelllength5thRfAmt[,2+(selStn-1)*3]#maximum wet spell length
		#maxSpelllengthSelStn<-maxSpelllength5thRfAmt[,3+(selStn-1)*3]#maximum dry spell length
		#maxSpelllengthSelStn<-maxSpelllength5thRfAmt[,4+(selStn-1)*3]#5th rf amt
	    maxSpelllength5thRfAmtSelStn<-maxSpelllength5thRfAmt[,fromCol+(selStn-1)*3]
		ymax<-max(maxSpelllength5thRfAmtSelStn)
		ymin<-min(maxSpelllength5thRfAmtSelStn)
		yext<-(ymax-ymin)*0.05	    
        par(mar=c(5,6,4,4),xpd=TRUE,pty="s")
		if (mainLength>30){
			boxplot(maxSpelllength5thRfAmtSelStn[2:(nSim+1)],ylim=c(ymin-yext,ymax+yext),xaxt='n',
				main=paste(main, "\nat station",rfStatSelStn),cex.main=fontsize,lwd=linewidth,
				xlab="",ylab="Statistic Value",cex.lab=fontsize, cex.axis=fontsize,cex=fontsize)
		}
		else{
			boxplot(maxSpelllength5thRfAmtSelStn[2:(nSim+1)],ylim=c(ymin-yext,ymax+yext),xaxt='n',
				main=paste(main, "at station",rfStatSelStn),cex.main=fontsize,lwd=linewidth,
				xlab="",ylab="Statistic Value",cex.lab=fontsize, cex.axis=fontsize,cex=fontsize)
		}
		points(maxSpelllength5thRfAmtSelStn[1],col="red",pch=21,cex=fontsize)									 
		par(mfg=c(1,1),pty="s")
		boxplot(mean(maxSpelllength5thRfAmtSelStn[2:(nSim+1)]),ylim=c(ymin-yext,ymax+yext),border=2,lwd=linewidth,yaxt='n',
			cex.main=fontsize,cex.lab=fontsize, cex.axis=fontsize,cex=fontsize)	
		legend("bottom", inset=c(-0.15,-0.15),legend = c("observed","simulations mean"),col=c("red","red"),
			lty=c(0,1),lwd=c(linewidth,linewidth+1),pch=c(21,NA),bg = "white", horiz=TRUE,cex=fontsize, bty = "n" )					
	}	
}		
avgOccW_DSpellsPlotFun<-function(avgOccW_DSpells,text1,text2,text3,text4,main,nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth){
	ColInd_1<-seq(from=2,to=1+nStation*4,by=4) #length = 1 day for WS and DS
	ColInd_2<-seq(from=3,to=1+nStation*4,by=4) #length = 2-4 days for WS and 2-9 days for DS
	ColInd_3<-seq(from=4,to=1+nStation*4,by=4) #length = 5-7 days for WS and 9-18 days for DS
	ColInd_4<-seq(from=5,to=1+nStation*4,by=4) #length >7 days for WS and >18 days for DS
	if (nSim==1){
		Rep_1<-avgOccW_DSpells[2:(nSim+1),ColInd_1]
		Rep_2<-avgOccW_DSpells[2:(nSim+1),ColInd_2]
		Rep_3<-avgOccW_DSpells[2:(nSim+1),ColInd_3]
		Rep_4<-avgOccW_DSpells[2:(nSim+1),ColInd_4]
	}
	else if (nStation==1){
		Rep_1<-mean(avgOccW_DSpells[2:(nSim+1),ColInd_1])
		Rep_2<-mean(avgOccW_DSpells[2:(nSim+1),ColInd_2])
		Rep_3<-mean(avgOccW_DSpells[2:(nSim+1),ColInd_3])
		Rep_4<-mean(avgOccW_DSpells[2:(nSim+1),ColInd_4])
	}
	else{
		Rep_1<-apply(avgOccW_DSpells[2:(nSim+1),ColInd_1],2,mean)
		Rep_2<-apply(avgOccW_DSpells[2:(nSim+1),ColInd_2],2,mean)
		Rep_3<-apply(avgOccW_DSpells[2:(nSim+1),ColInd_3],2,mean)
		Rep_4<-apply(avgOccW_DSpells[2:(nSim+1),ColInd_4],2,mean)
	}
						 
	Ob_1<-avgOccW_DSpells[1,ColInd_1]
	Ob_2<-avgOccW_DSpells[1,ColInd_2]
	Ob_3<-avgOccW_DSpells[1,ColInd_3]
	Ob_4<-avgOccW_DSpells[1,ColInd_4]
	if (rfStatSelStn=="All stations"){		
		par(mfrow = c(2,2),mar = c(4,4,2,1),oma=c(1.5,1.5,3,1),xpd=FALSE,pty="s")
        qq_1<-qqplot(Ob_1, Rep_1, plot.it = FALSE)
		plot(qq_1$x,qq_1$y,xlim=xy_scale*range(qq_1$x,qq_1$y),ylim=xy_scale*range(qq_1$x,qq_1$y),
		  xlab="",ylab="",cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)	
		#fit_1 <- lm(Rep_1 ~ Ob_1, data = qq_1)
		#abline(fit_1,lty=3)		
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)		 		 
		mtext(side = 3, text = paste(text1), line = 0.5,cex=fontsize)
		mtext(side = 1, text = "Observed", line = 3,cex=fontsize)
		mtext(side = 2, text = "Simulated", line = 3,cex=fontsize)							 
	    qq_2<-qqplot(Ob_2, Rep_2, plot.it = FALSE)
		plot(qq_2$x,qq_2$y,xlim=xy_scale*range(qq_2$x,qq_2$y),ylim=xy_scale*range(qq_2$x,qq_2$y),
		  xlab="",ylab="",cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)	
		#fit_2 <- lm(Rep_2 ~ Ob_2, data = qq_2)
		#abline(fit_2,lty=3)		
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)			 
		mtext(side = 3, text = paste(text2), line = 0.5,cex=fontsize)	
		mtext(side = 1, text = "Observed", line = 3,cex=fontsize)
		mtext(side = 2, text = "Simulated", line = 3,cex=fontsize)							 
   	    qq_3<-qqplot(Ob_3, Rep_3, plot.it = FALSE)
		plot(qq_3$x,qq_3$y,xlim=xy_scale*range(qq_3$x,qq_3$y),ylim=xy_scale*range(qq_3$x,qq_3$y),
		  xlab="",ylab="",cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)	
		#fit_3 <- lm(Rep_3 ~ Ob_3, data = qq_3)
		#abline(fit_3,lty=3)	
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)			 		 
		mtext(side = 3, text = paste(text3), line = 0.5,cex=fontsize)	
		mtext(side = 1, text = "Observed", line = 3,cex=fontsize)
		mtext(side = 2, text = "Simulated", line = 3,cex=fontsize)							 
		qq_4<-qqplot(Ob_4, Rep_4, plot.it = FALSE)
		plot(qq_4$x,qq_4$y,xlim=xy_scale*range(qq_4$x,qq_4$y),ylim=xy_scale*range(qq_4$x,qq_4$y),
		  xlab="",ylab="",cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)	
		#fit_4 <- lm(Rep_4 ~ Ob_4, data = qq_4)
		#abline(fit_4,lty=3)	
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)		 		 
		mtext(side = 3, text = paste(text4), line = 0.5,cex=fontsize)								 
		mtext(side = 1, text = "Observed", line = 3,cex=fontsize)
		mtext(side = 2, text = "Simulated", line = 3,cex=fontsize)								 
		par(mfrow = c(1,1),mar = c(0,0,0,0),oma=c(0,0,2,0),xpd=TRUE)
		title(main=paste(main),outer = T,cex.main=fontsize+0.3) 							 								  						 												 
	}
	else{ 
		selStnNumber<-as.numeric(rfStatSelStn)
		selStn<-which(stnNumber==selStnNumber)
		SelStn_1<-avgOccW_DSpells[,2+(selStn-1)*4]
		SelStn_2<-avgOccW_DSpells[,3+(selStn-1)*4]
		SelStn_3<-avgOccW_DSpells[,4+(selStn-1)*4]
		SelStn_4<-avgOccW_DSpells[,5+(selStn-1)*4]
		ymax_1<-max(SelStn_1)								
		ymin_1<-min(SelStn_1)
		yext_1<-(ymax_1-ymin_1)*0.05							 
		ymax_2<-max(SelStn_2)								
		ymin_2<-min(SelStn_2)
		yext_2<-(ymax_2-ymin_2)*0.05							 
		ymax_3<-max(SelStn_3)								
		ymin_3<-min(SelStn_3)
		yext_3<-(ymax_3-ymin_3)*0.05							 
		ymax_4<-max(SelStn_4)								
		ymin_4<-min(SelStn_4)
		yext_4<-(ymax_4-ymin_4)*0.05						
		par(mfrow = c(2,2),mar = c(1.5,2,1,1),oma=c(7,2,7,1),xpd=TRUE,pty="s")							 	 		 																	 
		boxplot(SelStn_1[2:(nSim+1)],ylim=c(ymin_1-yext_1,ymax_1+yext_1),
			 xaxt='n',cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)	
		mtext(side = 1, text = paste(text1), line = 0.5,cex=fontsize)
		points(SelStn_1[1],col="red",pch=21,xaxt='n',ces=fontsize)
		boxplot(SelStn_2[2:(nSim+1)],ylim=c(ymin_2-yext_2,ymax_2+yext_2),
			 xaxt='n',cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)	
		mtext(side = 1, text = paste(text2), line = 0.5,cex=fontsize)
		points(SelStn_2[1],col="red",pch=21,xaxt='n',ces=fontsize)							 							 
		boxplot(SelStn_3[2:(nSim+1)],ylim=c(ymin_3-yext_3,ymax_3+yext_3),
			 xaxt='n',cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)			
        mtext(side = 1, text = paste(text3), line = 0.5,cex=fontsize)									
		points(SelStn_3[1],col="red",pch=21,xaxt='n',ces=fontsize)	
        boxplot(SelStn_4[2:(nSim+1)],ylim=c(ymin_4-yext_4,ymax_4+yext_4),
			 xaxt='n',cex=fontsize,cex.lab=fontsize,cex.axis=fontsize,lwd=linewidth)	
		mtext(side = 1, text = paste(text4), line = 0.5,cex=fontsize)
		points(SelStn_4[1],col="red",pch=21,xaxt='n',ces=fontsize)
		par(mfg=c(1,1))
		boxplot(mean(SelStn_1[2:(nSim+1)]),ylim=c(ymin_1-yext_1,ymax_1+yext_1),border=2,lwd=0.5,yaxt='n')							 
		boxplot(mean(SelStn_2[2:(nSim+1)]),ylim=c(ymin_2-yext_2,ymax_2+yext_2),border=2,lwd=0.5,yaxt='n')
		boxplot(mean(SelStn_3[2:(nSim+1)]),ylim=c(ymin_3-yext_3,ymax_3+yext_3),border=2,lwd=0.5,yaxt='n')
		boxplot(mean(SelStn_4[2:(nSim+1)]),ylim=c(ymin_4-yext_4,ymax_4+yext_4),border=2,lwd=0.5,yaxt='n')							 
		par(mfrow = c(1,1),mar = c(0,0,0,0),oma=c(0,0,5,0),xpd=TRUE)
		#Main title is written in two lines
		title(main=paste(main, c("","at station"),c("",rfStatSelStn)),outer = T,cex.main=fontsize+0.3) 							 
		legend("bottom", inset=c(-0.1,-0.1),legend = c("observed","simulations mean"),
			col=c("red","red"),lty=c(0,1),lwd=c(0,linewidth),pch=c(21,NA),
			bg = "white", horiz=TRUE,cex=fontsize,bty="n")		
	}
}	
avgOccW_DSpellsPlotSaveFun<-function(avgOccW_DSpells,text1,text2,text3,text4,main,nSim,nStation,rfStatSelStn,stnNumber){
	ColInd_1<-seq(from=2,to=1+nStation*4,by=4) #length = 1 day for WS and DS
	ColInd_2<-seq(from=3,to=1+nStation*4,by=4) #length = 2-4 days for WS and 2-9 days for DS
	ColInd_3<-seq(from=4,to=1+nStation*4,by=4) #length = 5-7 days for WS and 9-18 days for DS
	ColInd_4<-seq(from=5,to=1+nStation*4,by=4) #length >7 days for WS and >18 days for DS
	if (nSim==1){
		Rep_1<-avgOccW_DSpells[2:(nSim+1),ColInd_1]
		Rep_2<-avgOccW_DSpells[2:(nSim+1),ColInd_2]
		Rep_3<-avgOccW_DSpells[2:(nSim+1),ColInd_3]
		Rep_4<-avgOccW_DSpells[2:(nSim+1),ColInd_4]
	}
	else if (nStation==1){
		Rep_1<-mean(avgOccW_DSpells[2:(nSim+1),ColInd_1])
		Rep_2<-mean(avgOccW_DSpells[2:(nSim+1),ColInd_2])
		Rep_3<-mean(avgOccW_DSpells[2:(nSim+1),ColInd_3])
		Rep_4<-mean(avgOccW_DSpells[2:(nSim+1),ColInd_4])
	}
	else{
		Rep_1<-apply(avgOccW_DSpells[2:(nSim+1),ColInd_1],2,mean)
		Rep_2<-apply(avgOccW_DSpells[2:(nSim+1),ColInd_2],2,mean)
		Rep_3<-apply(avgOccW_DSpells[2:(nSim+1),ColInd_3],2,mean)
		Rep_4<-apply(avgOccW_DSpells[2:(nSim+1),ColInd_4],2,mean)	
	}
	
					 
	Ob_1<-avgOccW_DSpells[1,ColInd_1]
	Ob_2<-avgOccW_DSpells[1,ColInd_2]
	Ob_3<-avgOccW_DSpells[1,ColInd_3]
	Ob_4<-avgOccW_DSpells[1,ColInd_4]
	if (rfStatSelStn=="All stations"){		
		par(mfrow = c(2,2),mar = c(3.5,3.5,2,1),oma=c(1.5,1.5,3,1),xpd=FALSE,pty="s")
        qq_1<-qqplot(Ob_1, Rep_1, plot.it = FALSE)
		plot(qq_1$x,qq_1$y,xlim=xy_scale*range(qq_1$x,qq_1$y),ylim=xy_scale*range(qq_1$x,qq_1$y),
		  xlab="",ylab="")
		#fit_1 <- lm(Rep_1 ~ Ob_1, data = qq_1)
		#abline(fit_1,lty=3)
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=1.2)		 		 
		mtext(side = 3, text = paste(text1), line = 0.5,cex=1)
		mtext(side = 1, text = "Observed", line = 2,cex=1)
		mtext(side = 2, text = "Simulated", line = 2,cex=1)							 
	    qq_2<-qqplot(Ob_2, Rep_2, plot.it = FALSE)
		plot(qq_2$x,qq_2$y,xlim=xy_scale*range(qq_2$x,qq_2$y),ylim=xy_scale*range(qq_2$x,qq_2$y),
		  xlab="",ylab="")
		#fit_2 <- lm(Rep_2 ~ Ob_2, data = qq_2)
		#abline(fit_2,lty=3)	
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=1.2)		 		 
		mtext(side = 3, text = paste(text2), line = 0.5,cex=1)	
		mtext(side = 1, text = "Observed", line = 2,cex=1)
		mtext(side = 2, text = "Simulated", line = 2,cex=1)							 
   	    qq_3<-qqplot(Ob_3, Rep_3, plot.it = FALSE)
		plot(qq_3$x,qq_3$y,xlim=xy_scale*range(qq_3$x,qq_3$y),ylim=xy_scale*range(qq_3$x,qq_3$y),
		  xlab="",ylab="")
		#fit_3 <- lm(Rep_3 ~ Ob_3, data = qq_3)
		#abline(fit_3,lty=3)	
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=1.2)		 		 
		mtext(side = 3, text = paste(text3), line = 0.5,cex=1)	
		mtext(side = 1, text = "Observed", line = 2,cex=1)
		mtext(side = 2, text = "Simulated", line = 2,cex=1)							 
		qq_4<-qqplot(Ob_4, Rep_4, plot.it = FALSE)
		plot(qq_4$x,qq_4$y,xlim=xy_scale*range(qq_4$x,qq_4$y),ylim=xy_scale*range(qq_4$x,qq_4$y),
		  xlab="",ylab="")
		#fit_4 <- lm(Rep_4 ~ Ob_4, data = qq_4)
		#abline(fit_4,lty=3)
		#Add a diagonal line to the scatter plot
		lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=1.2)		 		 
		mtext(side = 3, text = paste(text4), line = 0.5,cex=1)								 
		mtext(side = 1, text = "Observed", line = 2,cex=1)
		mtext(side = 2, text = "Simulated", line = 2,cex=1)								 
		par(mfrow = c(1,1),mar = c(0,0,0,0),oma=c(0,0,2,0),xpd=TRUE)
		title(main=paste(main),outer = T,cex.main=1) 							 								  						 												 
	}
	else{ 
		selStnNumber<-as.numeric(rfStatSelStn)
		selStn<-which(stnNumber==selStnNumber)
		SelStn_1<-avgOccW_DSpells[,2+(selStn-1)*4]
		SelStn_2<-avgOccW_DSpells[,3+(selStn-1)*4]
		SelStn_3<-avgOccW_DSpells[,4+(selStn-1)*4]
		SelStn_4<-avgOccW_DSpells[,5+(selStn-1)*4]
		ymax_1<-max(SelStn_1)								
		ymin_1<-min(SelStn_1)
		yext_1<-(ymax_1-ymin_1)*0.05							 
		ymax_2<-max(SelStn_2)								
		ymin_2<-min(SelStn_2)
		yext_2<-(ymax_2-ymin_2)*0.05							 
		ymax_3<-max(SelStn_3)								
		ymin_3<-min(SelStn_3)
		yext_3<-(ymax_3-ymin_3)*0.05							 
		ymax_4<-max(SelStn_4)								
		ymin_4<-min(SelStn_4)
		yext_4<-(ymax_4-ymin_4)*0.05		
		par(mfrow = c(2,2),mar = c(2,2,1,0.5),oma=c(4,1,2,0.5),xpd=TRUE,pty="s")							 	 		 																	 
		boxplot(SelStn_1[2:(nSim+1)],ylim=c(ymin_1-yext_1,ymax_1+yext_1),
			 xaxt='n')
		mtext(side = 1, text = paste(text1), line = 0.5,cex=1)
		points(SelStn_1[1],col="red",pch=21,xaxt='n')
		boxplot(SelStn_2[2:(nSim+1)],ylim=c(ymin_2-yext_2,ymax_2+yext_2),
			 xaxt='n')
		mtext(side = 1, text = paste(text2), line = 0.5,cex=1)
		points(SelStn_2[1],col="red",pch=21,xaxt='n')							 							 
		boxplot(SelStn_3[2:(nSim+1)],ylim=c(ymin_3-yext_3,ymax_3+yext_3),
			 xaxt='n')		
        mtext(side = 1, text = paste(text3), line = 0.5,cex=1)									
		points(SelStn_3[1],col="red",pch=21,xaxt='n')	
        boxplot(SelStn_4[2:(nSim+1)],ylim=c(ymin_4-yext_4,ymax_4+yext_4),
			 xaxt='n')
		mtext(side = 1, text = paste(text4), line = 0.5,cex=1)
		points(SelStn_4[1],col="red",pch=21,xaxt='n')
		par(mfg=c(1,1))
		boxplot(mean(SelStn_1[2:(nSim+1)]),ylim=c(ymin_1-yext_1,ymax_1+yext_1),border=2,lwd=0.5,yaxt='n')							 
		boxplot(mean(SelStn_2[2:(nSim+1)]),ylim=c(ymin_2-yext_2,ymax_2+yext_2),border=2,lwd=0.5,yaxt='n')
		boxplot(mean(SelStn_3[2:(nSim+1)]),ylim=c(ymin_3-yext_3,ymax_3+yext_3),border=2,lwd=0.5,yaxt='n')
		boxplot(mean(SelStn_4[2:(nSim+1)]),ylim=c(ymin_4-yext_4,ymax_4+yext_4),border=2,lwd=0.5,yaxt='n')							 
		par(mfrow = c(1,1),mar = c(0,0,0,0),oma=c(0,0,2,0),xpd=TRUE)
		title(main=paste(main, "at station",rfStatSelStn),outer = T,cex.main=1) 							 
		legend("bottom", inset=c(-0.1,-0.1),legend = c("observed","simulations mean"),
			col=c("red","red"),lty=c(0,1),lwd=c(0,1),pch=c(21,NA),
			bg = "white", horiz=TRUE,cex=1,bty="n")		
	}
}
annualCrsCorrlPlotFun<-function(scanIndex1,scanIndex2,scanIndex3,main,nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth){
	#scanIndex1<-0, scanIndex2<-0, scanIndex3<-2, for daily log-odds ratio on seasonal and annual basis
	#scanIndex1<-1, scanIndex2<-0, scanIndex3<-1, for daily crs-corrl of rf-wet days on seas & annual basis
	#scanIndex1<-1, scanIndex2<-1, scanIndex3<-1, for daily crs-corrl of rf-all days on seas & annual basis
	#scanIndex1<-1, scanIndex2<-2, scanIndex3<-1, for cross-corrl of number wet days in season and year
	#scanIndex1<-1, scanIndex2<-3, scanIndex3<-1, for cross-corrl of seasonal & annual rainfall
	seasonalAnuualStat<-matrix(scan(file=statFile,
	skip=11*(2+nSim)+3*(3+nSim)+scanIndex1*(2+(nStation-1)*nStation-sum(1:(nStation-1)))+scanIndex2*(1+(nStation-1)*nStation-sum(1:(nStation-1)))+scanIndex3,
	nlines=(nStation-1)*nStation-sum(1:(nStation-1)),quiet = TRUE),
	nrow=(nStation-1)*nStation-sum(1:(nStation-1)),ncol=22,byrow=TRUE)
	Rep<-seasonalAnuualStat[,21]
	Ob<-seasonalAnuualStat[,19]
	qq<-qqplot(Ob,Rep, plot.it = FALSE)	
    par(pty="s")
	plot(qq$x,qq$y,xlim=xy_scale*range(qq$x,qq$y),ylim=xy_scale*range(qq$x,qq$y),
	 xlab = "Observed",ylab = "Simulated",main=paste(main),lwd=linewidth,
	 cex.main=fontsize,cex.lab=fontsize, cex.axis=fontsize,cex=fontsize)
	#fit <- lm(Rep ~ Ob, data = qq)
	#abline(fit,lty=3,cex=1.2)	
	#Add a diagonal line to the scatter plot
	lines(par()$usr[1:2],par()$usr[3:4],lty=3,lwd=linewidth,cex=fontsize)		 	
}
seasonalCrsCorrlPlotFun<-function(scanIndex1,scanIndex2,scanIndex3,main,nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth){
	#scanIndex1<-0, scanIndex2<-0, scanIndex3<-2, for daily log-odds ratio on seasonal and annual basis
	#scanIndex1<-1, scanIndex2<-0, scanIndex3<-1, for daily crs-corrl of rf-wet days on seas & annual basis
	#scanIndex1<-1, scanIndex2<-1, scanIndex3<-1, for daily crs-corrl of rf-all days on seas & annual basis
	#scanIndex1<-1, scanIndex2<-2, scanIndex3<-1, for cross-corrl of number wet days in season and year
	#scanIndex1<-1, scanIndex2<-3, scanIndex3<-1, for cross-corrl of seasonal & annual rainfall
	seasonalAnuualStat<-matrix(scan(file=statFile,
					skip=11*(2+nSim)+3*(3+nSim)+scanIndex1*(2+(nStation-1)*nStation-sum(1:(nStation-1)))+scanIndex2*(1+(nStation-1)*nStation-sum(1:(nStation-1)))+scanIndex3,nlines=(nStation-1)*nStation-sum(1:(nStation-1)),quiet = TRUE),
					nrow=(nStation-1)*nStation-sum(1:(nStation-1)),ncol=22,byrow=TRUE)
	SpringRep<-seasonalAnuualStat[,13]
	SummerRep<-seasonalAnuualStat[,17]
	AutumnRep<-seasonalAnuualStat[,5]
	WinterRep<-seasonalAnuualStat[,9]
	SpringOb<-seasonalAnuualStat[,11]
	SummerOb<-seasonalAnuualStat[,15]
	AutumnOb<-seasonalAnuualStat[,3]
	WinterOb<-seasonalAnuualStat[,7]							 	
	par(mfrow = c(2,2),mar = c(4,4,2,1),oma=c(1.5,1.5,3,1),xpd=FALSE,pty="s")	
    qq_au<-qqplot(AutumnOb, AutumnRep, plot.it = FALSE)
	plot(qq_au$x,qq_au$y,xlim=xy_scale*range(qq_au$x,qq_au$y),ylim=xy_scale*range(qq_au$x,qq_au$y),
		xlab="",ylab="",asp=1,cex.lab=fontsize, cex.axis=fontsize,cex=fontsize)
	#fit_au <- lm(AutumnRep ~ AutumnOb, data = qq_au)
	#abline(fit_au,lty=3)
	#Add a diagonal line to the scatter plot
	lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)			 	 
	mtext(side = 3, text = "Autumn", line = 0.5,cex=fontsize)
	mtext(side = 1, text = "Observed", line = 3,cex=fontsize)
	mtext(side = 2, text = "Simulated", line = 3,cex=fontsize)
	qq_wi<-qqplot(WinterOb, WinterRep, plot.it = FALSE)
	plot(qq_wi$x,qq_wi$y,xlim=xy_scale*range(qq_wi$x,qq_wi$y),ylim=xy_scale*range(qq_wi$x,qq_wi$y),
		xlab="",ylab="",asp=1,cex.lab=fontsize, cex.axis=fontsize,cex=fontsize)
	#fit_wi <- lm(WinterRep ~ WinterOb, data = qq_wi)
	#abline(fit_wi,lty=3)	
	#Add a diagonal line to the scatter plot
	lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)	 	 
	mtext(side = 3, text = "Winter", line = 0.5,cex=fontsize)
	mtext(side = 1, text = "Observed", line = 3,cex=fontsize)
  	mtext(side = 2, text = "Simulated", line = 3,cex=fontsize)							 
	qq_sp<-qqplot(SpringOb, SpringRep, plot.it = FALSE)
	plot(qq_sp$x,qq_sp$y,xlim=xy_scale*range(qq_sp$x,qq_sp$y),ylim=xy_scale*range(qq_sp$x,qq_sp$y),
		xlab="",ylab="",asp=1,cex.lab=fontsize, cex.axis=fontsize,cex=fontsize)
	#fit_sp <- lm(SpringRep ~ SpringOb, data = qq_sp)
	#abline(fit_sp,lty=3)
	#Add a diagonal line to the scatter plot
	lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)		 	 
	mtext(side = 3, text = "Spring", line = 0.5,cex=fontsize)
	mtext(side = 1, text = "Observed", line = 3,cex=fontsize)
	mtext(side = 2, text = "Simulated", line = 3,cex=fontsize)							 
	qq_su<-qqplot(SummerOb, SummerRep, plot.it = FALSE)
	plot(qq_su$x,qq_su$y,xlim=xy_scale*range(qq_su$x,qq_su$y),ylim=xy_scale*range(qq_su$x,qq_su$y),
		xlab="",ylab="",asp=1,cex.lab=fontsize, cex.axis=fontsize,cex=fontsize)
	#fit_su <- lm(SummerRep ~ SummerOb, data = qq_su)
	#abline(fit_su,lty=3)
	#Add a diagonal line to the scatter plot
	lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)			 	 
	mtext(side = 3, text = "Summer", line = 0.5,cex=fontsize)
	mtext(side = 1, text = "Observed", line = 3,cex=fontsize)
	mtext(side = 2, text = "Simulated", line = 3,cex=fontsize)						 
	par(mfrow = c(1,1),mar = c(0,0,0,0),oma=c(0,0,2,0),xpd=TRUE)
	title(main=paste(main),outer = T,cex.main=fontsize+0.3) 							 		
}
seasonalCrsCorrlSavePlotFun<-function(scanIndex1,scanIndex2,scanIndex3,main,nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth){
	#scanIndex1<-0, scanIndex2<-0, scanIndex3<-2, for daily log-odds ratio on seasonal and annual basis
	#scanIndex1<-1, scanIndex2<-0, scanIndex3<-1, for daily crs-corrl of rf-wet days on seas & annual basis
	#scanIndex1<-1, scanIndex2<-1, scanIndex3<-1, for daily crs-corrl of rf-all days on seas & annual basis
	#scanIndex1<-1, scanIndex2<-2, scanIndex3<-1, for cross-corrl of number wet days in season and year
	#scanIndex1<-1, scanIndex2<-3, scanIndex3<-1, for cross-corrl of seasonal & annual rainfall
	seasonalAnuualStat<-matrix(scan(file=statFile,
					skip=11*(2+nSim)+3*(3+nSim)+scanIndex1*(2+(nStation-1)*nStation-sum(1:(nStation-1)))+scanIndex2*(1+(nStation-1)*nStation-sum(1:(nStation-1)))+scanIndex3,nlines=(nStation-1)*nStation-sum(1:(nStation-1)),quiet = TRUE),
					nrow=(nStation-1)*nStation-sum(1:(nStation-1)),ncol=22,byrow=TRUE)
	SpringRep<-seasonalAnuualStat[,13]
	SummerRep<-seasonalAnuualStat[,17]
	AutumnRep<-seasonalAnuualStat[,5]
	WinterRep<-seasonalAnuualStat[,9]
	SpringOb<-seasonalAnuualStat[,11]
	SummerOb<-seasonalAnuualStat[,15]
	AutumnOb<-seasonalAnuualStat[,3]
	WinterOb<-seasonalAnuualStat[,7]							 	
	par(mfrow = c(2,2),mar = c(4,4,2,1),oma=c(1.5,1.5,3,1),xpd=FALSE,pty="s")	
    qq_au<-qqplot(AutumnOb, AutumnRep, plot.it = FALSE)
	plot(qq_au$x,qq_au$y,xlim=xy_scale*range(qq_au$x,qq_au$y),ylim=xy_scale*range(qq_au$x,qq_au$y),
		xlab="",ylab="",asp=1,cex.lab=fontsize, cex.axis=fontsize,cex=fontsize)
	#fit_au <- lm(AutumnRep ~ AutumnOb, data = qq_au)
	#abline(fit_au,lty=3)
	#Add a diagonal line to the scatter plot
	lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)			 	 
	mtext(side = 3, text = "Autumn", line = 0.5,cex=fontsize)
	mtext(side = 1, text = "Observed", line = 2,cex=fontsize)
	mtext(side = 2, text = "Simulated", line = 2,cex=fontsize)
	qq_wi<-qqplot(WinterOb, WinterRep, plot.it = FALSE)
	plot(qq_wi$x,qq_wi$y,xlim=xy_scale*range(qq_wi$x,qq_wi$y),ylim=xy_scale*range(qq_wi$x,qq_wi$y),
		xlab="",ylab="",asp=1,cex.lab=fontsize, cex.axis=fontsize,cex=fontsize)
	#fit_wi <- lm(WinterRep ~ WinterOb, data = qq_wi)
	#abline(fit_wi,lty=3)	
	#Add a diagonal line to the scatter plot
	lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)	 	 
	mtext(side = 3, text = "Winter", line = 0.5,cex=fontsize)
	mtext(side = 1, text = "Observed", line = 2,cex=fontsize)
  	mtext(side = 2, text = "Simulated", line = 2,cex=fontsize)							 
	qq_sp<-qqplot(SpringOb, SpringRep, plot.it = FALSE)
	plot(qq_sp$x,qq_sp$y,xlim=xy_scale*range(qq_sp$x,qq_sp$y),ylim=xy_scale*range(qq_sp$x,qq_sp$y),
		xlab="",ylab="",asp=1,cex.lab=fontsize, cex.axis=fontsize,cex=fontsize)
	#fit_sp <- lm(SpringRep ~ SpringOb, data = qq_sp)
	#abline(fit_sp,lty=3)
	#Add a diagonal line to the scatter plot
	lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)		 	 
	mtext(side = 3, text = "Spring", line = 0.5,cex=fontsize)
	mtext(side = 1, text = "Observed", line = 2,cex=fontsize)
	mtext(side = 2, text = "Simulated", line = 2,cex=fontsize)							 
	qq_su<-qqplot(SummerOb, SummerRep, plot.it = FALSE)
	plot(qq_su$x,qq_su$y,xlim=xy_scale*range(qq_su$x,qq_su$y),ylim=xy_scale*range(qq_su$x,qq_su$y),
		xlab="",ylab="",asp=1,cex.lab=fontsize, cex.axis=fontsize,cex=fontsize)
	#fit_su <- lm(SummerRep ~ SummerOb, data = qq_su)
	#abline(fit_su,lty=3)
	#Add a diagonal line to the scatter plot
	lines(par()$usr[1:2],par()$usr[3:4],lty=3,cex=fontsize,lwd=linewidth)			 	 
	mtext(side = 3, text = "Summer", line = 0.5,cex=fontsize)
	mtext(side = 1, text = "Observed", line = 2,cex=fontsize)
	mtext(side = 2, text = "Simulated", line = 2,cex=fontsize)						 
	par(mfrow = c(1,1),mar = c(0,0,0,0),oma=c(0,0,2,0),xpd=TRUE)
	title(main=paste(main),outer = T,cex.main=fontsize+0.3) 							 		
}
#DataFrame functions
annualStatDfFun<-function(annualStat,nSim,nStation,rfStatSelStn,stnNumber,stnName){
	if (rfStatSelStn=="All stations"){
	    ColIndex<-seq(from=6,to=1+nStation*5,by=5)
		if (nSim==1){
			Rep<-annualStat[2:(nSim+1),ColIndex]
		}
		else if (nStation==1){
			Rep<-mean(annualStat[2:(nSim+1),ColIndex])
		}
		else{
			Rep<-apply(annualStat[2:(nSim+1),ColIndex],2,mean)
		}
		Ob<-annualStat[1,ColIndex]#length=30
		annualStat.df<-data.frame(as.numeric(stnNumber),as.vector(as.matrix(stnName)),
			as.numeric(format(round(Ob,digits=1),nsmall=1)),
			as.numeric(format(round(Rep,digits=1),nsmall=1)))
		colnames(annualStat.df)<-c("Station Number","Station Name","Observed","Mean")		 
	}
	else{ 
		selStnNumber<-as.numeric(rfStatSelStn)
		selStn<-which(stnNumber==selStnNumber)
	    annualStatSelStn<-annualStat[,1+selStn*5]
	    quantiles<-as.numeric(format(round(quantile(annualStatSelStn[2:(nSim+1)],c(0.05,0.25,0.5,0.75,0.95)),digits=1),nsmall=1))
		annualStat.df<-data.frame(selStnNumber,as.vector(as.matrix(stnName))[selStn],
			as.numeric(format(round(annualStatSelStn[1],digits=1),nsmall=1)),
			as.numeric(format(round(mean(annualStatSelStn[2:(nSim+1)]),digits=1),nsmall=1)),quantiles[1],
			quantiles[2],quantiles[3],quantiles[4],quantiles[5])
		colnames(annualStat.df)<-c("Station Number","Station Name","Observed",
			"Mean Simulated","5%th Simulated","25%th Simulated",
			"50%th Simulated","75%th Simulated","95%th Simulated")						
	}
	return(annualStat.df)
}
seasonalStatDfFun<-function(seasonalStat,nSim,nStation,rfStatSelStn,stnNumber,stnName){
	if (rfStatSelStn=="All stations"){
		AnnualColIndex<-seq(from=6,to=1+nStation*5,by=5)
		#seasonal repl. and seasonal ob.
		if(nSim==1){
			Rep<-seasonalStat[2:(nSim+1),c(-1,-AnnualColIndex)]
		}
		if(nStation==1){
			Rep<-mean(seasonalStat[2:(nSim+1),c(-1,-AnnualColIndex)])
		}
		else{
			Rep<-apply(seasonalStat[2:(nSim+1),c(-1,-AnnualColIndex)],2,mean)
		}

		Ob<-seasonalStat[1,c(-1,-AnnualColIndex)]						 					 
		seasonalStat.df<-data.frame(rep(as.numeric(stnNumber),each=4),rep(as.vector(as.matrix(stnName)),each=4),
		  	rep(c("Autumn","Winter","Spring","Summer"),nStation),as.numeric(format(round(Ob,1),nsmall=1)),
			as.numeric(format(round(Rep,1),nsmall=1)))
		colnames(seasonalStat.df)<-c("Station Number","Station Name","Season","Observed","Mean Simulated")			 
	}
	else{ 
		selStnNumber<-as.numeric(rfStatSelStn)
		selStn<-which(stnNumber==selStnNumber)
		seasonalStatSelStn<-seasonalStat[,(2+(selStn-1)*5):(5+(selStn-1)*5)]
		seasonalQuantiles<-format(round(apply(seasonalStatSelStn,2,function(x) quantile(x[2:(nSim+1)],c(0.05,0.25,0.5,0.75,0.95))),1),nsmall=1)
		if (nSim==1){
			seasonalStat.df<-data.frame(rep(selStnNumber,each=4),rep(as.vector(as.matrix(stnName))[selStn],each=4),
				c("Autumn","Winter","Spring","Summer"),
				as.numeric(format(round(seasonalStatSelStn[1,],1),nsmall=1)),
				as.numeric(format(round(seasonalStatSelStn[2:(nSim+1),],1),nsmall=1)),
				as.numeric(seasonalQuantiles[1,]),as.numeric(seasonalQuantiles[2,]),
				as.numeric(seasonalQuantiles[3,]),as.numeric(seasonalQuantiles[4,]),
				as.numeric(seasonalQuantiles[5,]))    
		}
		else {
			seasonalStat.df<-data.frame(rep(selStnNumber,each=4),rep(as.vector(as.matrix(stnName))[selStn],each=4),
				c("Autumn","Winter","Spring","Summer"),
				as.numeric(format(round(seasonalStatSelStn[1,],1),nsmall=1)),
				as.numeric(format(round(apply(seasonalStatSelStn[2:(nSim+1),],2,mean),1),nsmall=1)),
				as.numeric(seasonalQuantiles[1,]),as.numeric(seasonalQuantiles[2,]),
				as.numeric(seasonalQuantiles[3,]),as.numeric(seasonalQuantiles[4,]),
				as.numeric(seasonalQuantiles[5,]))    
		}
         																																																																							
		colnames(seasonalStat.df)<-c("Station Number","Station Name","Season",
			"Observed","Mean Simulated","5%th Simulated","25%th Simulated",
			"50%th Simulated","75%th Simulated","95%th Simulated")						
	}
	return(seasonalStat.df)
}
monthlyStatDfFun<-function(monthlyStat,nSim,nStation,rfStatSelStn,stnNumber,stnName){	 
	if (rfStatSelStn=="All stations"){
		Ob<-monthlyStat[1,]
	    stn_Ob<-Ob[2:13]#Grab data in Station 1
		if (nSim==1){
			Rep<-monthlyStat[2:(nSim+1),]
			stn_Rep<-Rep[2:13]#Grab data in Station 1
		}
		else if (nStation==1){
			Rep<-apply(monthlyStat[2:(nSim+1),],2,mean)#mean of all simulations
			stn_Rep<-Rep[2:13]#Grab data in Station 1
		}
		else if(nStation>1){
			Rep<-apply(monthlyStat[2:(nSim+1),],2,mean)#mean of all simulations
			stn_Rep<-Rep[2:13]#Grab data in Station 1
			for (iStn in 2:nStation){
				istn_Ob<-Ob[(2+(iStn-1)*12):(13+(iStn-1)*12)]
				istn_Rep<-Rep[(2+(iStn-1)*12):(13+(iStn-1)*12)]
				stn_Rep<-rbind(stn_Rep,istn_Rep)
				stn_Ob<-rbind(stn_Ob,istn_Ob)
			}		
		}		
		stn_Rep<-as.vector(t(stn_Rep))
		stn_Ob<-as.vector(t(stn_Ob))
	    monthlyStat.df<-data.frame(rep(as.numeric(stnNumber),each=12),
			rep(as.vector(as.matrix(stnName)),each=12),rep(month.abb,nStation),
			as.numeric(format(round(stn_Ob,1),nsmall=1)),
			as.numeric(format(round(stn_Rep,1),nsmall=1)))
		colnames(monthlyStat.df)<-c("Station Number","Station Name","Month","Observed","Mean Simulated")							 
	}						
	else{ 
		selStnNumber<-as.numeric(rfStatSelStn)
		selStn<-which(stnNumber==selStnNumber)
        monthlyStatSelStn<-monthlyStat[,(2+(selStn-1)*12):(13+(selStn-1)*12)]	
	    monthlyQuantiles<-format(round(apply(monthlyStatSelStn,2,
			function(x) quantile(x[2:(nSim+1)],c(0.05,0.25,0.5,0.75,0.95))),1),nsmall=1)
  	    if (nSim==1){
			monthlyStat.df<-data.frame(rep(selStnNumber,each=12),
				rep(as.vector(as.matrix(stnName))[selStn],each=12),month.abb,
				as.numeric(format(round(monthlyStatSelStn[1,],1),nsmall=1)),
				as.numeric(format(round(monthlyStatSelStn[2:(nSim+1),],1),nsmall=1)),
				as.numeric(monthlyQuantiles[1,]),as.numeric(monthlyQuantiles[2,]),
				as.numeric(monthlyQuantiles[3,]),as.numeric(monthlyQuantiles[4,]),
				as.numeric(monthlyQuantiles[5,]))
		}
		else{
			monthlyStat.df<-data.frame(rep(selStnNumber,each=12),
				rep(as.vector(as.matrix(stnName))[selStn],each=12),month.abb,
				as.numeric(format(round(monthlyStatSelStn[1,],1),nsmall=1)),
				as.numeric(format(round(apply(monthlyStatSelStn[2:(nSim+1),],2,mean),1),nsmall=1)),
				as.numeric(monthlyQuantiles[1,]),as.numeric(monthlyQuantiles[2,]),
				as.numeric(monthlyQuantiles[3,]),as.numeric(monthlyQuantiles[4,]),
				as.numeric(monthlyQuantiles[5,]))
		}

		colnames(monthlyStat.df)<-c("Station Number","Station Name","Month","Observed","Mean Simulated",
			"5%th Simulated","25%th Simulated","50%th Simulated","75%th Simulated","95%th Simulated")		 			 
	}
	return(monthlyStat.df)
}			
maxSpelllength5thRfAmtDfFun<-function(maxSpelllength5thRfAmt,fromCol,nSim,nStation,rfStatSelStn,stnNumber,stnName){					 
	if (rfStatSelStn=="All stations"){
		ColIndex<-seq(from=fromCol,to=1+nStation*3,by=3)
		if(nSim==1){
			Rep<-maxSpelllength5thRfAmt[2:(nSim+1),ColIndex]
		}
		else if(nStation==1){
			Rep<-mean(maxSpelllength5thRfAmt[2:(nSim+1),ColIndex])
		}
		else{
			Rep<-apply(maxSpelllength5thRfAmt[2:(nSim+1),ColIndex],2,mean)	
		}
		Ob<-maxSpelllength5thRfAmt[1,ColIndex]								 
		maxSpelllength5thRfAmt.df<-data.frame(as.numeric(stnNumber),
			as.vector(as.matrix(stnName)),as.numeric(format(round(Ob,1),nsmall=1)),
			as.numeric(format(round(Rep,1),nsmall=1)))
		colnames(maxSpelllength5thRfAmt.df)<-c("Station Number","Station Name","Observed","Mean Simulated")		 										 							 
	}
	else{ 
		selStnNumber<-as.numeric(rfStatSelStn)
		selStn<-which(stnNumber==selStnNumber)
        maxSpelllength5thRfAmtSelStn<-maxSpelllength5thRfAmt[,fromCol+(selStn-1)*3]
	    quantiles<-as.numeric(format(round(quantile(maxSpelllength5thRfAmtSelStn[2:(nSim+1)],c(0.05,0.25,0.5,0.75,0.95)),1),nsmall=1))
		maxSpelllength5thRfAmt.df<-data.frame(selStnNumber,as.vector(as.matrix(stnName))[selStn],
			as.numeric(format(round(maxSpelllength5thRfAmtSelStn[1],1),nsmall=1)),
			as.numeric(format(round(mean(maxSpelllength5thRfAmtSelStn[2:(nSim+1)]),1),nsmall=1)),
			quantiles[1],quantiles[2],quantiles[3],quantiles[4],quantiles[5])
		colnames(maxSpelllength5thRfAmt.df)<-c("Station Number","Station Name",
			"Observed","Mean Simulated","5%th Simulated","25%th Simulated",
			"50%th Simulated","75%th Simulated","95%th Simulated")						 					
	}
    return(maxSpelllength5thRfAmt.df)		
}
totRfAmtInWSDfFun<-function(totRfAmtInWS,text1,text2,text3,text4,text5,nSim,nStation,rfStatSelStn,stnNumber,stnName){
	#text1="1-day",text2="2-4 days", text3="5-7 days",text4="> 7 days", text5="Wet Spell Length"		
	if(nSim==1){
		Rep<-totRfAmtInWS[2:(nSim+1),2:(1+4*nStation)]
	}
	else if(nStation==1){
		Rep<-mean(totRfAmtInWS[2:(nSim+1),2:(1+4*nStation)])
	}
	else{
		Rep<-apply(totRfAmtInWS[2:(nSim+1),2:(1+4*nStation)],2,mean)
	}
	Ob<-totRfAmtInWS[1,2:(1+4*nStation)]										
	if (rfStatSelStn=="All stations"){
		totRfAmtInWS.df<-data.frame(rep(as.numeric(stnNumber),each=4),rep(as.vector(as.matrix(stnName)),each=4),
			rep(c(paste(text1),paste(text2),paste(text3),paste(text4)),nStation),
			as.numeric(format(round(Ob,1),nsmall=1)),as.numeric(format(round(Rep,1),nsmall=1)))	
		colnames(totRfAmtInWS.df)<-c("Station Number","Station Name",paste(text5),"Observed","Mean Simulated")
	}
	else{ 
		selStnNumber<-as.numeric(rfStatSelStn)
		selStn<-which(stnNumber==selStnNumber)
		SelStn_1<-totRfAmtInWS[,2+(selStn-1)*4]
		SelStn_2<-totRfAmtInWS[,3+(selStn-1)*4]
		SelStn_3<-totRfAmtInWS[,4+(selStn-1)*4]
		SelStn_4<-totRfAmtInWS[,5+(selStn-1)*4]				         
		selStnNumber<-as.numeric(rfStatSelStn)
        totRfAmtInWSSelStn<-totRfAmtInWS[,2:(1+4*nStation)]						 
		totRfAmtInWSQuantiles<-format(round(apply(totRfAmtInWSSelStn,2,
			function(x) quantile(x[2:(nSim+1)],c(0.05,0.25,0.5,0.75,0.95))),1),nsmall=1)
  	    totRfAmtInWS.df<-data.frame(rep(selStnNumber,each=4),
			rep(as.vector(as.matrix(stnName))[selStn],each=4),
			c(paste(text1),paste(text2),paste(text3),paste(text4)),
			as.numeric(format(round(totRfAmtInWSSelStn[1,],1),nsmall=1)),
			as.numeric(format(round(apply(totRfAmtInWSSelStn[2:(nSim+1),],2,mean),1),nsmall=1)),
			as.numeric(totRfAmtInWSQuantiles[1,]),as.numeric(totRfAmtInWSQuantiles[2,]),
			as.numeric(totRfAmtInWSQuantiles[3,]),as.numeric(totRfAmtInWSQuantiles[4,]),
			as.numeric(totRfAmtInWSQuantiles[5,]))
		colnames(totRfAmtInWS.df)<-c("Station Number","Station Name",paste(text5),
			"Observed","Mean Simulated","5%th Simulated","25%th Simulated",
			"50%th Simulated","75%th Simulated","95%th Simulated")
    }
	return(totRfAmtInWS.df)	
}
rfStatInAYearDfFun<-function(scanIndex1,scanIndex2,scanIndex3,nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,stnName){ 
	#scanIndex1<-1;scanIndex2<-0;scanIndex3<-2 for number of wet days in a year
	#scanIndex1<-3;scanIndex2<-0;scanIndex3<-2 for maximum wet spell length in a year
	#scanIndex1<-5;scanIndex2<-0;scanIndex3<-1 for maximum dry spell length in a year
	#scanIndex1<-4;scanIndex2<-0;scanIndex3<-2 for average numer of wet spells>1 in a year
	#scanIndex1<-5;scanIndex1<-0;scanIndex3<-1 for average number of dry spells >1 in a year
	#scanIndex1<-0;scanIndex2<-0;scanIndex3<-2 for maxm rf amt in a year
	#scanIndex1<-2;scanIndex2<-0;scanIndex3<-2 for avg rf amt in a year
	if (rfStatSelStn=="All stations"){	
		if (nStation==1){
			iStn<-1
			med_RfStat<-apply(matrix(scan(file=statFile,
				skip=(iStn-1)*(5*(nYrStat+2)+2*(nYrStat+1))+11*(nSim+2)+3*(nSim+3)+6+scanIndex1*(nYrStat+2)+scanIndex2*(nYrStat+1)+scanIndex3,nlines=2,quiet = TRUE),nrow=2,ncol=8,byrow=TRUE),2,median)
			med_RfStatRep<-med_RfStat[7]
			med_RfStatOb<-med_RfStat[5]
		}
		else {
			iStn<-1
			med_RfStat<-apply(matrix(scan(file=statFile,
				skip=(iStn-1)*(5*(nYrStat+2)+2*(nYrStat+1))+11*(nSim+2)+3*(nSim+3)+(2+(nStation-1)*nStation-sum(1:(nStation-1)))+4*(1+(nStation-1)*nStation-sum(1:(nStation-1)))+scanIndex1*(nYrStat+2)+scanIndex2*(nYrStat+1)+scanIndex3,nlines=2,quiet = TRUE),nrow=2,ncol=8,byrow=TRUE),2,median)
					  
			for (iStn in 2:nStation){ 
				imed_RfStat<-apply(matrix(scan(file=statFile,
						skip=(iStn-1)*(5*(nYrStat+2)+2*(nYrStat+1))+11*(nSim+2)+3*(nSim+3)+(2+(nStation-1)*nStation-sum(1:(nStation-1)))+4*(1+(nStation-1)*nStation-sum(1:(nStation-1)))+scanIndex1*(nYrStat+2)+scanIndex2*(nYrStat+1)+scanIndex3,nlines=2,quiet = TRUE),
						nrow=2,ncol=8,byrow=TRUE),2,median)								   
				med_RfStat<-rbind(med_RfStat,imed_RfStat)						
			}
			med_RfStatRep<-med_RfStat[,7]
			med_RfStatOb<-med_RfStat[,5]
		}		
		rfStatInAYear.df<-data.frame(as.numeric(stnNumber),as.vector(as.matrix(stnName)),
								  as.numeric(format(round(med_RfStatOb,1),nsmall=1)),
								  as.numeric(format(round(med_RfStatRep,1),nsmall=1)))
		colnames(rfStatInAYear.df)<-c("Station Number","Station Name","Median Observed","Median simulations")
	}
	else{ 
		selStnNumber<-as.numeric(rfStatSelStn) 
		selStn<-which(stnNumber==selStnNumber)
		if (nStation==1){
			rfStatInAYearSelStn<-matrix(scan(file=statFile,
				skip=(selStn-1)*(5*(nYrStat+2)+2*(nYrStat+1))+11*(nSim+2)+3*(nSim+3)+6+scanIndex1*(nYrStat+2)+scanIndex2*(nYrStat+1)+scanIndex3,nlines=nYrStat,quiet = TRUE),
				nrow=nYrStat,ncol=8,byrow=TRUE)
		}
		else {
			rfStatInAYearSelStn<-matrix(scan(file=statFile,
				skip=(selStn-1)*(5*(nYrStat+2)+2*(nYrStat+1))+11*(nSim+2)+3*(nSim+3)+(2+(nStation-1)*nStation-sum(1:(nStation-1)))+4*(1+(nStation-1)*nStation-sum(1:(nStation-1)))+scanIndex1*(nYrStat+2)+scanIndex2*(nYrStat+1)+scanIndex3,nlines=nYrStat,quiet = TRUE),
				nrow=nYrStat,ncol=8,byrow=TRUE)
		}
		rfStatInAYear.df<-data.frame(rep(selStnNumber,each=nYrStat),rep(as.vector(as.matrix(stnName))[selStn],each=nYrStat),
								  as.numeric(format(round(rfStatInAYearSelStn[,3],2),nsmall=2)),
								  as.numeric(format(round(rfStatInAYearSelStn[,5],1),nsmall=1)),
								  as.numeric(format(round(rfStatInAYearSelStn[,6],1),nsmall=1)),
								  as.numeric(format(round(rfStatInAYearSelStn[,7],1),nsmall=1)),
								  as.numeric(format(round(rfStatInAYearSelStn[,8],1),nsmall=1)))
		colnames(rfStatInAYear.df)<-c("Station Number","Station Name","Cumulative Probability","Observed","5%th Simulated",
										"50%th Simulated","95%th Simulated")											
	}
	return(rfStatInAYear.df)
}				
#text1="1-day",text2="2-4 days", text3="5-7 days",text4="> 7 days", text5="Wet Spell length"
avgOccW_DSpellsDfFun<-function(avgOccW_DSpells,text1,text2,text3,text4,text5,nSim,nStation,rfStatSelStn,stnNumber,stnName){
	 if(nSim==1){
	 	 Rep<-avgOccW_DSpells[2:(nSim+1),2:(1+4*nStation)]
	 }
	 else if(nStation==1){
	 	 Rep<-mean(avgOccW_DSpells[2:(nSim+1),2:(1+4*nStation)])
	 }
	 else{
	 	 Rep<-apply(avgOccW_DSpells[2:(nSim+1),2:(1+4*nStation)],2,mean)
	 }	 
	 Ob<-avgOccW_DSpells[1,2:(1+4*nStation)]										
	 if (rfStatSelStn=="All stations"){
		avgOccW_DSpells.df<-data.frame(rep(as.numeric(stnNumber),each=4),
			rep(as.vector(as.matrix(stnName)),each=4),
			rep(c(paste(text1),paste(text2),paste(text3),paste(text4)),nStation),
			as.numeric(format(round(Ob,1),nsmall=1)),as.numeric(format(round(Rep,1),nsmall=1)))	
		colnames(avgOccW_DSpells.df)<-c("Station Number","Station Name",paste(text5),"Observed","Mean Simulated")				 							
	}
    else{ 		         
		selStnNumber<-as.numeric(rfStatSelStn)
		selStn<-which(stnNumber==selStnNumber)
	    avgOccW_DSpellsSelStn<-avgOccW_DSpells[,2:(1+4*nStation)]						 
	    avgOccW_DSpellsQuantiles<-format(round(apply(avgOccW_DSpellsSelStn,2,
			function(x) quantile(x[2:(nSim+1)],c(0.05,0.25,0.5,0.75,0.95))),1),nsmall=1)
		if(nSim==1){
			avgOccW_DSpells.df<-data.frame(rep(selStnNumber,each=4),
				rep(as.vector(as.matrix(stnName))[selStn],each=4),
				c(paste(text1),paste(text2),paste(text3),paste(text4)),
				as.numeric(format(round(avgOccW_DSpellsSelStn[1,],1),nsmall=1)),
				as.numeric(format(round(avgOccW_DSpellsSelStn[2:(nSim+1),],1),nsmall=1)),
				as.numeric(avgOccW_DSpellsQuantiles[1,]),as.numeric(avgOccW_DSpellsQuantiles[2,]),
				as.numeric(avgOccW_DSpellsQuantiles[3,]),as.numeric(avgOccW_DSpellsQuantiles[4,]),
				as.numeric(avgOccW_DSpellsQuantiles[5,]))
		}
		else {
			 avgOccW_DSpells.df<-data.frame(rep(selStnNumber,each=4),
				rep(as.vector(as.matrix(stnName))[selStn],each=4),
				c(paste(text1),paste(text2),paste(text3),paste(text4)),
				as.numeric(format(round(avgOccW_DSpellsSelStn[1,],1),nsmall=1)),
				as.numeric(format(round(apply(avgOccW_DSpellsSelStn[2:(nSim+1),],2,mean),1),nsmall=1)),
				as.numeric(avgOccW_DSpellsQuantiles[1,]),as.numeric(avgOccW_DSpellsQuantiles[2,]),
				as.numeric(avgOccW_DSpellsQuantiles[3,]),as.numeric(avgOccW_DSpellsQuantiles[4,]),
				as.numeric(avgOccW_DSpellsQuantiles[5,]))
			
		}
  	   
		colnames(avgOccW_DSpells.df)<-c("Station Number","Station Name",paste(text5),
			"Observed","Mean Simulated","5%th Simulated","25%th Simulated",
			"50%th Simulated","75%th Simulated","95%th Simulated")				 		
		}
	 return(avgOccW_DSpells.df)
	}				 	
annualCrsCorrlDfFun<-function(scanIndex1,scanIndex2,scanIndex3,nSim,nStation,statFile,nYrStat,stnNumber,stnName){
	#scanIndex1<-0, scanIndex2<-0, scanIndex3<-2, for daily log-odds ratio on seasonal and annual basis
	#scanIndex1<-1, scanIndex2<-0, scanIndex3<-1, for daily crs-corrl of rf-wet days on seas & annual basis
	#scanIndex1<-1, scanIndex2<-1, scanIndex3<-1, for daily crs-corrl of rf-all days on seas & annual basis
	#scanIndex1<-1, scanIndex2<-2, scanIndex3<-1, for cross-corrl of number wet days in season and year
	#scanIndex1<-1, scanIndex2<-3, scanIndex3<-1, for cross-corrl of seasonal & annual rainfall
	seasonalAnuualStat<-matrix(scan(file=statFile,
		skip=11*(2+nSim)+3*(3+nSim)+scanIndex1*(2+(nStation-1)*nStation-sum(1:(nStation-1)))+scanIndex2*(1+(nStation-1)*nStation-sum(1:(nStation-1)))+scanIndex3,nlines=(nStation-1)*nStation-sum(1:(nStation-1)),quiet = TRUE),
		nrow=(nStation-1)*nStation-sum(1:(nStation-1)),ncol=22,byrow=TRUE)
	Rep5<-seasonalAnuualStat[,20]
	Rep50<-seasonalAnuualStat[,21]
	Rep95<-seasonalAnuualStat[,22]
	Ob<-seasonalAnuualStat[,19]
	stnIndex1<-seasonalAnuualStat[,1]
	stnIndex2<-seasonalAnuualStat[,2]
	stnNumber1<-as.numeric(stnNumber)[stnIndex1]
	stnNumber2<-as.numeric(stnNumber)[stnIndex2]
	stnName1<-as.vector(as.matrix(stnName))[stnIndex1]
	stnName2<-as.vector(as.matrix(stnName))[stnIndex2]
	annualStat.df<-data.frame(stnNumber1,stnName1,stnNumber2,stnName2,
		as.numeric(format(round(Ob,digits=2),nsmall=2)),
		as.numeric(format(round(Rep5,digits=2),nsmall=2)),
		as.numeric(format(round(Rep50,digits=2),nsmall=2)),
		as.numeric(format(round(Rep95,digits=2),nsmall=2)))
	colnames(annualStat.df)<-c("Station Number (1)","Station Name (1)",
		"Station Number (2)","Station Name 2","Observed","5%th Simulated",
		"50%th Simulated","95%th Simulated")	
    return(annualStat.df)								
}
seasonalCrsCorrlDfFun<-function(scanIndex1,scanIndex2,scanIndex3,nSim,nStation,statFile,nYrStat,stnNumber,stnName){
	#scanIndex1<-0, scanIndex2<-0, scanIndex3<-2, for daily log-odds ratio on seasonal and annual basis
	#scanIndex1<-1, scanIndex2<-0, scanIndex3<-1, for daily crs-corrl of rf-wet days on seas & annual basis
	#scanIndex1<-1, scanIndex2<-1, scanIndex3<-1, for daily crs-corrl of rf-all days on seas & annual basis
	#scanIndex1<-1, scanIndex2<-2, scanIndex3<-1, for cross-corrl of number wet days in season and year
	#scanIndex1<-1, scanIndex2<-3, scanIndex3<-1, for cross-corrl of seasonal & annual rainfall
	seasonalAnuualStat<-matrix(scan(file=statFile,
		skip=11*(2+nSim)+3*(3+nSim)+scanIndex1*(2+(nStation-1)*nStation-sum(1:(nStation-1)))+scanIndex2*(1+(nStation-1)*nStation-sum(1:(nStation-1)))+scanIndex3,nlines=(nStation-1)*nStation-sum(1:(nStation-1)),quiet = TRUE),
		nrow=(nStation-1)*nStation-sum(1:(nStation-1)),ncol=22,byrow=TRUE)
	seasonalRep5<-as.vector(as.matrix(seasonalAnuualStat[,c(4,8,12,16)],nrow=1,ncol=4*((nStation-1)*nStation-sum(1:(nStation-1))),byrow=TRUE))
	seasonalRep50<-as.vector(as.matrix(seasonalAnuualStat[,c(5,9,13,17)],nrow=1,ncol=4*((nStation-1)*nStation-sum(1:(nStation-1))),byrow=TRUE))
	seasonalRep95<-as.vector(as.matrix(seasonalAnuualStat[,c(6,10,14,18)],nrow=1,ncol=4*((nStation-1)*nStation-sum(1:(nStation-1))),byrow=TRUE))
	seasonalOb<-as.vector(as.matrix(seasonalAnuualStat[,c(3,7,11,15)],nrow=1,ncol=4*((nStation-1)*nStation-sum(1:(nStation-1))),byrow=TRUE))
	stnIndex1<-seasonalAnuualStat[,1]
	stnIndex2<-seasonalAnuualStat[,2]
	stnNumber1<-as.numeric(stnNumber)[stnIndex1]
	stnNumber2<-as.numeric(stnNumber)[stnIndex2]
	stnName1<-as.vector(as.matrix(stnName))[stnIndex1]
	stnName2<-as.vector(as.matrix(stnName))[stnIndex2]
	seasonalStat.df<-data.frame(rep(stnNumber1,each=4),rep(stnName1,each=4),
		rep(stnNumber2,each=4),rep(stnName2,each=4),
		rep(c("Autumn","Winter","Spring","Summer"),(nStation-1)*nStation-sum(1:(nStation-1))),
		as.numeric(format(round(seasonalOb,2),nsmall=2)),
		as.numeric(format(round(seasonalRep5,2),nsmall=2)),
		as.numeric(format(round(seasonalRep50,2),nsmall=2)),
		as.numeric(format(round(seasonalRep95,2),nsmall=2)))               																																																																							
	colnames(seasonalStat.df)<-c("Station Number (1)","Station Name (1)",
		"Station Number (2)","Station Name 2","Season"," Observed",
		"5%th Simulated","50%th Simulated","95%th Simulated")
    return(seasonalStat.df)									
}
#Rainfall Occurrence page
rfOccTable<-gtkTable(rows=3,columns=4,homogeneous=FALSE)
notebookStat$appendPage(rfOccTable,gtkLabel("Rainfall Occurrence "))
rfOccOptionFrame<-gtkFrame("Rainfall Occurrence")
rfOccTable$attach(rfOccOptionFrame,left.attach=0,1,top.attach=0,1,
	xoptions=c("shrink","fill"),yoptions="",ypadding=0)
rfOccAnnualList<-c("mean of wet days","SD of wet days","maximum wet spell length",
	"maximum dry spell length","average Occurrence of wet spells of varying length",
	"average Occurrence of dry spells of varying length","number of wet days in a year",
	"maximum wet spell length in a year","average number of wet spell>1 in a year",
	"maximum dry spell length in a year","average number of dry spell>1 in a year",
	"daily log-odds ratio","cross-correlation of number of wet days")
rfOccSeasonalList<-c("mean of wet days","SD of wet days","daily log-odds ratio",
	"cross-correlation of number of wet days")
rfOccMonthlyList<-c("mean of wet days","SD of wet days")
rfOccOption<-data.frame(aggregation=c(rep("Annual",length(rfOccAnnualList)),
	rep("Seasonal",length(rfOccSeasonalList)),rep("Monthly",length(rfOccMonthlyList))),
	rfOccStat=c(rfOccAnnualList,rfOccSeasonalList,rfOccMonthlyList))
rfOccOptionModel<-gtkTreeStore("gchararray")
by (rfOccOption,rfOccOption$aggregation,function(DF2){
	parent_iter <- rfOccOptionModel$append()
	rfOccOptionModel$setValue(parent_iter$iter,column = 0,value = DF2$aggregation)
	sapply ( DF2$rfOccStat, function (rfOccStat){
		child_iter <- rfOccOptionModel$append(parent = parent_iter$iter)
		if (is.null(child_iter$retval))
		rfOccOptionModel$setValue(child_iter$iter,column = 0 ,value = rfOccStat)
	})
})
rfOccOptionView<-gtkTreeView()
rfOccOptionView$getSelection()$setMode("browse")
rfOccOptionView$insertColumnWithAttributes(0,"              ",gtkCellRendererText(),text=0)
rfOccOptionView$setModel(rfOccOptionModel)
rfOccScrolledWindow<-gtkScrolledWindow()
rfOccScrolledWindow$setSizeRequest(200,800)
rfOccScrolledWindow$add(rfOccOptionView)
rfOccOptionFrame$add(rfOccScrolledWindow)
rfOccStnSelFrame<-gtkFrame("Select Station: ")
rfOccTable$attach(rfOccStnSelFrame,left.attach=0,1,top.attach=1,2,
	xoptions=c("shrink","fill"),yoptions="",ypadding=0)
rfOccStnCombo <- gtkComboBoxNewText()
rfOccStnSelFrame$add(rfOccStnCombo)
gSignalConnect(rfOccStnCombo,"changed",f = function(button,...){    
	#message("",button$getActiveText(),"\n")
	list<-readLines("option.dat")
	isuccess=as.numeric(list[2])
	if(isuccess==1) {rfOccOptionFun()}
})
rfOccViewOptionFrame<-gtkFrame("View Options")
rfOccTable$attach(rfOccViewOptionFrame,left.attach=1,2,top.attach=1,2,
	xoptions=c("expand","fill"),yoptions="",ypadding=0)
rfOccViewOptionLabels<-c("Grid","Plot")
rfOccViewOptionRadioGp<-list() 
rfOccViewOptionRadioGp [[rfOccViewOptionLabels[1]]]<-gtkRadioButton(label=rfOccViewOptionLabels[1])
for(label in rfOccViewOptionLabels [-1])
rfOccViewOptionRadioGp[[label]]<-gtkRadioButton(rfOccViewOptionRadioGp,label=label)
rfOccViewOptionHBox<-gtkHBox(homogeneous = NULL,spacing = NULL,show = TRUE)
rfOccViewOptionFrame$add(rfOccViewOptionHBox)
sapply(rfOccViewOptionRadioGp,gtkBoxPackStart,object=rfOccViewOptionHBox)
rfOccViewOptionHBox[[2]]$setActive(TRUE)
sapply(rfOccViewOptionRadioGp,'[',"active")
sapply(rfOccViewOptionRadioGp,gSignalConnect,"toggled",
	function(button,data){
		if(button['active']){
			#message("",button$getLabel(),"\n")
			list<-readLines("option.dat")
			isuccess=as.numeric(list[2])
			if (isuccess==1) {rfOccOptionFun()}
		}
	})	
rfOccSaveViewButton<-gtkButtonNewWithLabel("Save View")
rfOccTable$attach(rfOccSaveViewButton,left.attach=0,1,top.attach=2,3,
	xoptions=c("shrink","fill"),yoptions="",ypadding=0)	
#add plot device to rfOCCTable
rfOccPlotDeviceAdd<-function(){				 				
	rfOccPlotDevice<-gtkDrawingArea()
	rfOccPlotDevice$setSizeRequest(600,800)
	asCairoDevice(rfOccPlotDevice)
	rfOccTable$attach(rfOccPlotDevice,left.attach=1,2,top.attach=0,1,
		xoptions=c("expand","fill"),yoptions="",ypadding=0)
	Sys.sleep(.1)
}
#Function to view rainfall occurrence statistics
rfOccOptionFun<-function(){
	 if (length(dev.list())>1) dev.off()
	 if(length(rfOccOptionSel$getSelectedRows()$retval)==1){ 		 
		statFile<-"stat.out"
		#Read user-defined parameters
		parameters<-scan(file="data.dat",skip=2,nline=1,quiet = TRUE)
		nYr<-parameters[1]
		yrStart<-parameters[2]
		band<-parameters[3]
		nStation<-parameters[4]
		nSim<-parameters[5]
		nYrSim<-parameters[8]
		nYrStat<-max(parameters[8],parameters[1]) #multi_site_rain.f L4643
		list_data_fi=readLines("data.dat")
		inputRfFile<-list_data_fi[8]
		stnNumber<-read.table(inputRfFile,nrows=1)[2:(nStation+1)]	
	    stnName<-read.table(inputRfFile,skip=1,nrow=1,quote="\"")[2:(nStation+1)]
		#get view option from radiobutton gp
		sapply(rfOccViewOptionRadioGp,function(button,data){
			if(button['active']){
				list<-readLines("option.dat")
				list<-sub(list[4],button$getLabel(),list)
				writeLines(list,"option.dat") 
			}
		}) 
		list<-readLines("option.dat")
		rfOccViewOption<-list[4]
		rfStatSelStn<-rfOccStnCombo$getActiveText()
		#rfOccPlotDeviceAdd()				        				 				 														 																							
		if(length(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices())==2 & length(rfStatSelStn)>0){
			if (rfOccViewOption=="Plot"){
				rfOccPlotDeviceAdd()
				#Mean of annual wet days plot
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,0))){
					wetDaysAnnualSeasonalMean<-matrix(scan(file=statFile,skip=0*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
					fontsize<-1.5
					linewidth<-2
					mainLength<-nchar("Mean of annual wet days")
					annualStatPlotFun(wetDaysAnnualSeasonalMean,"Mean of annual wet days",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)					 					
				}
				#SD of annual wet days plot
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,1))){
					wetDaysAnnualSeasonalSD<-matrix(scan(file=statFile,skip=3*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)					 
					fontsize<-1.5
					linewidth<-2
					mainLength<-nchar("SD of annual wet days")
					annualStatPlotFun(wetDaysAnnualSeasonalSD,"SD of annual wet days",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)						
				}	
				#Maximum wet spell lengths plot
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,2))){
					rfOccMaxSpell5th<-matrix(scan(file=statFile,skip=10*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+3*nStation,byrow=TRUE)
					fontsize<-1.5
					linewidth<-2
					mainLength<-nchar("Maximum wet spell length")
					maxSpelllength5thRfAmtPlotFun(rfOccMaxSpell5th,2,"Maximum wet spell length",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)	
				}
				#Maximum dry spell lengths plot
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,3))){
					rfOccMaxSpell5th<-matrix(scan(file=statFile,skip=10*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+3*nStation,byrow=TRUE)						 						 
					fontsize<-1.5
					linewidth<-2
					mainLength<-nchar("Maximum dry spell length")
					maxSpelllength5thRfAmtPlotFun(rfOccMaxSpell5th,3,"Maximum dry spell length",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)	
					skip<-10*(nSim+2)+1
				}
				#Average Occurrence of wet spells of varying lengths plot
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,4))){ 
					avgOccOfWS<-matrix(scan(file=statFile,skip=11*(nSim+2)+0*(nSim+3)+2,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+4*nStation,byrow=TRUE)
					fontsize<-1.2
					linewidth<-1
					avgOccW_DSpellsPlotFun(avgOccOfWS,"1-day","2-4 days","5-7 days","> 7 days",
						c("Average occurrence of wet spells","\nof varying lengths"),nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth)
				}	
				 #Average Occurrence of dry spells of varying lengths plot
				 if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,5))){
					avgOccOfDS<-matrix(scan(file=statFile,skip=11*(nSim+2)+2*(nSim+3)+2,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+4*nStation,byrow=TRUE)	
					fontsize<-1.2
					linewidth<-1
					avgOccW_DSpellsPlotFun(avgOccOfDS,"1-day","2-9 days","9-18 days","> 18 days",
						c("Average occurrence of dry spells","\nof varying lengths"),nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth)
				}	
				 #Number of wet days in a year plot
				 if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,6))){
					#scanIndex1<-1,scanIndex2<-0,scanIndex3<-2 for number of wet days in a year
					fontsize<-1.5
					linewidth<-2
					mainLength<-nchar("Number of wet days in a year")
					rfStatInAYearPlotFun(1,0,2,"Number of wet days in a year",nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)
				}	
				#Maximum wet spell length in a year plot
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,7))){
					#scanIndex1<-3,scanIndex2<-0,scanIndex3<-2 for maximum wet spell length in a year 
					fontsize<-1.5
					linewidth<-2
					mainLength<-nchar("Maximum wet spell length in a year")
					rfStatInAYearPlotFun(3,0,2,"Maximum wet spell length in a year",nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)							 
				}	
				#Average number of wet spells > 1 in a year plot
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,8))){
					#scanIndex1<-4,scanIndex2<-0,scanIndex3<-2 for average numer of wet spells>1 in a year	
					fontsize<-1.5
					linewidth<-2
					mainLength<-nchar("Average number of wet spells > 1 in a year")
					rfStatInAYearPlotFun(4,0,2,"Average number of wet spells > 1 in a year",nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)
				}
				#Maximum dry spell length in a year plot
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,9))){
					#scanIndex1<-5,scanIndex2<-0,scanIndex3<-1 for maximum dry spell length in a year
					fontsize<-1.5
					linewidth<-2
					mainLength<-nchar("Maximum dry spell length in a year")
					rfStatInAYearPlotFun(5,0,1,"Maximum dry spell length in a year",nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)
				}	
				#Average number of dry spells > 1 in a year plot
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,10))){
					#scanIndex1<-5,scanIndex1<-1,scanIndex3<-1 for average number of dry spells >1 in a year
					fontsize<-1.5
					linewidth<-2	
					mainLength<-nchar("Average number of dry spells >1 in a year")
					rfStatInAYearPlotFun(5,1,1,"Average number of dry spells >1 in a year",nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)
				}			 	
				#Daily log-odds ratio on annual basis plot
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,11))){
					fontsize<-1.5
					linewidth<-2
					if (nStation>1){
						annualCrsCorrlPlotFun(0,0,2,"Daily log-odds ratio on annual basis",nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)
					}						
				}	
				 #Cross-corrl of number wet days on annual basis plot
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,12))){
					fontsize<-1.5
					linewidth<-2
					if (nStation>1) {
						annualCrsCorrlPlotFun(1,2,1,c("Cross-correlation of the number of", "\nwet days on annual basis"),nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)	
					}					
				}	
				#Mean of seasonal wet days plot
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,0))){
					wetDaysAnnualSeasonalMean<-matrix(scan(file=statFile,skip=0*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
					fontsize<-1.2
					linewidth<-1
					mainLength<-nchar("Mean of seasonal wet days")
					seasonalStatPlotFun(wetDaysAnnualSeasonalMean,"Mean of seasonal wet days",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)
				}	
				#SD of seasonal wet days plot
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,1))){
					wetDaysAnnualSeasonalSD<-matrix(scan(file=statFile,skip=3*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
					fontsize<-1.2
					linewidth<-1
					mainLength<-nchar("Mean of seasonal wet days")
					seasonalStatPlotFun(wetDaysAnnualSeasonalSD,"SD of seasonal wet days",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)
				}
				#Daily log-odds ratio on seasonal basis plot
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,2))){
					fontsize<-1.2
					linewidth<-1
					if (nStation>1){
						seasonalCrsCorrlPlotFun(0,0,2,"Daily log-odds ratio on seasonal basis",nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)
					}
				}	
				#Cross-corrl of number wet days on seasonal basis plot
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,3))){
					fontsize<-1.2
					linewidth<-1
					if (nStation>1){
						seasonalCrsCorrlPlotFun(1,2,1,c("Cross-correlation of the number of wet days", "\non seasonal basis"),nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)						
					}
				}
				#Mean of monthly wet days plot
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,0))){
					#col=[2:13] for station 1
					wetDaysMonthlyMean<-matrix(scan(file=statFile,skip=6*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
					mainLength<-nchar("Mean of monthly wet days")
					monthlyStatPlotFun(wetDaysMonthlyMean,"Mean of monthly wet days",nSim,nStation,rfStatSelStn,stnNumber,mainLength)
				}	
				#SD of monthly wet days plot
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,1))){
					#col=[2:13] for station 1
					wetDaysMonthlySD<-matrix(scan(file=statFile,skip=8*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
					mainLength<-nchar("SD of monthly wet days")
					monthlyStatPlotFun(wetDaysMonthlySD,"SD of monthly wet days",nSim,nStation,rfStatSelStn,stnNumber,mainLength)														
				}	
			}
			if (rfOccViewOption=="Grid"){
				#Mean of annual wet days df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,0))){
					wetDaysAnnualSeasonalMean<-matrix(scan(file=statFile,skip=0*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
					StatDf<-annualStatDfFun(wetDaysAnnualSeasonalMean,nSim,nStation,rfStatSelStn,stnNumber,stnName)					 					
				}											 
				#SD of annual wet days df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,1))){
					wetDaysAnnualSeasonalSD<-matrix(scan(file=statFile,skip=3*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
					StatDf<-annualStatDfFun(wetDaysAnnualSeasonalSD,nSim,nStation,rfStatSelStn,stnNumber,stnName)						
				}						 					 
				#Maximum wet spell lengths df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,2))){
					rfOccMaxSpell5th<-matrix(scan(file=statFile,skip=10*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+3*nStation,byrow=TRUE)						 
					StatDf<-maxSpelllength5thRfAmtDfFun(rfOccMaxSpell5th,2,nSim,nStation,rfStatSelStn,stnNumber,stnName)	
				}										 
				#Maximum dry spell lengths df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,3))){
					rfOccMaxSpell5th<-matrix(scan(file=statFile,skip=10*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+3*nStation,byrow=TRUE)					 
					StatDf<-maxSpelllength5thRfAmtDfFun(rfOccMaxSpell5th,3,nSim,nStation,rfStatSelStn,stnNumber,stnName)	
				}																		 
				#Average Occurrence of wet spells of varying lengths df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,4))){ 
					avgOccOfWS<-matrix(scan(file=statFile,skip=11*(nSim+2)+0*(nSim+3)+2,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+4*nStation,byrow=TRUE)
					StatDf<-avgOccW_DSpellsDfFun(avgOccOfWS,"1-day","2-4 days","5-7 days","> 7 days","Wet Spell length",nSim,nStation,rfStatSelStn,stnNumber,stnName)
				}						 						
				#Average Occurrence of dry spells of varying lengths df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,5))){
					avgOccOfDS<-matrix(scan(file=statFile,skip=11*(nSim+2)+2*(nSim+3)+2,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+4*nStation,byrow=TRUE)
					StatDf<-avgOccW_DSpellsDfFun(avgOccOfDS,"1-day","2-9 days","9-18 days","> 18 days","Dry Spell length",nSim,nStation,rfStatSelStn,stnNumber,stnName)
				}												 
				#Number of wet days in a year df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,6))){
					#scanIndex1<-1,scanIndex2<-0,scanIndex3<-2 for number of wet days in a year
					StatDf<-rfStatInAYearDfFun(1,0,2,nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,stnName)
				}					 
				#Maximum wet spell length in a year df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,7))){
					#scanIndex1<-3,scanIndex2<-0,scanIndex3<-2 for maximum wet spell length in a year 
					StatDf<-rfStatInAYearDfFun(3,0,2,nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,stnName)							 
				}					 											
				#Average number of wet spells > 1 in a year df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,8))){
					#scanIndex1<-4,scanIndex2<-0,scanIndex3<-2 for average numer of wet spells>1 in a year
					StatDf<-rfStatInAYearDfFun(4,0,2,nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,stnName)
				}										
				#Maximum dry spell length in a year df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,9))){
					#scanIndex1<-5,scanIndex2<-0,scanIndex3<-1 for maximum dry spell length in a year
					StatDf<-rfStatInAYearDfFun(5,0,1,nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,stnName)
				}					 
				#Average number of dry spells > 1 in a year df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,10))){
					#scanIndex1<-5,scanIndex1<-1,scanIndex3<-1 for average number of dry spells >1 in a year
					StatDf<-rfStatInAYearDfFun(5,1,1,nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,stnName)
				}					
				#Daily log-odds ratio on annual basis df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,11))){
					if (nStation>1){
						StatDf<-annualCrsCorrlDfFun(0,0,2,nSim,nStation,statFile,nYrStat,stnNumber,stnName)	
					}
				}	
				#Cross-corrl of number wet days on annual basis df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,12))){
					if (nStation>1){
						StatDf<-annualCrsCorrlDfFun(1,2,1,nSim,nStation,statFile,nYrStat,stnNumber,stnName)
					}
				}					 
				#Mean of seasonal wet days df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,0))){
					wetDaysAnnualSeasonalMean<-matrix(scan(file=statFile,skip=0*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
					StatDf<-seasonalStatDfFun(wetDaysAnnualSeasonalMean,nSim,nStation,rfStatSelStn,stnNumber,stnName)
				}						 
				#SD of seasonal wet days df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,1))){
					wetDaysAnnualSeasonalSD<-matrix(scan(file=statFile,skip=3*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
					StatDf<-seasonalStatDfFun(wetDaysAnnualSeasonalSD,nSim,nStation,rfStatSelStn,stnNumber,stnName)
				}
				#Daily log-odds ratio on seasonal basis df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,2))){
					if (nStation>1){
						StatDf<-seasonalCrsCorrlDfFun(0,0,2,nSim,nStation,statFile,nYrStat,stnNumber,stnName)
					}
				}	
				#Cross-corrl of number wet days on seasonal basis df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,3))){
					if (nStation>1){
						StatDf<-seasonalCrsCorrlDfFun(1,2,1,nSim,nStation,statFile,nYrStat,stnNumber,stnName)
					}
				}					
				#Mean of monthly wet days df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,0))){
					#col=[2:13] for station 1
					wetDaysMonthlyMean<-matrix(scan(file=statFile,skip=6*(nSim+2)+1,nlines=nSim+1, quiet=TRUE),nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
					StatDf<-monthlyStatDfFun(wetDaysMonthlyMean,nSim,nStation,rfStatSelStn,stnNumber,stnName)
				}											
				#SD of monthly wet days df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,1))){
					#col=[2:13] for station 1
					wetDaysMonthlySD<-matrix(scan(file=statFile,skip=8*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
					StatDf<-monthlyStatDfFun(wetDaysMonthlySD,nSim,nStation,rfStatSelStn,stnNumber,stnName)														
				}				
				if (nStation>1) {
					model<-rGtkDataFrame(StatDf)
					model$setFrame(StatDf)
					column<-gtkTreeViewColumn()
					column$setTitle("Station Number")
					column$setSortColumnId(0)
					model$setSortColumnId (0,"ascending" )
					sorted_model<-gtkTreeModelSortNewWithModel(model)
					view<-gtkTreeView(sorted_model)
					mapply(view$insertColumnWithAttributes,position=-1,
						title=colnames(model),cell=list(gtkCellRendererText()),text=seq_len(ncol(model))-1)
					sapply(seq_len(ncol(model)),function(i)
						view$getColumn(i-1)$setSortColumnId(i-1))
					view$setHeadersClickable(TRUE)
					if (is.null(gtkCheckVersion(2, 10, 0))) view$setGridLines("both")	
					rfOccScrolledWindow<-gtkScrolledWindow()
					rfOccScrolledWindow$setSizeRequest(600,800)
					rfOccScrolledWindow$add(view)
					rfOccTable$attach(rfOccScrolledWindow,left.attach=1,2,top.attach=0,1,xoptions=c("shrink","fill"),yoptions="")	
				}
				else if (nStation==1 & any(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(0,11)) & 
					any(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(0,12)) & any(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(2,2)) &
					any(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(2,3))){
					model<-rGtkDataFrame(StatDf)
					model$setFrame(StatDf)
					column<-gtkTreeViewColumn()
					column$setTitle("Station Number")
					column$setSortColumnId(0)
					model$setSortColumnId (0,"ascending" )
					sorted_model<-gtkTreeModelSortNewWithModel(model)
					view<-gtkTreeView(sorted_model)
					mapply(view$insertColumnWithAttributes,position=-1,
						title=colnames(model),cell=list(gtkCellRendererText()),text=seq_len(ncol(model))-1)
					sapply(seq_len(ncol(model)),function(i)
						view$getColumn(i-1)$setSortColumnId(i-1))
					view$setHeadersClickable(TRUE)
					if (is.null(gtkCheckVersion(2, 10, 0))) view$setGridLines("both")	
					rfOccScrolledWindow<-gtkScrolledWindow()
					rfOccScrolledWindow$setSizeRequest(600,800)
					rfOccScrolledWindow$add(view)
					rfOccTable$attach(rfOccScrolledWindow,left.attach=1,2,top.attach=0,1,xoptions=c("shrink","fill"),yoptions="")	
				}
				else {rfOccPlotDeviceAdd()}	
			}
		}				
    }   
}
rfOccOptionSel<-rfOccOptionView$getSelection()
gSignalConnect(rfOccOptionSel,"changed",function(rfOccOptionSel,event,data){
	list<-readLines("option.dat")
	isuccess=as.numeric(list[2])
	if (isuccess==1){
		rfOccOptionFun()
	}

})
#save rfOcc view
gSignalConnect(rfOccSaveViewButton, "clicked", function(rfOccSaveViewButton,event,data){
	if(length(rfOccOptionSel$getSelectedRows()$retval)==1){  
		statFile<-"stat.out"
		#Read user-defined parameters
		parameters<-scan(file="data.dat",skip=2,nline=1,quiet = TRUE)
		nYr<-parameters[1]
		yrStart<-parameters[2]
		band<-parameters[3]
		nStation<-parameters[4]
		nSim<-parameters[5]
		nYrSim<-parameters[8]
		nYrStat<-max(parameters[8],parameters[1]) #multi_site_rain.f L4643
		list_data_fi=readLines("data.dat")
		inputRfFile<-list_data_fi[8]
		stnNumber<-read.table(inputRfFile,nrows=1)[2:(nStation+1)]	
	    stnName<-read.table(inputRfFile,skip=1,nrow=1,quote="\"")[2:(nStation+1)]
		#get view option from RadioButton gp
		sapply(rfOccViewOptionRadioGp,function(button,data){
			if(button['active']){
				list<-readLines("option.dat")
				list<-sub(list[4],button$getLabel(),list)
				writeLines(list,"option.dat") 
			}
		}) 
		list<-readLines("option.dat")
		rfOccViewOption<-list[4]
		rfStatSelStn<-rfOccStnCombo$getActiveText()
 		#rfOccPlotDeviceAdd()      				 				 														 																							
		if(length(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices())==2 & length(rfStatSelStn)>0){
			if (rfOccViewOption=="Plot"){
				if (nStation>1){				
					statPlot<-savePlotFileAs()
					if (statPlot!=""){
						#Mean of annual wet days plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,0))){
							wetDaysAnnualSeasonalMean<-matrix(scan(file=statFile,skip=0*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
								nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							mainLength<-nchar("Mean of annual wet days")
							annualStatPlotFun(wetDaysAnnualSeasonalMean,"Mean of annual wet days",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)					 					
						}
						#SD of annual wet days plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,1))){
							wetDaysAnnualSeasonalSD<-matrix(scan(file=statFile,skip=3*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
								nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)					 
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							mainLength<-nchar("SD of annual wet days")
							annualStatPlotFun(wetDaysAnnualSeasonalSD,"SD of annual wet days",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)						
						}	
						#Maximum wet spell lengths plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,2))){
							rfOccMaxSpell5th<-matrix(scan(file=statFile,skip=10*(nSim+2)+1,nlines=nSim+1),
								nrow=1+nSim,ncol=1+3*nStation,byrow=TRUE)												 
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							mainLength<-nchar("Maximum wet spell length")
							maxSpelllength5thRfAmtPlotFun(rfOccMaxSpell5th,2,"Maximum wet spell length",
								nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)	
						}
						#Maximum dry spell lengths plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,3))){
							rfOccMaxSpell5th<-matrix(scan(file=statFile,skip=10*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
								nrow=1+nSim,ncol=1+3*nStation,byrow=TRUE)						 						 
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							mainLength<-nchar("Maximum dry spell length")
							maxSpelllength5thRfAmtPlotFun(rfOccMaxSpell5th,3,"Maximum dry spell length",
								nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)	
						}
						#Average Occurrence of wet spells of varying lengths plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,4))){ 
							avgOccOfWS<-matrix(scan(file=statFile,skip=11*(nSim+2)+0*(nSim+3)+2,nlines=nSim+1,quiet = TRUE),
							nrow=1+nSim,ncol=1+4*nStation,byrow=TRUE)						 
							dev.new(width=6.25, height=6.25)
							avgOccW_DSpellsPlotSaveFun(avgOccOfWS,"1-day","2-4 days","5-7 days","> 7 days",
													"Average occurrence of wet spells of varying lengths",
													nSim,nStation,rfStatSelStn,stnNumber)
						}	
						#Average Occurrence of dry spells of varying lengths plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,5))){
							avgOccOfDS<-matrix(scan(file=statFile,skip=11*(nSim+2)+2*(nSim+3)+2,nlines=nSim+1,quiet = TRUE),
								nrow=1+nSim,ncol=1+4*nStation,byrow=TRUE)						 						
							dev.new(width=6.25, height=6.25)
							avgOccW_DSpellsPlotSaveFun(avgOccOfDS,"1-day","2-9 days","9-18 days","> 18 days",
								"Average occurrence of dry spells of varying lengths",
								nSim,nStation,rfStatSelStn,stnNumber)
						}	
						#Number of wet days in a year plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,6))){
							#scanIndex1<-1,scanIndex2<-0,scanIndex3<-2 for number of wet days in a year
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							mainLength<-nchar("Number of wet days in a year")
							rfStatInAYearPlotFun(1,0,2,"Number of wet days in a year",
								nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)
						}	
						#Maximum wet spell length in a year plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,7))){
							#scanIndex1<-3,scanIndex2<-0,scanIndex3<-2 for maximum wet spell length in a year 
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							mainLength<-nchar("Maximum wet spell length in a year")
							rfStatInAYearPlotFun(3,0,2,"Maximum wet spell length in a year",
								nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)							 
						}	
						#Average number of wet spells > 1 in a year plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,8))){
							#scanIndex1<-4,scanIndex2<-0,scanIndex3<-2 for average numer of wet spells>1 in a year			
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							mainLength<-nchar("Average number of wet spells > 1 in a year")
							rfStatInAYearPlotFun(4,0,2,"Average number of wet spells > 1 in a year",
								nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)
						}
						#Maximum dry spell length in a year plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,9))){
							#scanIndex1<-5,scanIndex2<-0,scanIndex3<-1 for maximum dry spell length in a year
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							mainLength<-nchar("Maximum dry spell length in a year")
							rfStatInAYearPlotFun(5,0,1,"Maximum dry spell length in a year",
								nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)
						}	
						#Average number of dry spells > 1 in a year plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,10))){
							#scanIndex1<-5,scanIndex1<-1,scanIndex3<-1 for average number of dry spells >1 in a year						 
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							mainLength<-"Average number of dry spells >1 in a year"
							rfStatInAYearPlotFun(5,1,1,"Average number of dry spells >1 in a year",
								nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)
						}	
						#Daily log-odds ratio on annual basis
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,11))){
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							if	(nStation>1){
								annualCrsCorrlPlotFun(0,0,2,"Daily log-odds ratio on annual basis",nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)		
							}
						}	
						#Cross-corrl of number wet days on annual basis
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,12))){
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							if (nStation>1){
								annualCrsCorrlPlotFun(1,2,1,c("Cross-correlation of the number of", "\nwet days on annual basis"),nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)						
							}
						}					 
						#Mean of seasonal wet days plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,0)))	
							{
							wetDaysAnnualSeasonalMean<-matrix(scan(file=statFile,skip=0*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
							dev.new(width=6.25, height=6.25)
							seasonalStatPlotSaveFun(wetDaysAnnualSeasonalMean,"Mean of seasonal wet days",nSim,nStation,rfStatSelStn,stnNumber)
							}	
						#SD of seasonal wet days plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,1)))	
							{
							wetDaysAnnualSeasonalSD<-matrix(scan(file=statFile,skip=3*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
							dev.new(width=6.25, height=6.25)
							seasonalStatPlotSaveFun(wetDaysAnnualSeasonalSD,"SD of seasonal wet days",nSim,nStation,rfStatSelStn,stnNumber)
							}
						#Daily log-odds ratio on seasonal basis
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,2))){
							dev.new(width=6.25, height=6.25)
							fontsize<-0.8
							linewidth<-1
							if (nStation>1){
								seasonalCrsCorrlSavePlotFun(0,0,2,"Daily log-odds ratio on seasonal basis",nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)						
							}
						}	
						#Cross-corrl of number wet days on seasonal basis
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,3))){
							dev.new(width=6.25, height=6.25)
							fontsize<-0.8
							linewidth<-1
							if (nStation>1){
								seasonalCrsCorrlSavePlotFun(1,2,1,c("Cross-correlation of the number of wet days","\non seasonal basis"),nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)						
							}
						}				 
						#Mean of monthly wet days plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,0)))	
							{
							#col=[2:13] for station 1
							wetDaysMonthlyMean<-matrix(scan(file=statFile,skip=6*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
							if (rfStatSelStn=="All stations") {dev.new(width=6.25, height=8.33)}
							else {dev.new(width=6.25, height=6.25)}
							mainLength<-nchar("Mean of monthly wet days")
							monthlyStatPlotSaveFun(wetDaysMonthlyMean,"Mean of monthly wet days",nSim,nStation,rfStatSelStn,stnNumber,mainLength)
							}	
						#SD of monthly wet days plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,1))){
							#col=[2:13] for station 1
							wetDaysMonthlySD<-matrix(scan(file=statFile,skip=8*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
								nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
							if (rfStatSelStn=="All stations") {dev.new(width=6.25, height=8.33)}
							else {dev.new(width=6.25, height=6.25)}
							mainLength<-nchar("SD of monthly wet days")
							monthlyStatPlotSaveFun(wetDaysMonthlySD,"SD of monthly wet days",nSim,nStation,rfStatSelStn,stnNumber,mainLength)														
						}
						savePlot(filename = statPlot,type = getExt(statPlot),device = dev.cur(),restoreConsole = TRUE)
						dev.off()
					}
				}
				else if (nStation==1 & any(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(0,11)) & 
					any(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(0,12)) & any(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(2,2)) &
					any(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(2,3))){
					statPlot<-savePlotFileAs()
					if (statPlot!=""){
						#Mean of annual wet days plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,0))){
							wetDaysAnnualSeasonalMean<-matrix(scan(file=statFile,skip=0*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
								nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							mainLength<-nchar("Mean of annual wet days")
							annualStatPlotFun(wetDaysAnnualSeasonalMean,"Mean of annual wet days",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)					 					
						}
						#SD of annual wet days plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,1))){
							wetDaysAnnualSeasonalSD<-matrix(scan(file=statFile,skip=3*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
								nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)					 
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							mainLength<-nchar("SD of annual wet days")
							annualStatPlotFun(wetDaysAnnualSeasonalSD,"SD of annual wet days",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)						
						}	
						#Maximum wet spell lengths plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,2))){
							rfOccMaxSpell5th<-matrix(scan(file=statFile,skip=10*(nSim+2)+1,nlines=nSim+1),
								nrow=1+nSim,ncol=1+3*nStation,byrow=TRUE)												 
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							mainLength<-nchar("Maximum wet spell length")
							maxSpelllength5thRfAmtPlotFun(rfOccMaxSpell5th,2,"Maximum wet spell length",
								nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)	
						}
						#Maximum dry spell lengths plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,3))){
							rfOccMaxSpell5th<-matrix(scan(file=statFile,skip=10*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
								nrow=1+nSim,ncol=1+3*nStation,byrow=TRUE)						 						 
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							mainLength<-nchar("Maximum dry spell length")
							maxSpelllength5thRfAmtPlotFun(rfOccMaxSpell5th,3,"Maximum dry spell length",
								nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)	
						}
						#Average Occurrence of wet spells of varying lengths plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,4))){ 
							avgOccOfWS<-matrix(scan(file=statFile,skip=11*(nSim+2)+0*(nSim+3)+2,nlines=nSim+1,quiet = TRUE),
							nrow=1+nSim,ncol=1+4*nStation,byrow=TRUE)						 
							dev.new(width=6.25, height=6.25)
							avgOccW_DSpellsPlotSaveFun(avgOccOfWS,"1-day","2-4 days","5-7 days","> 7 days",
													"Average occurrence of wet spells of varying lengths",
													nSim,nStation,rfStatSelStn,stnNumber)
						}	
						#Average Occurrence of dry spells of varying lengths plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,5))){
							avgOccOfDS<-matrix(scan(file=statFile,skip=11*(nSim+2)+2*(nSim+3)+2,nlines=nSim+1,quiet = TRUE),
								nrow=1+nSim,ncol=1+4*nStation,byrow=TRUE)						 						
							dev.new(width=6.25, height=6.25)
							avgOccW_DSpellsPlotSaveFun(avgOccOfDS,"1-day","2-9 days","9-18 days","> 18 days",
								"Average occurrence of dry spells of varying lengths",
								nSim,nStation,rfStatSelStn,stnNumber)
						}	
						#Number of wet days in a year plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,6))){
							#scanIndex1<-1,scanIndex2<-0,scanIndex3<-2 for number of wet days in a year
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							mainLength<-nchar("Number of wet days in a year")
							rfStatInAYearPlotFun(1,0,2,"Number of wet days in a year",
								nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)
						}	
						#Maximum wet spell length in a year plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,7))){
							#scanIndex1<-3,scanIndex2<-0,scanIndex3<-2 for maximum wet spell length in a year 
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							mainLength<-nchar("Maximum wet spell length in a year")
							rfStatInAYearPlotFun(3,0,2,"Maximum wet spell length in a year",
								nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)							 
						}	
						#Average number of wet spells > 1 in a year plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,8))){
							#scanIndex1<-4,scanIndex2<-0,scanIndex3<-2 for average numer of wet spells>1 in a year			
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							mainLength<-nchar("Average number of wet spells > 1 in a year")
							rfStatInAYearPlotFun(4,0,2,"Average number of wet spells > 1 in a year",
								nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)
						}
						#Maximum dry spell length in a year plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,9))){
							#scanIndex1<-5,scanIndex2<-0,scanIndex3<-1 for maximum dry spell length in a year
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							mainLength<-nchar("Maximum dry spell length in a year")
							rfStatInAYearPlotFun(5,0,1,"Maximum dry spell length in a year",
								nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)
						}	
						#Average number of dry spells > 1 in a year plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,10))){
							#scanIndex1<-5,scanIndex1<-1,scanIndex3<-1 for average number of dry spells >1 in a year						 
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							mainLength<-"Average number of dry spells >1 in a year"
							rfStatInAYearPlotFun(5,1,1,"Average number of dry spells >1 in a year",
								nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)
						}	
						#Daily log-odds ratio on annual basis
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,11))){
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							if	(nStation>1){
								annualCrsCorrlPlotFun(0,0,2,"Daily log-odds ratio on annual basis",nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)		
							}
						}	
						#Cross-corrl of number wet days on annual basis
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,12))){
							dev.new(width=6.25, height=6.25)
							fontsize<-1.5
							linewidth<-2
							if (nStation>1){
								annualCrsCorrlPlotFun(1,2,1,c("Cross-correlation of the number of", "\nwet days on annual basis"),nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)						
							}
						}					 
						#Mean of seasonal wet days plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,0)))	
							{
							wetDaysAnnualSeasonalMean<-matrix(scan(file=statFile,skip=0*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
							dev.new(width=6.25, height=6.25)
							seasonalStatPlotSaveFun(wetDaysAnnualSeasonalMean,"Mean of seasonal wet days",nSim,nStation,rfStatSelStn,stnNumber)
							}	
						#SD of seasonal wet days plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,1)))	
							{
							wetDaysAnnualSeasonalSD<-matrix(scan(file=statFile,skip=3*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
							dev.new(width=6.25, height=6.25)
							seasonalStatPlotSaveFun(wetDaysAnnualSeasonalSD,"SD of seasonal wet days",nSim,nStation,rfStatSelStn,stnNumber)
							}
						#Daily log-odds ratio on seasonal basis
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,2))){
							dev.new(width=6.25, height=6.25)
							fontsize<-0.8
							linewidth<-1
							if (nStation>1){
								seasonalCrsCorrlSavePlotFun(0,0,2,"Daily log-odds ratio on seasonal basis",nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)						
							}
						}	
						#Cross-corrl of number wet days on seasonal basis
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,3))){
							dev.new(width=6.25, height=6.25)
							fontsize<-0.8
							linewidth<-1
							if (nStation>1){
								seasonalCrsCorrlSavePlotFun(1,2,1,c("Cross-correlation of the number of wet days","\non seasonal basis"),nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)						
							}
						}				 
						#Mean of monthly wet days plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,0)))	
							{
							#col=[2:13] for station 1
							wetDaysMonthlyMean<-matrix(scan(file=statFile,skip=6*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
							if (rfStatSelStn=="All stations") {dev.new(width=6.25, height=8.33)}
							else {dev.new(width=6.25, height=6.25)}
							mainLength<-nchar("Mean of monthly wet days")
							monthlyStatPlotSaveFun(wetDaysMonthlyMean,"Mean of monthly wet days",nSim,nStation,rfStatSelStn,stnNumber,mainLength)
							}	
						#SD of monthly wet days plot
						if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,1))){
							#col=[2:13] for station 1
							wetDaysMonthlySD<-matrix(scan(file=statFile,skip=8*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
								nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
							if (rfStatSelStn=="All stations") {dev.new(width=6.25, height=8.33)}
							else {dev.new(width=6.25, height=6.25)}
							mainLength<-nchar("SD of monthly wet days")
							monthlyStatPlotSaveFun(wetDaysMonthlySD,"SD of monthly wet days",nSim,nStation,rfStatSelStn,stnNumber,mainLength)														
						}
						savePlot(filename = statPlot,type = getExt(statPlot),device = dev.cur(),restoreConsole = TRUE)
						dev.off()
					}
				}
			}		
			if (rfOccViewOption=="Grid"){
				#Mean of annual wet days df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,0))){
					wetDaysAnnualSeasonalMean<-matrix(scan(file=statFile,skip=0*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
					nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
					StatDf<-annualStatDfFun(wetDaysAnnualSeasonalMean,nSim,nStation,rfStatSelStn,stnNumber,stnName)					 					
				}											 
				#SD of annual wet days df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,1))){
					wetDaysAnnualSeasonalSD<-matrix(scan(file=statFile,skip=3*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
						nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
					StatDf<-annualStatDfFun(wetDaysAnnualSeasonalSD,nSim,nStation,rfStatSelStn,stnNumber,stnName)						
				}						 					 
				#Maximum wet spell lengths df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,2))){
					rfOccMaxSpell5th<-matrix(scan(file=statFile,skip=10*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
						nrow=1+nSim,ncol=1+3*nStation,byrow=TRUE)						 
					StatDf<-maxSpelllength5thRfAmtDfFun(rfOccMaxSpell5th,2,nSim,nStation,rfStatSelStn,stnNumber,stnName)	
				}										 
				#Maximum dry spell lengths df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,3))){
					rfOccMaxSpell5th<-matrix(scan(file=statFile,skip=10*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+3*nStation,byrow=TRUE)					 
					StatDf<-maxSpelllength5thRfAmtDfFun(rfOccMaxSpell5th,3,nSim,nStation,rfStatSelStn,stnNumber,stnName)	
				}																		 
				#Average Occurrence of wet spells of varying lengths df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,4))){ 
					avgOccOfWS<-matrix(scan(file=statFile,skip=11*(nSim+2)+0*(nSim+3)+2,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+4*nStation,byrow=TRUE)
					StatDf<-avgOccW_DSpellsDfFun(avgOccOfWS,"1-day","2-4 days","5-7 days","> 7 days","Wet Spell length",nSim,nStation,rfStatSelStn,stnNumber,stnName)
				}						 						
				#Average Occurrence of dry spells of varying lengths df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,5))){
					avgOccOfDS<-matrix(scan(file=statFile,skip=11*(nSim+2)+2*(nSim+3)+2,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+4*nStation,byrow=TRUE)
					StatDf<-avgOccW_DSpellsDfFun(avgOccOfDS,"1-day","2-9 days","9-18 days","> 18 days","Dry Spell length",nSim,nStation,rfStatSelStn)
				}												 
				#Number of wet days in a year df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,6))){
					#scanIndex1<-1,scanIndex2<-0,scanIndex3<-2 for number of wet days in a year
					StatDf<-rfStatInAYearDfFun(1,0,2,nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,stnName)
				}					 
				#Maximum wet spell length in a year df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,7))){
					#scanIndex1<-3,scanIndex2<-0,scanIndex3<-2 for maximum wet spell length in a year 
					StatDf<-rfStatInAYearDfFun(3,0,2,nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,stnName)							 
				}					 											
				#Average number of wet spells > 1 in a year df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,8))){
					#scanIndex1<-4,scanIndex2<-0,scanIndex3<-2 for average numer of wet spells>1 in a year
					StatDf<-rfStatInAYearDfFun(4,0,2,nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,stnName)
				}										
				#Maximum dry spell length in a year df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,9))){
					#scanIndex1<-5,scanIndex2<-0,scanIndex3<-1 for maximum dry spell length in a year
					StatDf<-rfStatInAYearDfFun(5,0,1,nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,stnName)
				}					 
				#Average number of dry spells > 1 in a year df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,10))){
					#scanIndex1<-5,scanIndex1<-1,scanIndex3<-1 for average number of dry spells >1 in a year
					StatDf<-rfStatInAYearDfFun(5,1,1,nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,stnName)
				}					
				#Daily log-odds ratio on annual basis
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,11))){
					if (nStation>1){
						StatDf<-annualCrsCorrlDfFun(0,0,2,nSim,nStation,statFile,nYrStat,stnNumber,stnName)
					}						
				}	
				#Cross-corrl of number wet days on annual basis
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,12))){
					if (nStation>1){
						StatDf<-annualCrsCorrlDfFun(1,2,1,nSim,nStation,statFile,nYrStat,stnNumber,stnName)			
					}
				}							 
				#Mean of seasonal wet days df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,0))){
					wetDaysAnnualSeasonalMean<-matrix(scan(file=statFile,skip=0*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
					StatDf<-seasonalStatDfFun(wetDaysAnnualSeasonalMean,nSim,nStation,rfStatSelStn,stnNumber,stnName)
				}						 
				#SD of seasonal wet days df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,1))){
					wetDaysAnnualSeasonalSD<-matrix(scan(file=statFile,skip=3*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
					StatDf<-seasonalStatDfFun(wetDaysAnnualSeasonalSD,nSim,nStation,rfStatSelStn,stnNumber,stnName)
				}
				#Daily log-odds ratio on seasonal basis df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,2))){
					if (nStation>1){
						StatDf<-seasonalCrsCorrlDfFun(0,0,2,nSim,nStation,statFile,nYrStat,stnNumber,stnName)
					}
				}	
				#Cross-corrl of number wet days on seasonal basis df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,3))){
					if(nStation>1){
						StatDf<-seasonalCrsCorrlDfFun(1,2,1,nSim,nStation,statFile,nYrStat,stnNumber,stnName)
					}
				}						
				#Mean of monthly wet days df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,0))){
					#col=[2:13] for station 1
					wetDaysMonthlyMean<-matrix(scan(file=statFile,skip=6*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
					StatDf<-monthlyStatDfFun(wetDaysMonthlyMean,nSim,nStation,rfStatSelStn,stnNumber,stnName)
				}											
				#SD of monthly wet days df
				if (all(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,1))){
					#col=[2:13] for station 1
					wetDaysMonthlySD<-matrix(scan(file=statFile,skip=8*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
					StatDf<-monthlyStatDfFun(wetDaysMonthlySD,nSim,nStation,rfStatSelStn,stnNumber,stnName)														
				}
				if (nStation>1){
					gridFile<-saveGridFileAs()
					if (gridFile!="") {
						write.table(StatDf, file = gridFile, append = FALSE, quote = TRUE,sep = " ",dec = ".",
						row.names = FALSE,col.names = TRUE, qmethod = "double",fileEncoding = "")
					}								
				}
				else if (nStation==1 & any(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(0,11)) & 
					any(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(0,12)) & any(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(2,2)) &
					any(rfOccOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(2,3))){
					gridFile<-saveGridFileAs()
					if (gridFile!="") {
						write.table(StatDf, file = gridFile, append = FALSE, quote = TRUE,sep = " ",dec = ".",
						row.names = FALSE,col.names = TRUE, qmethod = "double",fileEncoding = "")
					}
				}								
			}
			
		}
	}
})
#Rainfall amount page
notebookStat$appendPage(rfAmtTable,gtkLabel("Rainfall Amount "))
rfAmtOptionFrame<-gtkFrame("Rainfall Amount")
rfAmtTable$attach(rfAmtOptionFrame,left.attach=0,1,top.attach=0,1,
	xoptions=c("shrink","fill"),yoptions="",ypadding=0)
aggregationList<-c("Annual","Seasonal","Monthly")
rfAmtAnnualList<-c("mean","SD","5th% (mm)",
	"mean per wet day","SD per wet day",
	"average in a year","maximum in a year",
	"total in wet spells of varying lengths",
	"daily cross-correlation of rainfall in wet days",
	"daily cross-correlation of rainfall in all days",
	"cross-correlation")
rfAmtSeasonalList<-c("mean","SD","mean per wet day","SD per wet day",
	"daily cross-correlation of rainfall in wet days",
	"daily cross-correlation of rainfall in all days",
	"cross-correlation")
rfAmtMonthlyList<-c("mean","SD")
rfAmtOption<-data.frame(aggregation=c(rep("Annual",length(rfAmtAnnualList)),
	rep("Seasonal",length(rfAmtSeasonalList)),
	rep("Monthly",length(rfAmtMonthlyList))),
	rfAmtStat=c(rfAmtAnnualList,rfAmtSeasonalList,rfAmtMonthlyList))
rfAmtOptionModel<-gtkTreeStore("gchararray")
by (rfAmtOption,rfAmtOption$aggregation,function(DF1){
	parent_iter <- rfAmtOptionModel$append()
	rfAmtOptionModel$setValue(parent_iter$iter,column = 0,value = DF1$aggregation)
	sapply ( DF1$rfAmtStat, function (rfAmtStat){
		child_iter <- rfAmtOptionModel$append(parent = parent_iter$iter)
		if (is.null(child_iter$retval))
		rfAmtOptionModel$setValue(child_iter$iter,column = 0 ,value = rfAmtStat)
	})
})
rfAmtOptionView<-gtkTreeView()
rfAmtOptionView$getSelection()$setMode("browse")
rfAmtOptionView$insertColumnWithAttributes(0,"              ",gtkCellRendererText(),text=0)
rfAmtOptionView$setModel(rfAmtOptionModel)
rfAmtScrolledWindow<-gtkScrolledWindow()
rfAmtScrolledWindow$setSizeRequest(200,800)
rfAmtScrolledWindow$add(rfAmtOptionView)
rfAmtOptionFrame$add(rfAmtScrolledWindow)							
#Function to view rainfall amount statistics 
rfAmtOptionFun<-function(){
	if (length(dev.list())>1) dev.off()
	#Read user-defined parameters
	parameters<-scan(file="data.dat",skip=2,nline=1,quiet = TRUE)
	nYr<-parameters[1]
	yrStart<-parameters[2]
	band<-parameters[3]
	nStation<-parameters[4]
	nSim<-parameters[5]
	nYrSim<-parameters[8]
	nYrStat<-max(parameters[8],parameters[1])#multi_site_rain.f L4643
	amt<-parameters[10]
	if (amt==1){
		if(length(rfAmtOptionSel$getSelectedRows()$retval)==1){
			sapply(rfAmtViewOptionRadioGp,function(button,data){ 
				if(button['active']){
				list<-readLines("option.dat")
				list<-sub(list[6],button$getLabel(),list)
				writeLines(list,"option.dat") 
				}
			}) 
			list<-readLines("option.dat")
			rfAmtViewOption<-list[6]
			rfStatSelStn<-rfAmtStnCombo$getActiveText()		 
			statFile<-"stat.out"
			list_data_fi=readLines("data.dat")
			inputRfFile<-list_data_fi[8]
			stnNumber<-read.table(inputRfFile,nrows=1)[2:(nStation+1)]	
			stnName<-read.table(inputRfFile,skip=1,nrow=1,quote="\"")[2:(nStation+1)]
			if (length(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices())==2 & length(rfStatSelStn)>0){
				if (rfAmtViewOption=="Plot"){
					rfAmtPlotDeviceAdd()
					#Mean of annual rf amt plot
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,0))){
						rfAmtAnnualSeasonalMean<-matrix(scan(file=statFile,skip=(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						fontsize<-1.5
						linewidth<-2
						mainLength<-nchar("Mean of annual rainfall amount")
						annualStatPlotFun(rfAmtAnnualSeasonalMean,"Mean of annual rainfall amount",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)
					}
					#SD of annual rf amt plot
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,1))){
						rfAmtAnnualSeasonalSD<-matrix(scan(file=statFile,skip=4*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						fontsize<-1.5 #STOP HERE
						linewidth<-2
						mainLength<-nchar("SD of annual rainfall amount")
						annualStatPlotFun(rfAmtAnnualSeasonalSD,"SD of annual rainfall amount",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)
					}
					#5th percentile of rf amt plot
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,2))){
						MaxSpell5thRfAmt<-matrix(scan(file=statFile,skip=10*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+3*nStation,byrow=TRUE)
						fontsize<-1.5
						linewidth<-2
						mainLength<-nchar("5th percentile of daily rainfall amount")
						maxSpelllength5thRfAmtPlotFun(MaxSpell5thRfAmt,4,"5th percentile of daily rainfall amount",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)													
					}
					#Mean of annual rf amt per wet day plot
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,3))){
						rfAmtAnnualSeasonalMeanPWD<-matrix(scan(file=statFile,skip=2*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						fontsize<-1.5
						linewidth<-2
						mainLength=nchar("Mean of annual rainfall amount per wet day")
						annualStatPlotFun(rfAmtAnnualSeasonalMeanPWD,"Mean of annual rainfall amount per wet day",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)
					}
					#SD of annual rf amt per wet day plot
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,4))){
						rfAmtAnnualSeasonalSDPWD<-matrix(scan(file=statFile,skip=5*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						fontsize<-1.5
						linewidth<-2
						mainLength<-nchar("SD of annual rainfall amount per wet day")
						annualStatPlotFun(rfAmtAnnualSeasonalSDPWD,"SD of annual rainfall amount per wet day",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)
					}
					#Average rf amt in a year plot
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,5))){
						#scanIndex<-2 for average rf amt in a year
						fontsize<-1.5
						linewidth<-2
						mainLength<-nchar("Average rainfall in a year")
						rfStatInAYearPlotFun(2,0,2,"Average rainfall in a year",nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)								 				
					}
					#Maximum rf amt in a year plot
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,6))){
						#scanIndex<-0 for maximum rf amt in a year						
						fontsize<-1.5
						linewidth<-2					
						mainLength<-nchar("Maximum rainfall amount in a year")
						rfStatInAYearPlotFun(0,0,2,"Maximum rainfall amount in a year",nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)					
					}
					#Total rf amt in wet spells of varying lengths plot
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,7))){
						totRfAmtInWS<-matrix(scan(file=statFile,skip=11*(nSim+2)+1*(nSim+3)+2,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+4*nStation,byrow=TRUE)
						fontsize<-1.2
						linewidth<-1
						totRfAmtInWSPlotFun(totRfAmtInWS,"1-day","2-4 days","5-7 days","> 7 days",
							"Total rainfall wet spells of varying lengths",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth)						
					}						
					#Daily crs-corrl of rf-wet days on annual basis
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,8))){
						fontsize<-1.5
						linewidth<-2
						if (nStation>1){
							annualCrsCorrlPlotFun(1,0,1,c("Daily cross-correlation of rainfall", "\n in wet days on annual basis"),nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)
						}
					}	
					#Daily crs-corrl of rf-all days on annual basis
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,9))){
						fontsize<-1.5
						linewidth<-2
						if (nStation>1){
							annualCrsCorrlPlotFun(1,1,1,c("Daily cross-correlation of rainfall", "\nin all days on annual basis"),nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)
						}
					}
					#Cross-corrl of annual rainfall
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,10))){
						fontsize<-1.5
						linewidth<-2
						if (nStation>1){
							annualCrsCorrlPlotFun(1,3,1,"Cross-correlation of annual rainfall",nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)						
						}
					}
					#Mean of seasonal rf amt plot
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,0))){
						rfAmtAnnualSeasonalMean<-matrix(scan(file=statFile,skip=(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						fontsize<-1.2
						linewidth<-1
						mainLength<-nchar("Mean of seasonal rainfall amount")
						seasonalStatPlotFun(rfAmtAnnualSeasonalMean,"Mean of seasonal rainfall amount",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)
					}	
					#SD of seasonal rf amt plot
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,1))){
						rfAmtAnnualSeasonalSD<-matrix(scan(file=statFile,skip=4*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						fontsize<-1.2
						linewidth<-1
						mainLength<-nchar("SD of seasonal rainfall amount")
						seasonalStatPlotFun(rfAmtAnnualSeasonalSD,"SD of seasonal rainfall amount",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)						 
					}
					#Mean of seasonal rf amt per wet day plot
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,2))){
						rfAmtAnnualSeasonalMeanPWD<-matrix(scan(file=statFile,skip=2*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						fontsize<-1.2
						linewidth<-1
						mainLength<-nchar("Mean of seasonal rainfall amount per wet day")
						seasonalStatPlotFun(rfAmtAnnualSeasonalMeanPWD,"Mean of seasonal rainfall amount per wet day",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)	
					}
					#SD of seasonal rf amt per wet day plot
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,3))){
						rfAmtAnnualSeasonalSDPWD<-matrix(scan(file=statFile,skip=5*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						fontsize<-1.2
						linewidth<-1
						mainLength<-nchar("SD of seasonal rainfall amount per wet day")
						seasonalStatPlotFun(rfAmtAnnualSeasonalSDPWD,"SD of seasonal rainfall amount per wet day",nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)
					}
					#Daily crs-corrl of rf-wet days on seasonal basis
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,4))){
						fontsize<-1.2
						linewidth<-1
						if (nStation>1){
							seasonalCrsCorrlPlotFun(1,0,1,c("Daily cross-correlation of rainfall","\nin wet days on seasonal basis"),nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)	
						}
					}	
					#Daily crs-corrl of rf-all days on seasonal basis
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,5))){
						fontsize<-1.2
						linewidth<-1
						if (nStation>1){
							seasonalCrsCorrlPlotFun(1,1,1,c("Daily cross-correlation of rainfall","\nin all days on seasonal basis"),nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)						
						}
					}
					#Cross-corrl of seasonal rainfall
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,6))){
						fontsize<-1.2
						linewidth<-1
						if (nStation>1){
						seasonalCrsCorrlPlotFun(1,3,1,"Cross-correlation of seasonal rainfall",nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)
						}
					}
					#Mean of monthly rf amt plot
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,0))){
						#col=[2:13] for station 1
						rfAmtMonthlyMean<-matrix(scan(file=statFile,skip=7*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
						mainLength<-nchar("Mean of monthly rainfall amount")
						monthlyStatPlotFun(rfAmtMonthlyMean,"Mean of monthly rainfall amount",nSim,nStation,rfStatSelStn,stnNumber,mainLength)
					}					 
					#SD of monthly rf amt plot
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,1))){
						#col=[2:13] for station 1
						rfAmtMonthlySD<-matrix(scan(file=statFile,skip=9*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
						mainLength<-nchar("SD of monthly rainfall amount")
						monthlyStatPlotFun(rfAmtMonthlySD,"SD of monthly rainfall amount",nSim,nStation,rfStatSelStn,stnNumber,mainLength)
					}
																				
				}
				if (rfAmtViewOption=="Grid"){
					#Mean of annual rf amt df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,0))){
						rfAmtAnnualSeasonalMean<-matrix(scan(file=statFile,skip=(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						StatDf<-annualStatDfFun(rfAmtAnnualSeasonalMean,nSim,nStation,rfStatSelStn,stnNumber,stnName)			
					}					
					#SD of annual rf amt df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,1))){
						rfAmtAnnualSeasonalSD<-matrix(scan(file=statFile,skip=4*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						StatDf<-annualStatDfFun(rfAmtAnnualSeasonalSD,nSim,nStation,rfStatSelStn,stnNumber,stnName)								 
					}											 						
					#5th percentile of rf df 
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,2))){
						MaxSpell5thRfAmt<-matrix(scan(file=statFile,skip=10*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+3*nStation,byrow=TRUE)
						StatDf<-maxSpelllength5thRfAmtDfFun(MaxSpell5thRfAmt,4,nSim,nStation,rfStatSelStn,stnNumber,stnName)													
					}						
					#Mean of annual rf amt per wet day df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,3))){
						rfAmtAnnualSeasonalMeanPWD<-matrix(scan(file=statFile,skip=2*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						StatDf<-annualStatDfFun(rfAmtAnnualSeasonalMeanPWD,nSim,nStation,rfStatSelStn,stnNumber,stnName)
					}					 
					#SD of annual rf amt per wet day df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,4))){
						rfAmtAnnualSeasonalSDPWD<-matrix(scan(file=statFile,skip=5*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						StatDf<-annualStatDfFun(rfAmtAnnualSeasonalSDPWD,nSim,nStation,rfStatSelStn,stnNumber,stnName)
					}
					#Average rf amt in a year df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,5))){
						#scanIndex<-2 for average rf amt in a year
						StatDf<-rfStatInAYearDfFun(2,0,2,nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,stnName)								 				
					}					 					 
					#Maximum rf amt in a year df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,6))){
						#scanIndex<-0 for maximum rf amt in a year						 
						StatDf<-rfStatInAYearDfFun(0,0,2,nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,stnName)					
					}					 
					#Total rf amt in wet spells of varying lengths df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,7))){
						totRfAmtInWS<-matrix(scan(file=statFile,skip=11*(nSim+2)+1*(nSim+3)+2,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+4*nStation,byrow=TRUE)
						StatDf<-totRfAmtInWSDfFun(totRfAmtInWS,"1-day","2-4 days","5-7 days","> 7 days","Wet Spell Lengths",nSim,nStation,rfStatSelStn,stnNumber,stnName)						
					}						
					#Daily crs-corrl of rf-wet days on annual basis
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,8))){
						if (nStation>1){
							StatDf<-annualCrsCorrlDfFun(1,0,1,nSim,nStation,statFile,nYrStat,stnNumber,stnName)
						}
					}	
					#Daily crs-corrl of rf-all days on annual basis
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,9))){
						if (nStation>1){
							StatDf<-annualCrsCorrlDfFun(1,1,1,nSim,nStation,statFile,nYrStat,stnNumber,stnName)
						}
					}
					#Cross-corrl of annual rainfall
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,10))){
						if (nStation>1){
							StatDf<-annualCrsCorrlDfFun(1,3,1,nSim,nStation,statFile,nYrStat,stnNumber,stnName)
						}
					}										
					#Mean of seasonal rf amt df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,0))){
						rfAmtAnnualSeasonalMean<-matrix(scan(file=statFile,skip=(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						StatDf<-seasonalStatDfFun(rfAmtAnnualSeasonalMean,nSim,nStation,rfStatSelStn,stnNumber,stnName)
					}					 					 
					#SD of seasonal rf amt df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,1))){
						rfAmtAnnualSeasonalSD<-matrix(scan(file=statFile,skip=4*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						StatDf<-seasonalStatDfFun(rfAmtAnnualSeasonalSD,nSim,nStation,rfStatSelStn,stnNumber,stnName)						 
					}						
					#Mean of seasonal rf amt per wet day df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,2))){
					rfAmtAnnualSeasonalMeanPWD<-matrix(scan(file=statFile,skip=2*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
					StatDf<-seasonalStatDfFun(rfAmtAnnualSeasonalMeanPWD,nSim,nStation,rfStatSelStn,stnNumber,stnName)	
					}					 
					#SD of seasonal rf amt per wet day df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,3))){
					rfAmtAnnualSeasonalSDPWD<-matrix(scan(file=statFile,skip=5*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
					StatDf<-seasonalStatDfFun(rfAmtAnnualSeasonalSDPWD,nSim,nStation,rfStatSelStn,stnNumber,stnName)
					}
					#Daily crs-corrl of rf-wet days on seasonal basis
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,4))){
						if (nStation>1){
							StatDf<-seasonalCrsCorrlDfFun(1,0,1,nSim,nStation,statFile,nYrStat,stnNumber,stnName)
						}
					}	
					#Daily crs-corrl of rf-all days on seasonal basis
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,5))){
						if (nStation>1){
							StatDf<-seasonalCrsCorrlDfFun(1,1,1,nSim,nStation,statFile,nYrStat,stnNumber,stnName)
						}
					}
					#Cross-corrl of seasonal rainfall
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,6))){
						if (nStation>1){
							StatDf<-seasonalCrsCorrlDfFun(1,3,1,nSim,nStation,statFile,nYrStat,stnNumber,stnName)
						}
					}				 				 
					#Mean of monthly rf amt df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,0)))
					{
					#col=[2:13] for station 1
					rfAmtMonthlyMean<-matrix(scan(file=statFile,skip=7*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
					StatDf<-monthlyStatDfFun(rfAmtMonthlyMean,nSim,nStation,rfStatSelStn,stnNumber,stnName)
					}											 
					#SD of monthly rf amt df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,1))){
						#col=[2:13] for station 1
						rfAmtMonthlySD<-matrix(scan(file=statFile,skip=9*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
						StatDf<-monthlyStatDfFun(rfAmtMonthlySD,nSim,nStation,rfStatSelStn,stnNumber,stnName)
					}	
					if (nStation>1){
						model<-rGtkDataFrame(StatDf)
						model$setFrame(StatDf)
						column<-gtkTreeViewColumn()
						column$setTitle("Station Number")
						column$setSortColumnId(0)
						model$setSortColumnId (0,"ascending" )
						sorted_model<-gtkTreeModelSortNewWithModel(model)
						view<-gtkTreeView(sorted_model)
						mapply(view$insertColumnWithAttributes,position=-1,
							title=colnames(model),cell=list(gtkCellRendererText()),text=seq_len(ncol(model))-1)
						sapply(seq_len(ncol(model)),function(i)
							view$getColumn(i-1)$setSortColumnId(i-1))
						view$setHeadersClickable(TRUE)
						if (is.null(gtkCheckVersion(2, 10, 0))) view$setGridLines("both")	
						rfAmtScrolledWindow<-gtkScrolledWindow()
						rfAmtScrolledWindow$setSizeRequest(600,800)
						rfAmtScrolledWindow$add(view)
						rfAmtTable$attach(rfAmtScrolledWindow,left.attach=1,2,top.attach=0,1,xoptions=c("shrink","fill"),yoptions="")						 
					}
					else if(nStation==1 & any(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(0,8)) &
						any(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(0,9)) &
						any(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(0,10)) &
						any(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(2,4)) &
						any(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(2,5)) &
						any(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(2,6))){
						model<-rGtkDataFrame(StatDf)
						model$setFrame(StatDf)
						column<-gtkTreeViewColumn()
						column$setTitle("Station Number")
						column$setSortColumnId(0)
						model$setSortColumnId (0,"ascending" )
						sorted_model<-gtkTreeModelSortNewWithModel(model)
						view<-gtkTreeView(sorted_model)
						mapply(view$insertColumnWithAttributes,position=-1,
							title=colnames(model),cell=list(gtkCellRendererText()),text=seq_len(ncol(model))-1)
						sapply(seq_len(ncol(model)),function(i)
							view$getColumn(i-1)$setSortColumnId(i-1))
						view$setHeadersClickable(TRUE)
						if (is.null(gtkCheckVersion(2, 10, 0))) view$setGridLines("both")	
						rfAmtScrolledWindow<-gtkScrolledWindow()
						rfAmtScrolledWindow$setSizeRequest(600,800)
						rfAmtScrolledWindow$add(view)
						rfAmtTable$attach(rfAmtScrolledWindow,left.attach=1,2,top.attach=0,1,xoptions=c("shrink","fill"),yoptions="")	
					}
					else {rfAmtPlotDeviceAdd()}	
				}
			}
			
		}
	}
}						
rfAmtOptionSel<-rfAmtOptionView$getSelection()
gSignalConnect(rfAmtOptionSel,"changed",function(rfAmtOptionSel,event,data){
	list<-readLines("option.dat")
	isuccess=as.numeric(list[2])
	if (isuccess==1) {rfAmtOptionFun()}
})	
#Add combo box for station select
rfAmtStnSelFrame<-gtkFrame("Select Station: ")
rfAmtTable$attach(rfAmtStnSelFrame,left.attach=0,1,top.attach=1,2,
	xoptions=c("shrink","fill"),yoptions="",ypadding=0)
rfAmtStnCombo <- gtkComboBoxNewText()
rfAmtStnSelFrame$add(rfAmtStnCombo)	
gSignalConnect(rfAmtStnCombo,"changed",f = function(button,...){
   	#message("",button$getActiveText(),"\n")
	list<-readLines("option.dat")
	isuccess=as.numeric(list[2])
	if (isuccess==1) {rfAmtOptionFun()}
})
#Add RadioButton for view options
rfAmtViewOptionFrame<-gtkFrame("View Options")
rfAmtTable$attach(rfAmtViewOptionFrame,left.attach=1,2,top.attach=1,2,
	xoptions=c("expand","fill"),yoptions="",ypadding=0)
rfAmtViewOptionLabels<-c("Grid","Plot")
rfAmtViewOptionRadioGp<-list() 
rfAmtViewOptionRadioGp [[rfAmtViewOptionLabels[1]]]<-gtkRadioButton(label=rfAmtViewOptionLabels[1])
for(label in rfAmtViewOptionLabels [-1])
rfAmtViewOptionRadioGp[[label]]<-gtkRadioButton(rfAmtViewOptionRadioGp,label=label)
rfAmtViewOptionHBox<-gtkHBox(homogeneous = NULL,spacing = NULL,show = TRUE)
rfAmtViewOptionFrame$add(rfAmtViewOptionHBox)
sapply(rfAmtViewOptionRadioGp,gtkBoxPackStart,object=rfAmtViewOptionHBox)
rfAmtViewOptionHBox[[2]]$setActive(TRUE) #set scatter plot as initial value
sapply(rfAmtViewOptionRadioGp,'[',"active")
sapply(rfAmtViewOptionRadioGp,gSignalConnect,"toggled",function(button,data){
	if(button['active']){
		#message("",button$getLabel(),"\n")
		list<-readLines("option.dat")
		isuccess=as.numeric(list[2])
		if (isuccess==1) {rfAmtOptionFun()}
	}
})	
rfAmtSaveViewButton<-gtkButtonNewWithLabel("Save View")
rfAmtTable$attach(rfAmtSaveViewButton,left.attach=0,1,top.attach=2,3,
	xoptions=c("shrink","fill"),yoptions="",ypadding=0)	
#Add plot device to rfAmtTable
rfAmtPlotDeviceAdd<-function(){				 				
	rfAmtPlotDevice<-gtkDrawingArea()
	rfAmtPlotDevice$setSizeRequest(600,800)
	asCairoDevice(rfAmtPlotDevice)
	rfAmtTable$attach(rfAmtPlotDevice,left.attach=1,2,top.attach=0,1,
		xoptions=c("expand","fill"),yoptions="",ypadding=0)
	Sys.sleep(.1)
}

#save rfAmt view
gSignalConnect(rfAmtSaveViewButton, "clicked", function(rfAmtSaveViewButton,event,data){
	#Read user-defined parameters
	parameters<-scan(file="data.dat",skip=2,nline=1,quiet = TRUE)
	nYr<-parameters[1]
	yrStart<-parameters[2]
	band<-parameters[3]
	nStation<-parameters[4]
	nSim<-parameters[5]
	nYrSim<-parameters[8]
	nYrStat<-max(parameters[8],parameters[1]) #multi_site_rain.f L4643
	amt<-parameters[10]	
	if (amt==1){							
		if(length(rfAmtOptionSel$getSelectedRows()$retval)==1){
			sapply(rfAmtViewOptionRadioGp,function(button,data){ 
				if(button['active']) {
					list<-readLines("option.dat")
					list<-sub(list[6],button$getLabel(),list)
					writeLines(list,"option.dat") 
				}
			}) 
			list<-readLines("option.dat")
			rfAmtViewOption<-list[6]
			rfStatSelStn<-rfAmtStnCombo$getActiveText()		 
			statFile<-"stat.out"
			list_data_fi=readLines("data.dat")
			inputRfFile<-list_data_fi[8]
			stnNumber<-read.table(inputRfFile,nrows=1)[2:(nStation+1)]	
			stnName<-read.table(inputRfFile,skip=1,nrow=1,quote="\"")[2:(nStation+1)]
			if (length(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices())==2 & length(rfStatSelStn)>0){
				if (rfAmtViewOption=="Plot"){
					if (nStation>1){
						statPlot<-savePlotFileAs()
						if (statPlot!=""){
							#Mean of annual rf amt plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,0))){
								rfAmtAnnualSeasonalMean<-matrix(scan(file=statFile,skip=(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								mainLength<-nchar("Mean of annual rainfall amount")
								annualStatPlotFun(rfAmtAnnualSeasonalMean,"Mean of annual rainfall amount",
									nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)
							}
							#SD of annual rf amt plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,1))){
								rfAmtAnnualSeasonalSD<-matrix(scan(file=statFile,skip=4*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								mainLength<-nchar("SD of annual rainfall amount")
								annualStatPlotFun(rfAmtAnnualSeasonalSD,"SD of annual rainfall amount",
									nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)
							}
							#5th percentile of rf amt plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,2))){
								MaxSpell5thRfAmt<-matrix(scan(file=statFile,skip=10*(nSim+2)+1,nlines=nSim+1),
									nrow=1+nSim,ncol=1+3*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								mainLength<-nchar("5th percentile of daily rainfall amount")
								maxSpelllength5thRfAmtPlotFun(MaxSpell5thRfAmt,4,
									"5th percentile of daily rainfall amount",nSim,
									nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)													
							}
							#Mean of annual rf amt per wet day plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,3))){
								rfAmtAnnualSeasonalMeanPWD<-matrix(scan(file=statFile,skip=2*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								mainLength<-nchar("Mean of annual rainfall amount per wet day")
								annualStatPlotFun(rfAmtAnnualSeasonalMeanPWD,"Mean of annual rainfall amount per wet day",
									nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)
							}
							#SD of annual rf amt per wet day plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,4))){
								rfAmtAnnualSeasonalSDPWD<-matrix(scan(file=statFile,skip=5*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								mainLenght<-nchar("SD of annual rainfall amount per wet day")
								annualStatPlotFun(rfAmtAnnualSeasonalSDPWD,"SD of annual rainfall amount per wet day",
									nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth)
							}
							#Average rf amt in a year plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,5))){
								#scanIndex<-2 for average rf amt in a year
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								mainLength<-nchar("Average rainfall in a year")
								rfStatInAYearPlotFun(2,0,2,"Average rainfall in a year",
									nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)								 				
							}
							#Maximum rf amt in a year plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,6))){
								#scanIndex<-0 for maximum rf amt in a year						 
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								mainLength<-nchar("Maximum rainfall amount in a year")
								rfStatInAYearPlotFun(0,0,2,"Maximum rainfall amount in a year",
									nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)					
							}
							#Total rf amt in wet spells of varying lengths plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,7))){
								totRfAmtInWS<-matrix(scan(file=statFile,skip=11*(nSim+2)+1*(nSim+3)+2,nlines=nSim+1,quiet = TRUE),
								nrow=1+nSim,ncol=1+4*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								totRfAmtInWSPlotSaveFun(totRfAmtInWS,"1-day","2-4 days","5-7 days","> 7 days",
									"Total rainfall wet spells of varying lengths",
									nSim,nStation,rfStatSelStn,stnNumber)						
							}
							#Daily crs-corrl of rf-wet days on annual basis
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,8))){
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								if (nStation>1) {
									annualCrsCorrlPlotFun(1,0,1,c("Daily cross-correlation of rainfall", "\nin wet days on annual basis"),
										nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)
								}
							}	
							#Daily crs-corrl of rf-all days on annual basis
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,9))){
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								if (nStation>1){
									annualCrsCorrlPlotFun(1,1,1,c("Daily cross-correlation of rainfall", "\nin all days on annual basis"),
										nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)	
								}
							}
							#Cross-corrl of annual rainfall
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,10))){
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								if (nStation>1){
									annualCrsCorrlPlotFun(1,3,1,"Cross-correlation of annual rainfall",
										nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)
								}
							}				
							#Mean of seasonal rf amt plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,0))){
								rfAmtAnnualSeasonalMean<-matrix(scan(file=statFile,skip=(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								seasonalStatPlotSaveFun(rfAmtAnnualSeasonalMean,"Mean of seasonal rainfall",
									nSim,nStation,rfStatSelStn,stnNumber)
							}	
							#SD of seasonal rf amt plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,1))){
								rfAmtAnnualSeasonalSD<-matrix(scan(file=statFile,skip=4*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								seasonalStatPlotSaveFun(rfAmtAnnualSeasonalSD,"SD of seasonal rainfall",
									nSim,nStation,rfStatSelStn,stnNumber)						 
							}
							#Mean of seasonal rf amt per wet day plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,2))){
								rfAmtAnnualSeasonalMeanPWD<-matrix(scan(file=statFile,skip=2*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								seasonalStatPlotSaveFun(rfAmtAnnualSeasonalMeanPWD,
									"Mean of seasonal rainfall per wet day",
									nSim,nStation,rfStatSelStn,stnNumber)	
							}
							#SD of seasonal rf amt per wet day plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,3))){
								rfAmtAnnualSeasonalSDPWD<-matrix(scan(file=statFile,skip=5*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								seasonalStatPlotSaveFun(rfAmtAnnualSeasonalSDPWD,
									"SD of seasonal rainfall per wet day",
									nSim,nStation,rfStatSelStn,stnNumber)
							}
							#Daily crs-corrl of rf-wet days on seasonal basis
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,4))){
								dev.new(width=6.25, height=6.25)
								fontsize<-0.8
								linewidth<-1
								if (nStation>1){
									seasonalCrsCorrlSavePlotFun(1,0,1,c("Daily cross-correlation of rainfall","\nin wet days on seasonal basis"),
										nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)		
								}
							}	
							#Daily crs-corrl of rf-all days on seasonal basis
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,5))){
								dev.new(width=6.25, height=6.25)
								fontsize<-0.8
								linewidth<-1
								if (nStation>1){
									seasonalCrsCorrlSavePlotFun(1,1,1,c("Daily cross-correlation of rainfall","\nin all days on seasonal basis"),
										nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)
								}
							}
							#Cross-corrl of seasonal rainfall
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,6))){
								dev.new(width=6.25, height=6.25)
								fontsize<-0.8
								linewidth<-1
								if (nStation>1){
									seasonalCrsCorrlSavePlotFun(1,3,1,"Cross-Correlation of Seasonal Rainfall",
										nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)
								}
							}				 
							#Mean of monthly rf amt plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,0))){
								#col=[2:13] for station 1
								rfAmtMonthlyMean<-matrix(scan(file=statFile,skip=7*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
								if (rfStatSelStn=="All stations") {dev.new(width=6.25, height=8.33)}
								else {dev.new(width=6.25, height=6.25)}		
								mainLength<-nchar("Mean of monthly rainfall amount")
								monthlyStatPlotSaveFun(rfAmtMonthlyMean,"Mean of monthly rainfall amount",
									nSim,nStation,rfStatSelStn,stnNumber,mainLength)
							}					 
							#SD of monthly rf amt plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,1))){
								#col=[2:13] for station 1
								rfAmtMonthlySD<-matrix(scan(file=statFile,skip=9*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
								if (rfStatSelStn=="All stations") {dev.new(width=6.25, height=8.33)}
								else {dev.new(width=6.25, height=6.25)}
								mainLength<-nchar("SD of monthly rainfall amount")
								monthlyStatPlotSaveFun(rfAmtMonthlySD,"SD of monthly rainfall amount",
									nSim,nStation,rfStatSelStn,stnNumber,mainLength)
							}
							savePlot(filename = statPlot,type = getExt(statPlot),device = dev.cur(),restoreConsole = TRUE)
							dev.off()
						}
					}
					else if(nStation==1 & any(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(0,8)) &
						any(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(0,9)) &
						any(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(0,10)) &
						any(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(2,4)) &
						any(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(2,5)) &
						any(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(2,6))){
						statPlot<-savePlotFileAs()
						if (statPlot!=""){
							#Mean of annual rf amt plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,0))){
								rfAmtAnnualSeasonalMean<-matrix(scan(file=statFile,skip=(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								mainLength<-nchar("Mean of annual rainfall amount")
								annualStatPlotFun(rfAmtAnnualSeasonalMean,"Mean of annual rainfall amount",
									nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)
							}
							#SD of annual rf amt plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,1))){
								rfAmtAnnualSeasonalSD<-matrix(scan(file=statFile,skip=4*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								mainLength<-nchar("SD of annual rainfall amount")
								annualStatPlotFun(rfAmtAnnualSeasonalSD,"SD of annual rainfall amount",
									nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)
							}
							#5th percentile of rf amt plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,2))){
								MaxSpell5thRfAmt<-matrix(scan(file=statFile,skip=10*(nSim+2)+1,nlines=nSim+1),
									nrow=1+nSim,ncol=1+3*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								mainLength<-nchar("5th percentile of daily rainfall amount")
								maxSpelllength5thRfAmtPlotFun(MaxSpell5thRfAmt,4,
									"5th percentile of daily rainfall amount",nSim,
									nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)													
							}
							#Mean of annual rf amt per wet day plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,3))){
								rfAmtAnnualSeasonalMeanPWD<-matrix(scan(file=statFile,skip=2*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								mainLength<-nchar("Mean of annual rainfall amount per wet day")
								annualStatPlotFun(rfAmtAnnualSeasonalMeanPWD,"Mean of annual rainfall amount per wet day",
									nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth,mainLength)
							}
							#SD of annual rf amt per wet day plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,4))){
								rfAmtAnnualSeasonalSDPWD<-matrix(scan(file=statFile,skip=5*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								mainLenght<-nchar("SD of annual rainfall amount per wet day")
								annualStatPlotFun(rfAmtAnnualSeasonalSDPWD,"SD of annual rainfall amount per wet day",
									nSim,nStation,rfStatSelStn,stnNumber,fontsize,linewidth)
							}
							#Average rf amt in a year plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,5))){
								#scanIndex<-2 for average rf amt in a year
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								mainLength<-nchar("Average rainfall in a year")
								rfStatInAYearPlotFun(2,0,2,"Average rainfall in a year",
									nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)								 				
							}
							#Maximum rf amt in a year plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,6))){
								#scanIndex<-0 for maximum rf amt in a year						 
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								mainLength<-nchar("Maximum rainfall amount in a year")
								rfStatInAYearPlotFun(0,0,2,"Maximum rainfall amount in a year",
									nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,fontsize,linewidth,mainLength)					
							}
							#Total rf amt in wet spells of varying lengths plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,7))){
								totRfAmtInWS<-matrix(scan(file=statFile,skip=11*(nSim+2)+1*(nSim+3)+2,nlines=nSim+1,quiet = TRUE),
								nrow=1+nSim,ncol=1+4*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								totRfAmtInWSPlotSaveFun(totRfAmtInWS,"1-day","2-4 days","5-7 days","> 7 days",
									"Total rainfall wet spells of varying lengths",
									nSim,nStation,rfStatSelStn,stnNumber)						
							}
							#Daily crs-corrl of rf-wet days on annual basis
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,8))){
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								if (nStation>1) {
									annualCrsCorrlPlotFun(1,0,1,c("Daily cross-correlation of rainfall", "\nin wet days on annual basis"),
										nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)
								}
							}	
							#Daily crs-corrl of rf-all days on annual basis
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,9))){
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								if (nStation>1){
									annualCrsCorrlPlotFun(1,1,1,c("Daily cross-correlation of rainfall", "\nin all days on annual basis"),
										nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)	
								}
							}
							#Cross-corrl of annual rainfall
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,10))){
								dev.new(width=6.25, height=6.25)
								fontsize<-1.5
								linewidth<-2
								if (nStation>1){
									annualCrsCorrlPlotFun(1,3,1,"Cross-correlation of annual rainfall",
										nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)
								}
							}				
							#Mean of seasonal rf amt plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,0))){
								rfAmtAnnualSeasonalMean<-matrix(scan(file=statFile,skip=(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								seasonalStatPlotSaveFun(rfAmtAnnualSeasonalMean,"Mean of seasonal rainfall",
									nSim,nStation,rfStatSelStn,stnNumber)
							}	
							#SD of seasonal rf amt plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,1))){
								rfAmtAnnualSeasonalSD<-matrix(scan(file=statFile,skip=4*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								seasonalStatPlotSaveFun(rfAmtAnnualSeasonalSD,"SD of seasonal rainfall",
									nSim,nStation,rfStatSelStn,stnNumber)						 
							}
							#Mean of seasonal rf amt per wet day plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,2))){
								rfAmtAnnualSeasonalMeanPWD<-matrix(scan(file=statFile,skip=2*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								seasonalStatPlotSaveFun(rfAmtAnnualSeasonalMeanPWD,
									"Mean of seasonal rainfall per wet day",
									nSim,nStation,rfStatSelStn,stnNumber)	
							}
							#SD of seasonal rf amt per wet day plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,3))){
								rfAmtAnnualSeasonalSDPWD<-matrix(scan(file=statFile,skip=5*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
								dev.new(width=6.25, height=6.25)
								seasonalStatPlotSaveFun(rfAmtAnnualSeasonalSDPWD,
									"SD of seasonal rainfall per wet day",
									nSim,nStation,rfStatSelStn,stnNumber)
							}
							#Daily crs-corrl of rf-wet days on seasonal basis
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,4))){
								dev.new(width=6.25, height=6.25)
								fontsize<-0.8
								linewidth<-1
								if (nStation>1){
									seasonalCrsCorrlSavePlotFun(1,0,1,c("Daily cross-correlation of rainfall","\nin wet days on seasonal basis"),
										nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)		
								}
							}	
							#Daily crs-corrl of rf-all days on seasonal basis
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,5))){
								dev.new(width=6.25, height=6.25)
								fontsize<-0.8
								linewidth<-1
								if (nStation>1){
									seasonalCrsCorrlSavePlotFun(1,1,1,c("Daily cross-correlation of rainfall","\nin all days on seasonal basis"),
										nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)
								}
							}
							#Cross-corrl of seasonal rainfall
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,6))){
								dev.new(width=6.25, height=6.25)
								fontsize<-0.8
								linewidth<-1
								if (nStation>1){
									seasonalCrsCorrlSavePlotFun(1,3,1,"Cross-Correlation of Seasonal Rainfall",
										nSim,nStation,statFile,nYrStat,stnNumber,fontsize,linewidth)
								}
							}				 
							#Mean of monthly rf amt plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,0))){
								#col=[2:13] for station 1
								rfAmtMonthlyMean<-matrix(scan(file=statFile,skip=7*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
								if (rfStatSelStn=="All stations") {dev.new(width=6.25, height=8.33)}
								else {dev.new(width=6.25, height=6.25)}		
								mainLength<-nchar("Mean of monthly rainfall amount")
								monthlyStatPlotSaveFun(rfAmtMonthlyMean,"Mean of monthly rainfall amount",
									nSim,nStation,rfStatSelStn,stnNumber,mainLength)
							}					 
							#SD of monthly rf amt plot
							if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,1))){
								#col=[2:13] for station 1
								rfAmtMonthlySD<-matrix(scan(file=statFile,skip=9*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
									nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
								if (rfStatSelStn=="All stations") {dev.new(width=6.25, height=8.33)}
								else {dev.new(width=6.25, height=6.25)}
								mainLength<-nchar("SD of monthly rainfall amount")
								monthlyStatPlotSaveFun(rfAmtMonthlySD,"SD of monthly rainfall amount",
									nSim,nStation,rfStatSelStn,stnNumber,mainLength)
							}
							savePlot(filename = statPlot,type = getExt(statPlot),device = dev.cur(),restoreConsole = TRUE)
							dev.off()
						}											
					}					
				}
				if (rfAmtViewOption=="Grid"){
					#Mean of annual rf amt df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,0))){
						rfAmtAnnualSeasonalMean<-matrix(scan(file=statFile,skip=(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
							nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						StatDf<-annualStatDfFun(rfAmtAnnualSeasonalMean,nSim,nStation,rfStatSelStn,stnNumber,stnName)			
					}					
					#SD of annual rf amt df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,1))){
						rfAmtAnnualSeasonalSD<-matrix(scan(file=statFile,skip=4*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
							nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						StatDf<-annualStatDfFun(rfAmtAnnualSeasonalSD,nSim,nStation,rfStatSelStn,stnNumber,stnName)								 
					}											 						
					#5th percentile of rf df 
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,2))){
						MaxSpell5thRfAmt<-matrix(scan(file=statFile,skip=10*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
							nrow=1+nSim,ncol=1+3*nStation,byrow=TRUE)
						StatDf<-maxSpelllength5thRfAmtDfFun(MaxSpell5thRfAmt,4,nSim,nStation,rfStatSelStn,stnNumber,stnName)													
					}						
					#Mean of annual rf amt per wet day df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,3))){
						rfAmtAnnualSeasonalMeanPWD<-matrix(scan(file=statFile,skip=2*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
							nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						StatDf<-annualStatDfFun(rfAmtAnnualSeasonalMeanPWD,nSim,nStation,rfStatSelStn,stnNumber,stnName)
					}					 
					#SD of annual rf amt per wet day df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,4))){
						rfAmtAnnualSeasonalSDPWD<-matrix(scan(file=statFile,skip=5*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
							nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						StatDf<-annualStatDfFun(rfAmtAnnualSeasonalSDPWD,nSim,nStation,rfStatSelStn,stnNumber,stnName)
					}
					#Average rf amt in a year df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,5))){
						#scanIndex<-2 for average rf amt in a year
						StatDf<-rfStatInAYearDfFun(2,0,2,nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,stnName)								 				
					}					 					 
					#Maximum rf amt in a year df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,6))){
						#scanIndex<-0 for maximum rf amt in a year						 
						StatDf<-rfStatInAYearDfFun(0,0,2,nSim,nStation,rfStatSelStn,statFile,nYrStat,stnNumber,stnName)					
					}					 
					#Total rf amt in wet spells of varying lengths df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,7))){
						totRfAmtInWS<-matrix(scan(file=statFile,skip=11*(nSim+2)+1*(nSim+3)+2,nlines=nSim+1,quiet = TRUE),
							nrow=1+nSim,ncol=1+4*nStation,byrow=TRUE)
						StatDf<-totRfAmtInWSDfFun(totRfAmtInWS,"1-day","2-4 days","5-7 days","> 7 days",
							"Wet Spells lengths",nSim,nStation,rfStatSelStn,stnNumber,stnName)						
					}																	 
					#Daily crs-corrl of rf-wet days on annual basis
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,8))){
						if (nStation>1){
							StatDf<-annualCrsCorrlDfFun(1,0,1,nSim,nStation,statFile,nYrStat,stnNumber,stnName)
						}												
					}	
					#Daily crs-corrl of rf-all days on annual basis
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,9))){
						if (nStation>1){
							StatDf<-annualCrsCorrlDfFun(1,1,1,nSim,nStation,statFile,nYrStat,stnNumber,stnName)	
						}					
					}
					#Cross-corrl of annual rainfall
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(0,10))){
						if (nStation>1){
							StatDf<-annualCrsCorrlDfFun(1,3,1,nSim,nStation,statFile,nYrStat,stnNumber,stnName)	
						}						
					}								 
					#Mean of seasonal rf amt df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,0))){
						rfAmtAnnualSeasonalMean<-matrix(scan(file=statFile,skip=(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
							nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						StatDf<-seasonalStatDfFun(rfAmtAnnualSeasonalMean,nSim,nStation,rfStatSelStn,stnNumber,stnName)
					}					 					 
					#SD of seasonal rf amt df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,1))){
						rfAmtAnnualSeasonalSD<-matrix(scan(file=statFile,skip=4*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
							nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						StatDf<-seasonalStatDfFun(rfAmtAnnualSeasonalSD,nSim,nStation,rfStatSelStn,stnNumber,stnName)						 
					}						
					#Mean of seasonal rf amt per wet day df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,2))){
						rfAmtAnnualSeasonalMeanPWD<-matrix(scan(file=statFile,skip=2*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
							nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						StatDf<-seasonalStatDfFun(rfAmtAnnualSeasonalMeanPWD,nSim,nStation,rfStatSelStn,stnNumber,stnName)	
					}					 
					#SD of seasonal rf amt per wet day df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,3))){
						rfAmtAnnualSeasonalSDPWD<-matrix(scan(file=statFile,skip=5*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
							nrow=1+nSim,ncol=1+5*nStation,byrow=TRUE)
						StatDf<-seasonalStatDfFun(rfAmtAnnualSeasonalSDPWD,nSim,nStation,rfStatSelStn,stnNumber,stnName)
					}
					#Daily crs-corrl of rf-wet days on seasonal basis
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,4))){
						if (nStation>1){
							StatDf<-seasonalCrsCorrlDfFun(1,0,1,nSim,nStation,statFile,nYrStat,stnNumber,stnName)
						}					
					}	
					#Daily crs-corrl of rf-all days on seasonal basis
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,5))){
						if (nStation>1){
							StatDf<-seasonalCrsCorrlDfFun(1,1,1,nSim,nStation,statFile,nYrStat,stnNumber,stnName)
						}					
					}
					#Cross-corrl of seasonal rainfall
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(2,6))){
						if (nStation>1){
							StatDf<-seasonalCrsCorrlDfFun(1,3,1,nSim,nStation,statFile,nYrStat,stnNumber,stnName)	
						}
					}				 			 			 
					#Mean of monthly rf amt df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,0))){
						#col=[2:13] for station 1
						rfAmtMonthlyMean<-matrix(scan(file=statFile,skip=7*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
							nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
						StatDf<-monthlyStatDfFun(rfAmtMonthlyMean,nSim,nStation,rfStatSelStn,stnNumber,stnName)
					}											 
					#SD of monthly rf amt df
					if (all(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()==c(1,1))){
						#col=[2:13] for station 1
						rfAmtMonthlySD<-matrix(scan(file=statFile,skip=9*(nSim+2)+1,nlines=nSim+1,quiet = TRUE),
							nrow=1+nSim,ncol=1+12*nStation,byrow=TRUE)
						StatDf<-monthlyStatDfFun(rfAmtMonthlySD,nSim,nStation,rfStatSelStn,stnNumber,stnName)
					}
					if (nStation>1){
						gridFile<-saveGridFileAs()
						if (gridFile!=""){
							write.table(StatDf, file = gridFile, append = FALSE, quote = TRUE,sep = " ",dec = ".",
							row.names = FALSE,col.names = TRUE, qmethod = "double",fileEncoding = "")
						}
					}
					else if(nStation==1 & any(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(0,8)) &
						any(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(0,9)) &
						any(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(0,10)) &
						any(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(2,4)) &
						any(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(2,5)) &
						any(rfAmtOptionSel$getSelectedRows()$retval[[1]]$getIndices()!=c(2,6))){
						gridFile<-saveGridFileAs()
						if (gridFile!=""){
							write.table(StatDf, file = gridFile, append = FALSE, quote = TRUE,sep = " ",dec = ".",
							row.names = FALSE,col.names = TRUE, qmethod = "double",fileEncoding = "")	
						}
					}
				}
			}
		}
	}
})
			