#' ADAMONT QQ Corr computes quantile-quantile correction of seasonal or decadal forecast data
#'
#'@author Paola Marson, \email{paola.marson@meteo.fr} for PROSNOW version
#'@author Lauriane Batté, \email{lauriane.batte@meteo.fr} for CSTools adaptation
#'
#'@param exp dimensions c(dataset,member,sdate,ftime,lat,lon)
#'@param wt dimensions c(dataset,member,sdate,ftime)
#'@param qexp dimensions c(Nwt, Nq+2, nlat, nlon)
#'@param qobs dimensions c(Nwt, Nq+2, nlat_o, nlon_o)
#'@param NN list (output from Adamont_NearestNeighbors) maps (nlat, nlon) onto (nlat_o, nlon_o)
#'
#'@import qmap

QQ_Slope <- function(qexp, qobs) {

	Nwt <- dim(qexp)[1]
	Nq <- dim(qexp)[2] - 2
	slope1 <- (qobs[,2]-qobs[,1])/(qexp[,2]-qexp[,1])
	slope2 <- (qobs[,Nq+2]-qobs[,Nq+1])/(qexp[,Nq+2]-qexp[,Nq+1]) # CHANGE TO ONES[NWT, NQ+2]

	return(list(s1=slope1,s2=slope2))
}

QQ_Corr <- function(exp, wt, qexp, qobs, NN) {

	# Data needs to be organized for use in qmap package
	# Aim of correction is to have qexp data on the qobs grid, bias adjusted using QQ method

	dim_exp <- dim(exp)
	dim_qobs <- dim(qobs) # CHECKS TO BE DONE: Nwt, Nq should be consistent between exp and obs
	nlat_o <- dim_qobs[3]
	nlon_o <- dim_qobs[4]
	Nwt <- dim_qobs[1]
	Nq <- dim_qobs[2]-2
	exp_corr <- array(dim=c(dim_exp[1:4],nlat_o,nlon_o))
	for (ilat in 1:nlat_o){
		for (ilon in 1:nlon_o){
			for (reg in 1:Nwt){
			    modq <- as.matrix(qexp[reg,,NN$imin_lat[ilat],NN$imin_lon[ilon]],nrow=Nq+2)
			    fitq <- as.matrix(qobs[reg,,ilat,ilon],nrow=Nq+2)
			    qq_slope <- QQ_Slope(qexp[reg,,NN$imin_lat[ilat],NN$imin_lon[ilon]],qobs[reg,,ilat,ilon])
			    fobjj<-list(par=list(modq=modq,
						 fitq=fitq,
						 slope=as.matrix(c(qq_slope$s1,qq_slope$s2),nrow=2) )
			               )
			    corr_qmap <- doQmapRQUANT(exp[which(wt==reg),NN$imin_lat[ilat],NN$imin_lon[ilon]],fobjj,type="linear2")
			    exp_corr[which(wt==reg),ilat,ilon] <- corr_qmap
			}
		}
	}

	return(exp_corr)
}

