#' musoSensi
#'
#' This function does regression based sensitivity analysis based on the output of musoMonte. 
#' @param settings A list of montecarlos environmental variables. It is generated by the setupMuso() function. In default the settings parameter is generated automatically. 
#' @param parameters This is a dataframe (heterogen data-matrix), which first column is the name of the parameters, the second is a numeric vector of the rownumbers of the given variable in the epc-fie, the last two column consist the endpont of the parameter-ranges, where the parameters will be randomized.
#' @param calibrationPar You may want to change some parameters in your epc file, before you run the modell. You have to select the appropirate modell parameters. You can refence to these with the number of the line in the epc file where the variables are. It indexes from one. You should use a vector for this, like: c(1,5,8)
#' @param inputDir The location of the input directory, this directory must content a viable pack of all inputfiles and the executable file. 
#' @param iterations number of the monteCarlo run.
#' @param preTag It will be the name of the output files. For example preTag-1.csv, pretag-2csv...
#' @param outputType This parameter can be "oneCsv", "moreCsv", and "netCDF". If "oneCsv" is choosen the function create 1 big csv file for all of the runs, if "moreCsv" is choosen, every modell output goes to separate files, if netCDF is selected the outputs will be put in a netCDF file. The default value of the outputTypes is "moreCsv". netCDF is not implemented yet. 
#' @param fun If you select a variable from the possible outputs (with specify the varIndex parameter), you have to provide a function which maps to a subset of real numbers. The most frequent possibilities are: mean, min, max, var, but you can define any function for your need.
#' @param varIndex This parameter specify which parameter of the output will be used. You can extract this information from the ini-files. At the output parameter specifications, the parameters order will determine this number. For example, if you have set these output parameters: 412, 874, 926, 888, and you want to use 926, you should address varIndex with 3.
#' @param skipSpinup With this parameter, you can turn of the spinup phase after the first spinup. I will decrease the time significantly.
#' @importFrom ggplot2 geom_bar ggplot aes theme element_text xlab ylab ggtitle ggsave scale_y_continuous
#' @importFrom scales percent
#' @export

musoSensi <- function(monteCarloFile = NULL,
                     parameters = NULL,
                     settings = NULL,
                     inputDir = "./",
                     outLoc = "./calib",
                     outVars = NULL,
                     iterations = 30,
                     preTag = "mont-",
                     outputType = "moreCsv",
                     fun = mean,
                     varIndex = 1,
                     outputFile = "sensitivity.csv",
                     plotName = "sensitivity.png",
                     plotTitle = "Sensitivity",
                     skipSpinup = TRUE,
                     skipZero = TRUE,
                     postProcString=NULL,
                     modifyOut=TRUE,
                     dpi=300){

    if(is.null(parameters)){
        parameters <- tryCatch(read.csv("parameters.csv",stringsAsFactor=FALSE), error = function (e) {
            stop("You need to specify a path for the parameters.csv, or a matrix.")
        })
    } else {
        if((!is.list(parameters)) & (!is.matrix(parameters))){
             parameters <- tryCatch(read.csv(parameters,stringsAsFactor=FALSE), error = function (e){
                                         stop("Cannot find neither parameters file neither the parameters matrix")
                                     })
        }}
    parameters[,1] <- gsub("([\\s]|\\-epc)","",parameters[,1],perl=TRUE)
    doSensi <- function(M){
        # browser()
        npar <- ncol(M)-1
        M <- M[which(!is.na(M[,ncol(M)])),]
        M <- M[-1,]
        y <- M[,(npar+1)]
        colnames(M) <- gsub("\\.epc","-epc",colnames(M))
        M <- M[,colnames(M) %in% parameters[,1]]
        npar <- ncol(M)
        M <- apply(M[,1:npar],2,function(x){x-mean(x)})
        varNames<- colnames(M)[1:npar]
        w <- lm(y~M)$coefficients[-1]
        Sv <- apply(M,2,var)
        overalVar <- sum(Sv*w^2,na.rm = TRUE)
        S=numeric(npar)
        
        for(i in 1:npar){
            S[i] <- ((w[i]^2*Sv[i])/(overalVar))*100
        }
        
        S <- round(S,digits=2)
        names(S)<-varNames
        write.csv(file = outputFile, x = S)

        sensiPlot <- ggplot(data.frame(name=varNames,y=S/100),aes(x=name,y=y))+
            geom_bar(stat = 'identity')+
            theme(axis.text.x = element_text(angle = 45, hjust = 1))+
            xlab(NULL)+
            ylab(NULL)+
            ggtitle("Sensitivity")+
            scale_y_continuous(labels = scales::percent,limits=c(0,1))
        print(sensiPlot)
        ggsave(plotName,dpi=dpi)
        return(S)
    }

    

    if(is.null(monteCarloFile)){
        M <- musoMonte(parameters = parameters,
                      settings = settings,
                      inputDir = inputDir,
                      outLoc = outLoc,
                      iterations = iterations,
                      preTag = preTag,
                      outputType = outputType,
                      outVars = outVars,
                      fun = fun,
                      varIndex = varIndex,
                      skipSpinup = skipSpinup,
                      skipZero=skipZero,
                      postProcString=postProcString,
                      modifyOut=modifyOut
                      )
        M <- cbind(seq_along(M[,1]),M)
        yInd <-  grep("mod.", colnames(M))[varIndex]
        parNames <- grep("mod.",colnames(M), invert=TRUE, value = TRUE)
        M <- M[,c(grep("mod.", colnames(M),invert=TRUE),yInd)]
        
        return(doSensi(M))
        
    } else {
        M <- read.csv(monteCarloFile)
        yInd <-  grep("mod.", colnames(M))[varIndex]
        parNames <- grep("mod.",colnames(M), invert=TRUE, value = TRUE)
        M <- M[,c(grep("mod.", colnames(M),invert=TRUE),yInd)]
        # browser()
        return(doSensi(M))        
    }
}



