#' musoMonte
#'
#' This function does monteCarlo on BiomeBGC-MuSo. It samples specified modell variables in given rangge from conditional multivariate uniform distribution, and runs the modell for each run.
#' @author Roland Hollos
#' @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 debugging If you set this parameter, you can save every logfile, and RBBGCMuso will select those which contains errors.
#' @param keepEpc if you set keepEpc also true, it will save every selected epc file, and put the wrong ones in the WRONGEPC directory.
#' @export

musoMonte <- function(settings=NULL,
                     parameters=NULL,
                     inputDir = "./",
                     outLoc = "./calib",
                     iterations = 10,
                     preTag = "mont-",
                     outputType = "moreCsv",
                     fun=mean,
                     varIndex = 1,
                     outVars = NULL,
                     silent = TRUE,
                     skipSpinup = TRUE,
                     debugging = FALSE,
                     keepEpc = FALSE,
                     constrains = NULL,
                     ...){


    readValuesFromEpc  <- function(epc, linums){
        epcFile <- readLines(epc)
        rows <- numeric(2)
        values <- sapply(linums, function(x){
            rows[1] <- as.integer(x)
            rows[2] <- as.integer(round(100*x)) %% 10 + 1 
            epcFile <- readLines(epc)
            selRow <- unlist(strsplit(epcFile[rows[1]], split= "[\t ]"))
            selRow <- selRow[selRow!=""]
            return(as.numeric(selRow[rows[2]]))
            
        })
        
        return(values)
    } 
    
    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")
                                     })
        }}
    
    outLocPlain <- basename(outLoc)
    currDir <- getwd()

    if(!dir.exists(outLoc)){
        dir.create(outLoc)
        warning(paste(outLoc," is not exists, so it was created"))
    }

    outLoc <- normalizePath(outLoc)

    if(is.null(settings)){
        settings <- setupMuso()
    }
    
    

    if(is.null(outVars)){
        numVars <- length(settings$outputVars[[1]])
        outVarNames <- settings$outputVars[[1]]
    } else {
        numVars <- length(outVars)
        outVarNames <- sapply(outVars, musoMapping)
    }
    
    parameterNames <- parameters[,1]
    # settings$calibrationPar <- A[,1] #:LATER:
    pretag <- file.path(outLoc,preTag)
    npar <- length(settings$calibrationPar)
    
    ##reading the original epc file at the specified
    ## row numbers
    if(iterations < 3000){
        randVals <- musoRand(parameters = parameters,constrains = constrains, iterations = 3000)
        randVals[[2]]<- randVals[[2]][sample(1:3000,iterations),]
    } else {
        randVals <- musoRand(parameters = parameters,constrains = constrains, iterations = iterations)
    }
    
    origEpc <- readValuesFromEpc(settings$epc[2],parameters[,2])
    
    ## Prepare the preservedEpc matrix for the faster
    ##  run.

    pretag <- file.path(outLoc,preTag)
    
    ## Creating function for generating separate
    ## csv files for each run

    progBar <- txtProgressBar(1,iterations,style=3)

    
    moreCsv <- function(){
        randValues <- randVals[[2]]
        settings$calibrationPar <- randVals[[1]]
        ## randValues <- randValues[,randVals[[1]] %in% parameters[,2]][,rank(parameters[,2])]
        modellOut <- matrix(ncol = numVars, nrow = iterations + 1)

        origModellOut <- calibMuso(silent=TRUE)
        write.csv(x=origModellOut, file=paste0(pretag,1,".csv"))

        if(!is.list(fun)){
            funct <- rep(list(fun), numVars)
        }
            
        tmp2 <- numeric(numVars)

        for(j in 1:numVars){
            tmp2[j]<-funct[[j]](origModellOut[,j])
        }
        modellOut[1,]<- tmp2
        
        for(i in 2:(iterations+1)){
            tmp <- calibMuso(settings = settings,
                             parameters = randValues[(i-1),],
                             silent= TRUE,
                             skipSpinup = skipSpinup,
                             keepEpc = keepEpc,
                             debugging = debugging,
                             outVars = outVars)
            

            for(j in 1:numVars){
                tmp2[j]<-funct[[j]](tmp[,j])
            }
            
            modellOut[i,]<- tmp2
            write.csv(x=tmp, file=paste0(pretag,(i+1),".csv"))
            setTxtProgressBar(progBar,i)
        }

        paramLines <- parameters[,2]
        paramLines <- order(paramLines)
        randInd <- randVals[[1]][(randVals[[1]] %in% parameters[,2])]
        randInd <- order(randInd)
        
       
        epcStrip <- rbind(origEpc[order(parameters[,2])],
                          randValues[,randVals[[1]] %in% parameters[,2]][,randInd])
        
        
            preservedEpc <- cbind(epcStrip,
                                  modellOut)
        colnames(preservedEpc) <- c(parameterNames[paramLines], sapply(outVarNames, function (x) paste0("mod.", x)))
        return(preservedEpc)
    }
    
    ## Creating function for generating one
    ## csv files for each run
    
    oneCsv <- function () {
        stop("This function is not implemented yet")
        ## numDays <- settings$numdata[1]
        ## if(!onDisk){
        ##     for(i in 1:iterations){
                
        ##         parVar <- apply(parameters,1,function (x) {
        ##             runif(1, as.numeric(x[3]), as.numeric(x[4]))})
                
        ##         preservedEpc[(i+1),] <- parVar
        ##         exportName <- paste0(preTag,".csv")
        ##         write.csv(parvar,"preservedEpc.csv",append=TRUE)
        ##         calibMuso(settings,debugging = "stamplog",
        ##                   parameters = parVar,keepEpc = TRUE) %>%
        ##             {mutate(.,iD = i)} %>%
        ##             {write.csv(.,file=exportName,append=TRUE)}
        ##     }
            
        ##     return(preservedEpc)
        ## } else {
            
        ## }
    }
    
    netCDF <- function () {
        stop("This function is not inplemented yet")
    }
    
    ## Call one function according to the outputType
    switch(outputType,
           "oneCsv" = (a <- oneCsv()),
           "moreCsv" = (a <- moreCsv()),
           "netCDF" = (a <- netCDF()))
    write.csv(a,"preservedEpc.csv")
   
    setwd(currDir)
    return(a)
}
