#' updateMusoMapping
#'
#' This function update the the muso outputcode-variable matrix
#' @author Roland Hollos
#' @param output_map_init The outputcode-variable bindings is described in output_map_init.c file, via this parameter, you can give it the the function
#' @return The outputcode-variable matrix, and also change the global variable
#' @export
#' @usage updateMusoMapping(output_map_init="output_map_init.c")

updateMusoMapping<-function(output_map_init="output_map_init.c"){
    
    outputRaw<-grep("\\[",readLines(output_map_init,-1),value=TRUE)

    codes <- as.vector(lapply(outputRaw, function (x)  as.numeric(unlist(strsplit(unlist(strsplit(x,"\\["))[2],"\\]"))[1])))
    names <- unlist(lapply(outputRaw, function (x) unlist(strsplit(unlist(strsplit(x,"\\&"))[2],";"))[1]))
    mMapping <-cbind(codes,names)
    save(mMapping, file="mMap.RData")
    return(mMapping)
}

#' musoMapping
#'
#' musoMapping can give us the name of a muso outputcode
#' @author Roland Hollos
#' @param code the MuSo outputcode
#' @param mapData updateMusomapping generated matrix
#' @return The name of the MuSo outputcode
#' @export
#' @usage musoMapping(code, mapData=NULL)


musoMapping <- function(code, mapData=NULL){
    if(is.null(mapData)){
        return(unlist(mMapping[which(mMapping[,1]==code),2])) #mMapping is package-scoped system variable generated by udateMusoMapping
    } else {
        return(unlist(mapData[which(mapData[,1]==code),2]))
    }
}


#' musoMappingFind
#'
#' musoMapping can give us the name of a muso outputcode
#' @author Roland Hollos
#' @param variable If null return the whole mapping, else search a variable code
#' @return The code of th specific name
#' @export
#' @usage musoMapping(code, mapData=NULL)


musoMappingFind <- function(variable=NULL){
    if(is.null(variable)){
        return(mMapping)
    } else {
                            mMapping[grep(variable,mMapping[,2]),]
                    }
}

