coreread() {
  VOLTAGE=0;
  while read UVOLT UNIT; do
    VOLTAGE=$((VOLTAGE + 1));
    if [ "$VOLTAGE" == $1 ]; then
      echo $UVOLT;
      return;
    fi;
  done < $P;
}

corewrite() {
  VOLTARR="";
  VOLTAGE=0;
  while read UVOLT UNIT; do
    VOLTAGE=$((VOLTAGE + 1));
    if [ "$VOLTAGE" == $1 ]; then
      VOLTARR="$VOLTARR $2";
    else
      VOLTARR="$VOLTARR $UVOLT";
    fi;
  done < $P;

  echo $VOLTARR > $P;
}

cpuread() {
  while read FREQ UVOLT UNIT; do
    if [ $FREQ == $1 ]; then
      echo $UVOLT;
      return;
    fi;
  done < $P;
}

cpuwrite() {
  VOLTARR="";
  while read FREQ UVOLT UNIT; do
    if [ $FREQ == $1 ]; then
      VOLTARR="$VOLTARR $2";
    else
      VOLTARR="$VOLTARR $UVOLT";
    fi;
  done < $P;

  echo $VOLTARR > $P;
}

case $1 in
  cpuvolt)
    P=/sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table;
    if [[ ! -z $3 ]]; then
      cpuwrite $2 $3;
    fi;
    echo `cpuread $2`;
  ;;

  corevolt)
    P=/sys/devices/virtual/misc/customvoltage/core_voltages;
    if [[ ! -z $3 ]]; then
      corewrite $2 $3;
    fi;
    echo `coreread $2`;
  ;;

  ivavolt)
    P=/sys/devices/virtual/misc/customvoltage/iva_voltages;
    if [[ ! -z $3 ]]; then
      corewrite $2 $3;
    fi;
    echo `coreread $2`;
  ;;

  regulatorvolt)
    P=/sys/devices/virtual/misc/customvoltage/regulator_voltages;
    if [[ ! -z $3 ]]; then
      cpuwrite $2 $3;
    fi;
    echo `cpuread $2`;
  ;;
esac;

