require(pacman)
p_load(stringr)

numextract <- function(string){ 
  str_extract(string, "\\-*\\d+\\.*\\d*")
}

which_vars <- function(xv) {
  if (grepl('x', xv)) {
    tmpVars = paste0('x', 1:10)
    if (xv %in% tmpVars) {
      return(xv)
    } else {
      return('x10')
    }
  } else if (grepl('NM', xv)) {
    return(xv)
  } else if (grepl('N', xv)) {
    return(xv)
  } else if (grepl('M', xv)) {
    num = numextract(xv)
    n = nchar(num)
    xt = paste0('M', substr(num, 1, n - 1))
    return(xt)
  } else {
    return(xv)
  }
}

import_xvars <- function(imp) {
  impT = rep(0, length(xvars))
  names(impT) = xvars
  vars = row.names(imp)
  if (length(vars) == 0) return(impT)
  
  for (i in 1:length(vars)) {
    v = vars[i]
    im = ifelse(is.na(imp[i,]), 0, imp[i,])
    
    if (grepl(':', v)) {
      v1 = which_vars(strsplit(v, ":")[[1]][1])
      v2 = which_vars(strsplit(v, ":")[[1]][2])
      impT[v1] = impT[v1] + im / 2
      impT[v2] = impT[v2] + im / 2
    } else {
      xv = which_vars(v)
      impT[xv] = impT[xv] + im
    }
  }
  impT['x10'] = impT['x10'] / 9
  for (xv in paste0('M', 1:10)) {
    impT[xv] = impT[xv] / 9
  }
  return(impT)
}


imp_measure <- function(imp_score) {
  return(rank(-imp_score))
}

imp_scale <- function(imp_score) {
  imp_score[is.na(imp_score)] = 0
  maxScore = max(imp_score)
  minScore = min(imp_score)
  if (minScore < 0) {
    res = ((imp_score - minScore) / (maxScore - minScore) * 100)
  } else {
    res = imp_score / maxScore * 100
  }
  res[is.na(res)] = 0
  return (res)
}
