#!/system/bin/sh
# L Speed tweak
# Codename: lspeed
version="v2.5.1-beta5"
build_date=16-Nov-2020
# Developer : Paget96
# Paypal : https://paypal.me/Paget96

LSPEED_DATA_DIR="$1"

BUSYBOX=$LSPEED_DATA_DIR/binary/busybox
LOG=$LSPEED_DATA_DIR/log/mainLog
SETUP_DIR=$LSPEED_DATA_DIR/setup

# Setup files
DISABLE_DEBUGGING="$SETUP_DIR/disable_debugging"
IO_STATS="$SETUP_DIR/io_stats"
CPU_OPTIMIZER="$SETUP_DIR/cpu_optimizer"
GPU_OPTIMIZER="$SETUP_DIR/gpu_optimizer"
OPTIMIZE_BUFFERS="$SETUP_DIR/optimize_buffers"
RENDER_OPENGLES_USING_GPU="$SETUP_DIR/render_opengles_using_gpu"
USE_OPENGL_SKIA="$SETUP_DIR/use_opengl_skia"
FORCE_GPU_RENDERING="$SETUP_DIR/force_gpu_rendering"
FORCE_4XMSAA="$SETUP_DIR/force_4xmsaa"
NET_BUFFERS="$SETUP_DIR/net_buffers"
RIL_TWEAKS="$SETUP_DIR/ril_tweaks"
DISABLE_MULTITASKING_LIMITATIONS="$SETUP_DIR/disable_multitasking_limitations"
LOW_RAM_FLAG="$SETUP_DIR/low_ram_flag"
OOM_KILLER="$SETUP_DIR/oom_killer"
RAM_MANAGER="$SETUP_DIR/ram_manager"
VIRTUAL_MEMORY_TWEAKS="$SETUP_DIR/virtual_memory_tweaks"
HEAP_OPTIMIZATION="$SETUP_DIR/heap_optimization"

# cpu_detect output files
CPU_DETECT_DATA_DIR="$SETUP_DIR/cpu_detect"
CPU_CORE_COUNT="$CPU_DETECT_DATA_DIR/cpu_core_count"
REAL_CPU_CORE_COUNT="$CPU_DETECT_DATA_DIR/real_cpu_core_count"
MIN_MAX_FREQ="$CPU_DETECT_DATA_DIR/min_max_freq"
MIN_FREQ_LIST="$CPU_DETECT_DATA_DIR/min_freq_list"
MAX_FREQ_LIST="$CPU_DETECT_DATA_DIR/max_freq_list"
LOGICAL_CORE="$CPU_DETECT_DATA_DIR/logical_core"
AFFECTED_CPU="$CPU_DETECT_DATA_DIR/affected_cpu"
UNIQUE_FREQ="$CPU_DETECT_DATA_DIR/unique_freq"
CORE_GETTER="$CPU_DETECT_DATA_DIR/core_getter"
PRIME_CORES_COUNT="$CPU_DETECT_DATA_DIR/prime_cores_count"
BIG_CORES_COUNT="$CPU_DETECT_DATA_DIR/big_cores_count"
LITTLE_CORES_COUNT="$CPU_DETECT_DATA_DIR/little_cores_count"

sendToLog() {
  timeZone=$(getprop persist.sys.timezone)
  printDate=$(TZ="$timeZone" $BUSYBOX date +"%H:%M:%S:%3N %d-%m-%Y")

  echo "[$printDate] $1" >>"$LOG"
}

write() {
  #chmod 0644 "$1"
  echo "$2" >"$1"
}

lockFile() {
  chmod 0644 "$1"
  echo "$2" >"$1"
  chmod 0444 "$1"
}

memTotal=$($BUSYBOX free -m | $BUSYBOX awk '/^Mem:/{print $2}')
# Prevent issues when $memTotal return weird output (including non-integer values, empty strings...),
# in this case device acts like a 4GB RAM device
case $memTotal in
'' | *[!0-9]*) memTotal=4096 ;;
*) memTotal=$memTotal ;;
esac

abi=$($BUSYBOX grep /system/build.prop ro.product.cpu.abi | $BUSYBOX head -n1 | $BUSYBOX cut -d= -f2)
case $abi in
arm* | x86*) ;;
*) abi=$(getprop ro.product.cpu.abi) ;;
esac
case $abi in
arm* | x86*) ;;
*) abi=$($BUSYBOX grep /system/default.prop ro.product.cpu.abi | $BUSYBOX head -n1 | $BUSYBOX cut -d= -f2) ;;
esac
case $abi in
arm64*) arch=arm64 ;;
arm*) arch=arm ;;
x86_64*) arch=x86_64 ;;
x86*) arch=x86 ;;
*) arch="Unknown arch: $abi" ;;
esac

real_cpu_cores=$($BUSYBOX ls /sys/devices/system/cpu | $BUSYBOX grep -c ^cpu[0-9])
cpu_cores=$((real_cpu_cores - 1))
brand=$(getprop ro.product.brand) 2>/dev/null
model=$(getprop ro.product.model) 2>/dev/null
rom=$(getprop ro.build.display.id) 2>/dev/null
androidRelease=$(getprop ro.build.version.release) 2>/dev/null
api=$(getprop ro.build.version.sdk) 2>/dev/null
kernel=$(uname -r) 2>/dev/null
root=$(magisk -c) 2>/dev/null
divider="==============================================="

getScheduler() {
  echo "$($BUSYBOX cut -d [ -f2 "$1"/queue/scheduler | $BUSYBOX cut -d] -f1)"
}

loggingHeader() {
  sendToLog "Starting with logging..."
  sendToLog $divider
  sendToLog "Version: $version ($build_date)"
  sendToLog $divider
  sendToLog "Getting device info"
  sendToLog "Brand: $brand"
  sendToLog "Model: $model"
  sendToLog "Arch: $arch"
  sendToLog "ROM: $rom (Android: $androidRelease|API: $api)"
  sendToLog "Kernel: $kernel"
  sendToLog "Root: $root"
  sendToLog "RAM: $((memTotal))mb"
  sendToLog $divider
}

#
# CPU Detector
#
#######
# Method returns the numbers of CPU cores
#######
getCPUcoreCount() {
  rm -rf "$CPU_CORE_COUNT"
  rm -rf $REAL_CPU_CORE_COUNT

  real_cpu_cores=$($BUSYBOX ls /sys/devices/system/cpu | $BUSYBOX grep -c ^cpu[0-9])
  cpu_cores=$((real_cpu_cores - 1))

  echo "$cpu_cores" >$CPU_CORE_COUNT
  echo "$real_cpu_cores" >$REAL_CPU_CORE_COUNT

  sleep 0.5

  unset real_cpu_cores
  unset cpu_cores
}

#######
# Method returns min and max frequencies as list
#######
getMinAndMaxFreq() {
  rm -rf $MIN_MAX_FREQ

  core_count=$($BUSYBOX cat $CPU_CORE_COUNT)
  core=0
  while [ $core -le "$core_count" ]; do

    scalingAvailableFrequencies=/sys/devices/system/cpu/cpu$core/cpufreq/scaling_available_frequencies

    if [ -e $scalingAvailableFrequencies ]; then
      minFreq=$($BUSYBOX cat $scalingAvailableFrequencies | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $1}')
      maxFreq=$($BUSYBOX cat $scalingAvailableFrequencies | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $NF}')

      if [ "$minFreq" -lt "$maxFreq" ]; then
        echo "$minFreq " >>$MIN_MAX_FREQ
        echo "$maxFreq " >>$MIN_MAX_FREQ
      elif [ "$minFreq" -gt "$maxFreq" ]; then
        echo "$maxFreq " >>$MIN_MAX_FREQ
        echo "$minFreq " >>$MIN_MAX_FREQ
      fi
    fi

    core=$((core + 1))
  done

  unset core
  unset scalingAvailableFrequencies
  unset minFreq
  unset maxFreq

  # This is for devices with mp-cpufreq dir
  if [ ! -e /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies ]; then
    rm -rf $MIN_MAX_FREQ

    cluster0FreqTable=/sys/devices/system/cpu/cpufreq/mp-cpufreq/cluster0_freq_table
    cluster1FreqTable=/sys/devices/system/cpu/cpufreq/mp-cpufreq/cluster1_freq_table
    cluster2FreqTable=/sys/devices/system/cpu/cpufreq/mp-cpufreq/cluster2_freq_table
    kfcFreqTable=/sys/devices/system/cpu/cpufreq/mp-cpufreq/kfc_freq_table
    cpuFreqTable=/sys/devices/system/cpu/cpufreq/mp-cpufreq/cpu_freq_table

    if [ -e $cluster0FreqTable ]; then
      minFreq=$($BUSYBOX cat $cluster0FreqTable | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $1}')
      maxFreq=$($BUSYBOX cat $cluster0FreqTable | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $NF}')

      if [ "$minFreq" -lt "$maxFreq" ]; then
        echo "$minFreq " >>$MIN_MAX_FREQ
        echo "$maxFreq " >>$MIN_MAX_FREQ
      elif [ "$minFreq" -gt "$maxFreq" ]; then
        echo "$maxFreq " >>$MIN_MAX_FREQ
        echo "$minFreq " >>$MIN_MAX_FREQ
      fi
    fi
    unset minFreq
    unset maxFreq

    if [ -e $cluster1FreqTable ]; then
      minFreq=$($BUSYBOX cat $cluster1FreqTable | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $1}')
      maxFreq=$($BUSYBOX cat $cluster1FreqTable | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $NF}')

      if [ "$minFreq" -lt "$maxFreq" ]; then
        echo "$minFreq " >>$MIN_MAX_FREQ
        echo "$maxFreq " >>$MIN_MAX_FREQ
      elif [ "$minFreq" -gt "$maxFreq" ]; then
        echo "$maxFreq " >>$MIN_MAX_FREQ
        echo "$minFreq " >>$MIN_MAX_FREQ
      fi
    fi
    unset minFreq
    unset maxFreq

    if [ -e $cluster2FreqTable ]; then
      minFreq=$($BUSYBOX cat $cluster2FreqTable | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $1}')
      maxFreq=$($BUSYBOX cat $cluster2FreqTable | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $NF}')

      if [ "$minFreq" -lt "$maxFreq" ]; then
        echo "$minFreq " >>$MIN_MAX_FREQ
        echo "$maxFreq " >>$MIN_MAX_FREQ
      elif [ "$minFreq" -gt "$maxFreq" ]; then
        echo "$maxFreq " >>$MIN_MAX_FREQ
        echo "$minFreq " >>$MIN_MAX_FREQ
      fi
    fi
    unset minFreq
    unset maxFreq

    if [ -e $kfcFreqTable ]; then
      minFreq=$($BUSYBOX cat $kfcFreqTable | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $1}')
      maxFreq=$($BUSYBOX cat $kfcFreqTable | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $NF}')

      if [ "$minFreq" -lt "$maxFreq" ]; then
        echo "$minFreq " >>$MIN_MAX_FREQ
        echo "$maxFreq " >>$MIN_MAX_FREQ
      elif [ "$minFreq" -gt "$maxFreq" ]; then
        echo "$maxFreq " >>$MIN_MAX_FREQ
        echo "$minFreq " >>$MIN_MAX_FREQ
      fi
    fi
    unset minFreq
    unset maxFreq

    if [ -e $cpuFreqTable ]; then
      minFreq=$($BUSYBOX cat $cpuFreqTable | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $1}')
      maxFreq=$($BUSYBOX cat $cpuFreqTable | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $NF}')

      if [ "$minFreq" -lt "$maxFreq" ]; then
        echo "$minFreq " >>$MIN_MAX_FREQ
        echo "$maxFreq " >>$MIN_MAX_FREQ
      elif [ "$minFreq" -gt "$maxFreq" ]; then
        echo "$maxFreq " >>$MIN_MAX_FREQ
        echo "$minFreq " >>$MIN_MAX_FREQ
      fi
    fi
    unset minFreq
    unset maxFreq
  fi

  sleep 0.5

  unset cluster0FreqTable
  unset cluster1FreqTable
  unset cluster2FreqTable
  unset kfcFreqTable
  unset cpuFreqTable
}

#######
# Method returns Min frequency of LITTLE, BIG and PRIME cores,
# also REGULAR frequency in a list taking min_max_freq list as argument
#######
getMinFreqList() {
  rm -rf "$MIN_FREQ_LIST"

  minMaxFreqSize=$($BUSYBOX cat $MIN_MAX_FREQ | $BUSYBOX tr '\n' ' ' | $BUSYBOX wc -w)

  i=1
  while [ $i -le "$minMaxFreqSize" ]; do

    minFreqList=$($BUSYBOX cat $MIN_MAX_FREQ | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $'$i'}')

    echo "$minFreqList " >>$MIN_FREQ_LIST

    i=$((i + 2))
  done

  sleep 0.5

  unset minMaxFreqSize
  unset i
  unset minFreqList
}

#######
# Method returns Max frequency of LITTLE, BIG and PRIME cores,
# also REGULAR frequency in a list taking min_max_freq list as argument
#######
getMaxFreqList() {
  rm -rf "$MAX_FREQ_LIST"

  minMaxFreqSize=$($BUSYBOX cat $MIN_MAX_FREQ | $BUSYBOX tr '\n' ' ' | $BUSYBOX wc -w)

  i=2
  while [ $i -le "$minMaxFreqSize" ]; do

    maxFreqList=$($BUSYBOX cat $MIN_MAX_FREQ | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $'$i'}')

    echo "$maxFreqList " >>$MAX_FREQ_LIST

    i=$((i + 2))
  done

  sleep 0.5

  unset minMaxFreqSize
  unset i
  unset maxFreqList
}

#######
# Logical cores detect the parent core of the cluster
#######
logicalCores() {
  rm -rf $LOGICAL_CORE

  #####
  # Get the logical core over affected cpu list
  #####
  core_count=$($BUSYBOX cat $CPU_CORE_COUNT)
  # Counter
  core=0

  # Core 0 is always affected
  echo "0 " >$LOGICAL_CORE

  while [ $core -le "$core_count" ]; do
    affected_cpus=/sys/devices/system/cpu/cpu$core/cpufreq/affected_cpus

    if [ -e $affected_cpus ]; then
      getAffectedCPU=$($BUSYBOX cat $affected_cpus | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $1}')

      getLastInputAffectedCPU=$($BUSYBOX cat $LOGICAL_CORE | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $NF}')

      # shellcheck disable=SC2086
      if [ ! "$getLastInputAffectedCPU" -eq $getAffectedCPU ]; then
        echo "$getAffectedCPU " >>$LOGICAL_CORE
      fi
    fi

    core=$((core + 1))
  done

  sleep 0.5

  unset core_count
  unset core
  unset affected_cpus
  unset getAffectedCPU
  unset getLastInputAffectedCPU
}

##########
# Lets create a Integer list containing non-repeating values of max_frequency
##########
getUniqueFreq() {
  rm -rf $UNIQUE_FREQ

  sleep 0.2

  $BUSYBOX cat $MAX_FREQ_LIST | $BUSYBOX uniq >$UNIQUE_FREQ

  sleep 0.5
}

##########
# coreGetter returns a list with parent core of clusters in descending order PRIME to LITTLE
##########
coreGetter() {

  rm -rf $CORE_GETTER

  prime=0
  big=0
  little=0

  logicalCoresListSize=$($BUSYBOX cat $LOGICAL_CORE | $BUSYBOX tr '\n' ' ' | $BUSYBOX wc -w)
  uniqueFreqListSize=$($BUSYBOX cat $UNIQUE_FREQ | $BUSYBOX tr '\n' ' ' | $BUSYBOX wc -w)
  real_core_count=$($BUSYBOX cat $REAL_CPU_CORE_COUNT)

  if [ "$logicalCoresListSize" -eq 3 ] && [ "$uniqueFreqListSize" -eq 3 ]; then

    firstHighestFreq=$($BUSYBOX cat $UNIQUE_FREQ | $BUSYBOX sort -n | $BUSYBOX tail -1 | $BUSYBOX head -1)
    secondHighestFreq=$($BUSYBOX cat $UNIQUE_FREQ | $BUSYBOX sort -n | $BUSYBOX tail -2 | $BUSYBOX head -1)
    thirdHighestFreq=$($BUSYBOX cat $UNIQUE_FREQ | $BUSYBOX sort -n | $BUSYBOX tail -3 | $BUSYBOX head -1)

    getPrimeCluster="$(grep -n "$firstHighestFreq" $UNIQUE_FREQ | head -n 1 | cut -d: -f1)"
    getBigCluster="$(grep -n "$secondHighestFreq" $UNIQUE_FREQ | head -n 1 | cut -d: -f1)"
    getLittleCluster="$(grep -n "$thirdHighestFreq" $UNIQUE_FREQ | head -n 1 | cut -d: -f1)"

    prime=$($BUSYBOX cat $LOGICAL_CORE | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $'$getPrimeCluster'}')
    big=$($BUSYBOX cat $LOGICAL_CORE | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $'$getBigCluster'}')
    little=$($BUSYBOX cat $LOGICAL_CORE | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $'$getLittleCluster'}')

    $BUSYBOX printf "$prime\n$big\n$little" >$CORE_GETTER

  elif
    [ "$logicalCoresListSize" -eq 2 ] && [ "$uniqueFreqListSize" -eq 2 ]
  then

    firstHighestFreq=$($BUSYBOX cat $UNIQUE_FREQ | $BUSYBOX sort -n | $BUSYBOX tail -1 | $BUSYBOX head -1)
    secondHighestFreq=$($BUSYBOX cat $UNIQUE_FREQ | $BUSYBOX sort -n | $BUSYBOX tail -2 | $BUSYBOX head -1)

    getBigCluster="$($BUSYBOX grep -n "$firstHighestFreq" $UNIQUE_FREQ | $BUSYBOX head -n 1 | $BUSYBOX cut -d: -f1)"
    getLittleCluster="$($BUSYBOX grep -n "$secondHighestFreq" $UNIQUE_FREQ | $BUSYBOX head -n 1 | $BUSYBOX cut -d: -f1)"

    big=$($BUSYBOX cat $LOGICAL_CORE | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $'$getBigCluster'}')
    little=$($BUSYBOX cat $LOGICAL_CORE | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $'$getLittleCluster'}')

    $BUSYBOX printf "$big\n$little" >$CORE_GETTER

    getBig=$($BUSYBOX cat $CORE_GETTER | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $1}')
    getLittle=$($BUSYBOX cat $CORE_GETTER | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $2}')

    # This is some dirty getter of inverted cluster
    # for now works well
    if [ $getBig -gt $getLittle ]; then
      littleCoresCount=$((getBig))
      bigCoresCount=$((real_core_count - getBig))
    else
      littleCoresCount=$((real_core_count - getLittle))
      bigCoresCount=$((getLittle))
    fi

    echo "$bigCoresCount" >$BIG_CORES_COUNT
    echo "$littleCoresCount" >$LITTLE_CORES_COUNT

  else
    $BUSYBOX cat $LOGICAL_CORE | $BUSYBOX tr ' ' '\n' | $BUSYBOX sort -n -r | $BUSYBOX uniq >$CORE_GETTER

  fi

  unset logicalCoresListSize
  unset uniqueFreqListSize
  unset prime
  unset big
  unset little
  unset firstHighestFreq
  unset secondHighestFreq
  unset thirdHighestFreq
  unset getPrimeCluster
  unset getBigCluster
  unset getLittleCluster
  sleep 0.5

}

######
# Function to call CPU detection related functions
######
cpuDetect() {
  getCPUcoreCount
  getMinAndMaxFreq
  getMinFreqList
  getMaxFreqList
  logicalCores
  getUniqueFreq
  coreGetter
}

disableDebugging() {
  sendToLog "Powerful logging disable started..."

  sched_schedstats=/proc/sys/kernel/sched_schedstats
  if [ -e $sched_schedstats ]; then
    write $sched_schedstats "0"
    sendToLog "Disabled sched_schedstats"
  fi

  console_suspend=/sys/module/printk/parameters/console_suspend
  if [ -e $console_suspend ]; then
    write $console_suspend "Y"
    sendToLog "Console suspended"
  fi

  printk=/proc/sys/kernel/printk
  if [ -e $printk ]; then
    write $printk "0 0 0 0"
    sendToLog "Fully disable kernel printk console log spamming (Reduces overhead)"
  fi

  log_mode=/sys/module/logger/parameters/log_mode
  if [ -e $log_mode ]; then
    write $log_mode "2"
    sendToLog "Logger disabled"
  fi

  debug_enabled=/sys/kernel/debug/debug_enabled
  if [ -e $debug_enabled ]; then
    write $debug_enabled "N"
    sendToLog "Disabled kernel debugging"
  fi

  exception_trace=/proc/sys/debug/exception-trace
  if [ -e "$exception_trace" ]; then
    write $exception_trace "0"
    sendToLog "Disabled exception-trace debugger"
  fi

  nmi_watchdog=/proc/sys/kernel/nmi_watchdog
  if [ -e "$nmi_watchdog" ]; then
    write $nmi_watchdog "0"
    sendToLog "Disabled nmi_watchdog"
  fi

  mali_debug_level=/sys/module/mali/parameters/mali_debug_level
  if [ -e $mali_debug_level ]; then
    write $mali_debug_level "0"
    sendToLog "Disabled mali GPU debugging"
  fi

  block_dump=/proc/sys/vm/block_dump
  if [ -e $block_dump ]; then
    write $block_dump "0"
    sendToLog "Disabled I/O block debugging"
  fi

  mballoc_debug=/sys/module/ext4/parameters/mballoc_debug
  if [ -e $mballoc_debug ]; then
    write $mballoc_debug "0"
    sendToLog "Disabled ext4 runtime debugging"
  fi

  logger_mode=/sys/kernel/logger_mode/logger_mode
  if [ -e $logger_mode ]; then
    write $logger_mode "0"
    sendToLog "Disabled $logger_mode"
  fi

  log_enabled=/sys/module/logger/parameters/log_enabled
  if [ -e $log_enabled ]; then
    write $log_enabled "0"
    sendToLog "Disabled $log_enabled"
  fi

  logger_enabled=/sys/module/logger/parameters/enabled
  if [ -e $logger_enabled ]; then
    write $logger_enabled "0"
    sendToLog "Disabled $logger_enabled"
  fi

  compat_log=/proc/sys/kernel/compat-log
  if [ -e $compat_log ]; then
    write $compat_log "0"
    sendToLog "Compat logging disabled"
  fi

  disable_ertm=/sys/module/bluetooth/parameters/disable_ertm
  if [ -e $disable_ertm ]; then
    write $disable_ertm "0"
    sendToLog "Bluetooth ertm disabled"
  fi

  disable_esco=/sys/module/bluetooth/parameters/disable_esco
  if [ -e $disable_esco ]; then
    write $disable_esco "0"
    sendToLog "Bluetooth esco is disabled"
  fi

  sendToLog "Logging disabled..."
  sendToLog "$divider"
}

miscTweaks() {
  sendToLog "Applying parameters started..."

  # Disabling ksm
  if [ -e "/sys/kernel/mm/ksm/run" ]; then
    write /sys/kernel/mm/ksm/run "0"
    sendToLog "KSM is disabled, saving battery cycles and improving battery life..."
  fi

  # Disabling uksm
  if [ -e "/sys/kernel/mm/uksm/run" ]; then
    write /sys/kernel/mm/uksm/run "0"
    sendToLog "UKSM is disabled, saving battery cycles and improving battery life..."
  fi

  # Kernel sleepers
  if [ -e "/sys/kernel/sched/gentle_fair_sleepers" ]; then
    write /sys/kernel/sched/gentle_fair_sleepers "0"
    sendToLog "Gentle fair sleepers disabled..."
  fi

  if [ -e "/sys/kernel/sched/arch_power" ]; then
    write /sys/kernel/sched/arch_power "1"
    sendToLog "Arch power enabled..."
  fi

  if [ -e "/sys/kernel/debug/sched_features" ]; then
    # Only give sleepers 50% of their service deficit. This allows
    # them to run sooner, but does not allow tons of sleepers to
    # rip the spread apart.
    write /sys/kernel/debug/sched_features "NO_GENTLE_FAIR_SLEEPERS"
    sendToLog "GENTLE_FAIR_SLEEPERS disabled..."

    write /sys/kernel/debug/sched_features "ARCH_POWER"
    sendToLog "ARCH_POWER enabled..."
  fi

  # Let's count this as nonsense, test needed
  setprop windowsmgr.max_events_per_sec 500
  setprop debug.sf.hw 1
  setprop debug.gr.swapinterval 0
  setprop video.accelerate.hw 1

  #/sys/power/pm_freeze_timeout controls how long it will cost at most to freeze
  #all user space processes or all freezable kernel threads, in unit of millisecond.
  #The default value is 20000, some Xiaomi devices are going in range from 2000 to 15000
  #more info on https://www.kernel.org/doc/Documentation/power/freezing-of-tasks.txt
  if [ -e "/sys/power/pm_freeze_timeout" ]; then
    write /sys/power/pm_freeze_timeout "5000"
    sendToLog "Kernel thread freeze time set to 5 seconds"
  fi

  # Enable fast charging
  if [ -e "/sys/kernel/fast_charge/force_fast_charge" ]; then
    write /sys/kernel/fast_charge/force_fast_charge "1"
    sendToLog "Fast charge enabled"
  fi

  # Disable gesture based vibration because it is honestly not even worth having enabled at all;
  if [ -e "/sys/android_touch/vib_strength" ]; then
    write /sys/android_touch/vib_strength "0"
    sendToLog "Disabled gesture vibrations"
  fi

  # lpm Levels
  lpm=/sys/module/lpm_levels
  if [ -d $lpm/parameters ]; then
    write $lpm/parameters/lpm_prediction "Y"
    write $lpm/parameters/sleep_disabled "0"
    sendToLog "Low power mode sleep enabled"
  fi

  if [ -e "/sys/class/lcd/panel/power_reduce" ]; then
    write /sys/class/lcd/panel/power_reduce "1"
    sendToLog "LCD power reduce enabled"
  fi

  if [ -e "/sys/module/pm2/parameters/idle_sleep_mode" ]; then
    write /sys/module/pm2/parameters/idle_sleep_mode "Y"
    sendToLog "PM2 module idle sleep mode enabled"
  fi

  sendToLog "$divider"
}

#######
# Cpuset tuner used to tune up cpusets according to different CPU structures
#######
cpusetTuner() {
  # Starting cpu_detect
  sendToLog "Starting CPU detect..."

  core_getter_list_size=$($BUSYBOX cat $CORE_GETTER | $BUSYBOX tr '\n' ' ' | $BUSYBOX wc -w)
  core_count=$($BUSYBOX cat $CPU_CORE_COUNT)
  real_core_count=$($BUSYBOX cat $REAL_CPU_CORE_COUNT)

  if [ "$core_getter_list_size" -eq 3 ]; then
    getPrime=$($BUSYBOX cat $CORE_GETTER | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $1}')
    getBig=$($BUSYBOX cat $CORE_GETTER | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $2}')
    getLittle=$($BUSYBOX cat $CORE_GETTER | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $3}')

    # This shows real numbers, for usage we should use n-1
    # e.g. CPU have 4 LITTLE(0-3) and 3 BIG (4-6) and 1 PRIME (7-7)
    littleCoresCount=$((getBig))
    bigCoresCount=$((getPrime - getBig))
    primeCoresCount=$((real_core_count - getPrime))

    sendToLog "Setting up cpuset for $littleCoresCount(0-$((getBig - 1))) LITTLE CPU cores, $bigCoresCount($getBig-$((getPrime - 1))) BIG CPU cores and $primeCoresCount($getPrime-$core_count) PRIME CPU cores"

    # Setting up cpuset based on profiles
    if [ "$1" = "1" ]; then
      # 0-1 2-5 6-9
      if [ $littleCoresCount -eq 2 ] && [ $bigCoresCount -eq 4 ] && [ $primeCoresCount -eq 4 ]; then
        foreground="0-4"
        topApp="0-5"
        background="0-1"
        systemBackground="0-1"

        validConfig=true

      # 0-3 4-5 6-7
      elif [ $littleCoresCount -eq 4 ] && [ $bigCoresCount -eq 2 ] && [ $primeCoresCount -eq 2 ]; then
        foreground="0-4"
        topApp="0-5"
        background="0-2"
        systemBackground="0-3"

        validConfig=true

      # 0-3 4-6 7
      elif [ $littleCoresCount -eq 4 ] && [ $bigCoresCount -eq 3 ] && [ $primeCoresCount -eq 1 ]; then
        foreground="0-3"
        topApp="0-4"
        background="0-2"
        systemBackground="0-3"

        validConfig=true
      else
        sendToLog "Cannot set cpuset for this CPU configuration"

        validConfig=false
      fi
    elif [ "$1" = "2" ]; then
      # 0-1 2-5 6-9
      if [ $littleCoresCount -eq 2 ] && [ $bigCoresCount -eq 4 ] && [ $primeCoresCount -eq 4 ]; then
        foreground="0-4"
        topApp="0-5"
        background="0-1"
        systemBackground="0-1"

        validConfig=true

      # 0-3 4-5 6-7
      elif [ $littleCoresCount -eq 4 ] && [ $bigCoresCount -eq 2 ] && [ $primeCoresCount -eq 2 ]; then
        foreground="0-5"
        topApp="0-6"
        background="0-2"
        systemBackground="0-3"

        validConfig=true

      # 0-3 4-6 7
      elif [ $littleCoresCount -eq 4 ] && [ $bigCoresCount -eq 3 ] && [ $primeCoresCount -eq 1 ]; then
        foreground="0-5"
        topApp="0-2,4-6"
        background="0-2"
        systemBackground="0-3"

        validConfig=true
      else
        sendToLog "Cannot set cpuset for this CPU configuration"

        validConfig=false
      fi
    elif [ "$1" = "3" ]; then
      # 0-1 2-5 6-9
      if [ $littleCoresCount -eq 2 ] && [ $bigCoresCount -eq 4 ] && [ $primeCoresCount -eq 4 ]; then
        foreground="0-8"
        topApp="0-9"
        background="0-1"
        systemBackground="0-1"

        validConfig=true

      # 0-3 4-5 6-7
      elif [ $littleCoresCount -eq 4 ] && [ $bigCoresCount -eq 2 ] && [ $primeCoresCount -eq 2 ]; then
        foreground="0-6"
        topApp="0-7"
        background="0-2"
        systemBackground="0-3"

        validConfig=true

      # 0-3 4-6 7
      elif [ $littleCoresCount -eq 4 ] && [ $bigCoresCount -eq 3 ] && [ $primeCoresCount -eq 1 ]; then
        foreground="0-6"
        topApp="0-7"
        background="0-2"
        systemBackground="0-3"

        validConfig=true
      else
        sendToLog "Cannot set cpuset for this CPU configuration"

        validConfig=false
      fi
    fi

  elif [ "$core_getter_list_size" -eq 2 ]; then
    # This shows real numbers, for usage we should use n-1
    # e.g. CPU have 6 LITTLE(0-5) and 2 BIG (6-7)
    littleCoresCount=$($BUSYBOX cat $LITTLE_CORES_COUNT)
    bigCoresCount=$($BUSYBOX cat $BIG_CORES_COUNT)

    sendToLog "Setting up cpuset for $littleCoresCount LITTLE CPU cores and $bigCoresCount BIG CPU cores"

    # Setting up cpuset based on profiles
    if [ "$1" = "1" ]; then
      # 0-1 2-3
      if [ $littleCoresCount -eq 2 ] && [ $bigCoresCount -eq 2 ]; then
        foreground="0-1"
        topApp="0-3"
        background="0-1"
        systemBackground="0-1"

        validConfig=true

      # 0-3 4-5
      elif [ $littleCoresCount -eq 4 ] && [ $bigCoresCount -eq 2 ]; then
        foreground="0-2,4"
        topApp="0-5"
        background="0-2"
        systemBackground="0-3"

        validConfig=true

      # 0-3 4-7
      elif [ $littleCoresCount -eq 4 ] && [ $bigCoresCount -eq 4 ]; then
        foreground="0-2,4-5"
        topApp="0-7"
        background="0-2"
        systemBackground="0-3"

        validConfig=true

      # 0-5 6-7
      elif [ $littleCoresCount -eq 6 ] && [ $bigCoresCount -eq 2 ]; then
        foreground="0-2,6"
        topApp="0-7"
        background="0-2"
        systemBackground="0-5"

        validConfig=true
      else
        sendToLog "Cannot set cpuset for this CPU configuration"

        validConfig=false
      fi
    elif [ "$1" = "2" ]; then
      # 0-1 2-3
      if [ $littleCoresCount -eq 2 ] && [ $bigCoresCount -eq 2 ]; then
        foreground="0-2"
        topApp="0-3"
        background="0-1"
        systemBackground="0-2"

        validConfig=true

      # 0-3 4-5
      elif [ $littleCoresCount -eq 4 ] && [ $bigCoresCount -eq 2 ]; then
        foreground="0-4"
        topApp="0-5"
        background="0-2"
        systemBackground="0-3"

        validConfig=true

      # 0-3 4-7
      elif [ $littleCoresCount -eq 4 ] && [ $bigCoresCount -eq 4 ]; then
        foreground="0-2,4-5"
        topApp="0-7"
        background="0-2"
        systemBackground="0-3"

        validConfig=true

      # 0-5 6-7
      elif [ $littleCoresCount -eq 6 ] && [ $bigCoresCount -eq 2 ]; then
        foreground="0-3,6"
        topApp="0-7"
        background="0-2"
        systemBackground="0-5"

        validConfig=true
      else
        sendToLog "Cannot set cpuset for this CPU configuration"

        validConfig=false
      fi
    elif [ "$1" = "3" ]; then
      # 0-1 2-3
      if [ $littleCoresCount -eq 2 ] && [ $bigCoresCount -eq 2 ]; then
        foreground="0-2"
        topApp="0-3"
        background="0-1"
        systemBackground="0-2"

        validConfig=true

      # 0-3 4-5
      elif [ $littleCoresCount -eq 4 ] && [ $bigCoresCount -eq 2 ]; then
        foreground="0-4"
        topApp="0-5"
        background="0-2"
        systemBackground="0-3"

        validConfig=true

      # 0-3 4-7
      elif [ $littleCoresCount -eq 4 ] && [ $bigCoresCount -eq 4 ]; then
        foreground="0-6"
        topApp="0-7"
        background="0-2"
        systemBackground="0-3"

        validConfig=true

      # 0-5 6-7
      elif [ $littleCoresCount -eq 6 ] && [ $bigCoresCount -eq 2 ]; then
        foreground="0-6"
        topApp="0-7"
        background="0-2"
        systemBackground="0-5"

        validConfig=true
      else
        sendToLog "Cannot set cpuset for this CPU configuration"

        validConfig=false
      fi
    fi
  else
    getRegular=$($BUSYBOX cat $CORE_GETTER | $BUSYBOX tr '\n' ' ' | $BUSYBOX awk '{print $1}')

    sendToLog "Setting up cpuset for $real_core_count REGULAR CPU cores"

    # Setting up cpuset based on profiles
    if [ "$1" = "1" ]; then
      # 0-3
      if [ "$real_core_count" -eq 4 ]; then
        foreground="0-1"
        topApp="0-3"
        background="0-1"
        systemBackground="0-2"

        validConfig=true

      # 0-5
      elif [ "$real_core_count" -eq 6 ]; then
        foreground="0-3"
        topApp="0-4"
        background="0-2"
        systemBackground="0-3"

        validConfig=true

      # 0-7
      elif [ "$real_core_count" -eq 8 ]; then
        foreground="0-5"
        topApp="0-6"
        background="0-2"
        systemBackground="0-4"

        validConfig=true

      # 0-9
      elif [ "$real_core_count" -eq 10 ]; then
        foreground="0-5"
        topApp="0-6"
        background="0-2"
        systemBackground="0-4"

        validConfig=true
      else
        sendToLog "Cannot set cpuset for this CPU configuration"

        validConfig=false
      fi

    elif [ "$1" = "2" ]; then
      # 0-3
      if [ "$real_core_count" -eq 4 ]; then
        foreground="0-1"
        topApp="0-4"
        background="0-1"
        systemBackground="0-2"

        validConfig=true

      # 0-5
      elif [ "$real_core_count" -eq 6 ]; then
        foreground="0-3"
        topApp="0-4"
        background="0-2"
        systemBackground="0-3"

        validConfig=true

      # 0-7
      elif [ "$real_core_count" -eq 8 ]; then
        foreground="0-5"
        topApp="0-6"
        background="0-2"
        systemBackground="0-4"

        validConfig=true

      # 0-9
      elif [ "$real_core_count" -eq 10 ]; then
        foreground="0-7"
        topApp="0-8"
        background="0-2"
        systemBackground="0-4"

        validConfig=true
      else
        sendToLog "Cannot set cpuset for this CPU configuration"

        validConfig=false
      fi

    elif [ "$1" = "3" ]; then
      # 0-3
      if [ "$real_core_count" -eq 4 ]; then
        foreground="0-2"
        topApp="0-3"
        background="0-1"
        systemBackground="0-2"

        validConfig=true

      # 0-5
      elif [ "$real_core_count" -eq 6 ]; then
        foreground="0-4"
        topApp="0-5"
        background="0-2"
        systemBackground="0-3"

        validConfig=true

      # 0-7
      elif [ "$real_core_count" -eq 8 ]; then
        foreground="0-6"
        topApp="0-7"
        background="0-2"
        systemBackground="0-5"

        validConfig=true

      # 0-9
      elif [ "$real_core_count" -eq 10 ]; then
        foreground="0-8"
        topApp="0-9"
        background="0-2"
        systemBackground="0-5"

        validConfig=true
      else
        sendToLog "Cannot set cpuset for this CPU configuration"

        validConfig=false
      fi
    fi
  fi

  if [ $validConfig = true ]; then
    # update cpuset now that processors are up
    # Foreground should contain most cores
    if [ -e /dev/cpuset/foreground/cpus ]; then
      write /dev/cpuset/foreground/cpus "$foreground"
      sendToLog "cpuset for foreground set: $foreground"
    fi

    # top-app usualy all the cpus
    if [ -e /dev/cpuset/top-app/cpus ]; then
      write /dev/cpuset/top-app/cpus "$topApp"
      sendToLog "cpuset for top-app set: $topApp"
    fi

    # background contains a small subset so lower cores as possible
    if [ -e /dev/cpuset/background/cpus ]; then
      write /dev/cpuset/background/cpus "$background"
      sendToLog "cpuset for background set: $background"
    fi

    # add system-background cpuset, a new cpuset for system services
    # that should not run on larger cores
    # system-background is for system tasks that should only run on
    # little cores, not on bigs to be used only by init
    # so we are using about the half of the cpu cores
    if [ -e /dev/cpuset/system-background/cpus ]; then
      write /dev/cpuset/system-background/cpus "$systemBackground"
      sendToLog "cpuset for system-background set: $systemBackground"
    fi
  fi
}

cpuOptimization() {
  if [ "$1" = "1" ]; then
    profile="power saving"
  elif [ "$1" = "2" ]; then
    profile="balanced"
  elif [ "$1" = "3" ]; then
    profile="performance"
  fi

  sendToLog "Applying $profile CPU optimization..."
  cpuDetect

  if [ "$1" = "1" ]; then
    if [ -e "/sys/devices/system/cpu/cpuidle/use_deepest_state" ]; then
      write /sys/devices/system/cpu/cpuidle/use_deepest_state "1"
      sendToLog "Enable deepest CPU idle state"
    fi

    # Disable krait voltage boost
    if [ -e "/sys/module/acpuclock_krait/parameters/boost" ]; then
      write /sys/module/acpuclock_krait/parameters/boost "N"
      sendToLog "Disable Krait voltage boost"
    fi

    if [ -e "/sys/module/workqueue/parameters/power_efficient" ]; then
      lockFile /sys/module/workqueue/parameters/power_efficient "Y"
      sendToLog "Power-save workqueues enabled, scheduling workqueues on awake CPUs to save power."
    fi

    sched_boost=/proc/sys/kernel/sched_boost
    if [ -e $sched_boost ]; then
      write $sched_boost "0"
      sendToLog "sched_boost=0"
    fi

    perf_cpu_time_max_percent=/proc/sys/kernel/perf_cpu_time_max_percent
    if [ -e $perf_cpu_time_max_percent ]; then
      write $perf_cpu_time_max_percent "5"
      sendToLog "perf_cpu_time_max_percent=5"
    fi

    sched_autogroup_enabled=/proc/sys/kernel/sched_autogroup_enabled
    if [ -e $sched_autogroup_enabled ]; then
      write $sched_autogroup_enabled "1"
      sendToLog "sched_autogroup_enabled=1"
    fi

    sched_child_runs_first=/proc/sys/kernel/sched_child_runs_first
    if [ -e $sched_child_runs_first ]; then
      write $sched_child_runs_first "1"
      sendToLog "sched_child_runs_first=1"
    fi

    sched_tunable_scaling=/proc/sys/kernel/sched_tunable_scaling
    if [ -e $sched_tunable_scaling ]; then
      write $sched_tunable_scaling "0"
      sendToLog "sched_tunable_scaling=0"
    fi

    sched_latency_ns=/proc/sys/kernel/sched_latency_ns
    if [ -e $sched_latency_ns ]; then
      write $sched_latency_ns "1000000"
      sendToLog "sched_latency_ns=1000000"
    fi

    sched_min_granularity_ns=/proc/sys/kernel/sched_min_granularity_ns
    if [ -e $sched_min_granularity_ns ]; then
      write $sched_min_granularity_ns "130000"
      sendToLog "sched_min_granularity_ns=130000"
    fi

    sched_wakeup_granularity_ns=/proc/sys/kernel/sched_wakeup_granularity_ns
    if [ -e $sched_wakeup_granularity_ns ]; then
      write $sched_wakeup_granularity_ns "750000"
      sendToLog "sched_wakeup_granularity_ns=750000"
    fi

    sched_migration_cost_ns=/proc/sys/kernel/sched_migration_cost_ns
    if [ -e $sched_migration_cost_ns ]; then
      write $sched_migration_cost_ns "3000000"
      sendToLog "sched_migration_cost_ns=3000000"
    fi

    sched_min_task_util_for_colocation=/proc/sys/kernel/sched_min_task_util_for_colocation
    if [ -e $sched_min_task_util_for_colocation ]; then
      write $sched_min_task_util_for_colocation "0"
      sendToLog "sched_min_task_util_for_colocation=0"
    fi

    sched_nr_migrate=/proc/sys/kernel/sched_nr_migrate
    if [ -e $sched_nr_migrate ]; then
      write $sched_nr_migrate "8"
      sendToLog "sched_nr_migrate=8"
    fi

    sched_schedstats=/proc/sys/kernel/sched_schedstats
    if [ -e $sched_schedstats ]; then
      write $sched_schedstats "0"
      sendToLog "sched_schedstats=0"
    fi

    # Disable touch boost
    touchboost=/sys/module/msm_performance/parameters/touchboost
    if [ -e $touchboost ]; then
      write $touchboost "0"
      sendToLog "$touchboost=0"
    fi

    touch_boost=/sys/power/pnpmgr/touch_boost
    if [ -e $touch_boost ]; then
      write $touch_boost "N"
      sendToLog "$touch_boost=N"
    fi

    #Disable CPU Boost
    boost_ms=/sys/module/cpu_boost/parameters/boost_ms
    if [ -e $boost_ms ]; then
      write $boost_ms "N"
      sendToLog "$boost_ms=N"
    fi

    sched_boost_on_input=/sys/module/cpu_boost/parameters/sched_boost_on_input
    if [ -e $sched_boost_on_input ]; then
      write $sched_boost_on_input "N"
      sendToLog "$sched_boost_on_input=N"
    fi

    stune_background_prefer_idle="/dev/stune/background/schedtune.prefer_idle"
    if [ -e $stune_background_prefer_idle ]; then
      write $stune_background_prefer_idle "0"
      sendToLog "$stune_background_prefer_idle=0"
    fi

    stune_foreground_prefer_idle="/dev/stune/foreground/schedtune.prefer_idle"
    if [ -e $stune_foreground_prefer_idle ]; then
      write $stune_foreground_prefer_idle "0"
      sendToLog "$stune_foreground_prefer_idle=0"
    fi

    stune_topapp_prefer_idle="/dev/stune/top-app/schedtune.prefer_idle"
    if [ -e $stune_topapp_prefer_idle ]; then
      write $stune_topapp_prefer_idle "1"
      sendToLog "$stune_topapp_prefer_idle=1"
    fi

    stune_topapp_schedtune_boost="/dev/stune/top-app/schedtune.boost"
    if [ -e $stune_topapp_schedtune_boost ]; then
      write $stune_topapp_schedtune_boost 1
      sendToLog "$stune_topapp_schedtune_boost=1"
    fi

    #stune_global_prefer_idle="/dev/stune/schedtune.prefer_idle"
    #if [ -e $stune_global_prefer_idle ]; then
    #  write $stune_global_prefer_idle "0"
    #  sendToLog "$stune_global_prefer_idle=0"
    #fi

    #stune_rt_prefer_idle="/dev/stune/rt/schedtune.prefer_idle"
    #if [ -e $stune_rt_prefer_idle ]; then
    #  write $stune_rt_prefer_idle "0"
    #  sendToLog "$stune_rt_prefer_idle=0"
    #fi

  elif [ "$1" = "2" ]; then
    if [ -e "/sys/devices/system/cpu/cpuidle/use_deepest_state" ]; then
      write /sys/devices/system/cpu/cpuidle/use_deepest_state "1"
      sendToLog "Enable deepest CPU idle state"
    fi

    # Disable krait voltage boost
    if [ -e "/sys/module/acpuclock_krait/parameters/boost" ]; then
      write /sys/module/acpuclock_krait/parameters/boost "N"
      sendToLog "Disable Krait voltage boost"
    fi

    if [ -e "/sys/module/workqueue/parameters/power_efficient" ]; then
      lockFile /sys/module/workqueue/parameters/power_efficient "N"
      sendToLog "Power-save workqueues disabled, scheduling workqueues on awake CPUs to save power."
    fi

    sched_boost=/proc/sys/kernel/sched_boost
    if [ -e $sched_boost ]; then
      write $sched_boost "0"
      sendToLog "sched_boost=0"
    fi

    perf_cpu_time_max_percent=/proc/sys/kernel/perf_cpu_time_max_percent
    if [ -e $perf_cpu_time_max_percent ]; then
      write $perf_cpu_time_max_percent "5"
      sendToLog "perf_cpu_time_max_percent=5"
    fi

    sched_autogroup_enabled=/proc/sys/kernel/sched_autogroup_enabled
    if [ -e $sched_autogroup_enabled ]; then
      write $sched_autogroup_enabled "1"
      sendToLog "sched_autogroup_enabled=1"
    fi

    sched_child_runs_first=/proc/sys/kernel/sched_child_runs_first
    if [ -e $sched_child_runs_first ]; then
      write $sched_child_runs_first "1"
      sendToLog "sched_child_runs_first=1"
    fi

    sched_tunable_scaling=/proc/sys/kernel/sched_tunable_scaling
    if [ -e $sched_tunable_scaling ]; then
      write $sched_tunable_scaling "0"
      sendToLog "sched_tunable_scaling=0"
    fi

    sched_latency_ns=/proc/sys/kernel/sched_latency_ns
    if [ -e $sched_latency_ns ]; then
      write $sched_latency_ns "1000000"
      sendToLog "sched_latency_ns=1000000"
    fi

    sched_min_granularity_ns=/proc/sys/kernel/sched_min_granularity_ns
    if [ -e $sched_min_granularity_ns ]; then
      write $sched_min_granularity_ns "130000"
      sendToLog "sched_min_granularity_ns=130000"
    fi

    sched_wakeup_granularity_ns=/proc/sys/kernel/sched_wakeup_granularity_ns
    if [ -e $sched_wakeup_granularity_ns ]; then
      write $sched_wakeup_granularity_ns "750000"
      sendToLog "sched_wakeup_granularity_ns=750000"
    fi

    sched_migration_cost_ns=/proc/sys/kernel/sched_migration_cost_ns
    if [ -e $sched_migration_cost_ns ]; then
      write $sched_migration_cost_ns "3000000"
      sendToLog "sched_migration_cost_ns=3000000"
    fi

    sched_min_task_util_for_colocation=/proc/sys/kernel/sched_min_task_util_for_colocation
    if [ -e $sched_min_task_util_for_colocation ]; then
      write $sched_min_task_util_for_colocation "0"
      sendToLog "sched_min_task_util_for_colocation=0"
    fi

    sched_nr_migrate=/proc/sys/kernel/sched_nr_migrate
    if [ -e $sched_nr_migrate ]; then
      write $sched_nr_migrate "8"
      sendToLog "sched_nr_migrate=8"
    fi

    sched_schedstats=/proc/sys/kernel/sched_schedstats
    if [ -e $sched_schedstats ]; then
      write $sched_schedstats "0"
      sendToLog "sched_schedstats=0"
    fi

    # Disable touch boost
    touchboost=/sys/module/msm_performance/parameters/touchboost
    if [ -e $touchboost ]; then
      write $touchboost "0"
      sendToLog "$touchboost=0"
    fi

    touch_boost=/sys/power/pnpmgr/touch_boost
    if [ -e $touch_boost ]; then
      write $touch_boost "N"
      sendToLog "$touch_boost=N"
    fi

    #Disable CPU Boost
    boost_ms=/sys/module/cpu_boost/parameters/boost_ms
    if [ -e $boost_ms ]; then
      write $boost_ms "N"
      sendToLog "$boost_ms=N"
    fi

    sched_boost_on_input=/sys/module/cpu_boost/parameters/sched_boost_on_input
    if [ -e $sched_boost_on_input ]; then
      write $sched_boost_on_input "N"
      sendToLog "$sched_boost_on_input=N"
    fi

    stune_background_prefer_idle="/dev/stune/background/schedtune.prefer_idle"
    if [ -e $stune_background_prefer_idle ]; then
      write $stune_background_prefer_idle "0"
      sendToLog "$stune_background_prefer_idle=0"
    fi

    stune_foreground_prefer_idle="/dev/stune/foreground/schedtune.prefer_idle"
    if [ -e $stune_foreground_prefer_idle ]; then
      write $stune_foreground_prefer_idle "0"
      sendToLog "$stune_foreground_prefer_idle=0"
    fi

    stune_topapp_prefer_idle="/dev/stune/top-app/schedtune.prefer_idle"
    if [ -e $stune_topapp_prefer_idle ]; then
      write $stune_topapp_prefer_idle "1"
      sendToLog "$stune_topapp_prefer_idle=1"
    fi

    stune_topapp_schedtune_boost="/dev/stune/top-app/schedtune.boost"
    if [ -e $stune_topapp_schedtune_boost ]; then
      write $stune_topapp_schedtune_boost 1
      sendToLog "$stune_topapp_schedtune_boost=1"
    fi

    #stune_global_prefer_idle="/dev/stune/schedtune.prefer_idle"
    #if [ -e $stune_global_prefer_idle ]; then
    #  write $stune_global_prefer_idle "0"
    #  sendToLog "$stune_global_prefer_idle=0"
    #fi

    #stune_rt_prefer_idle="/dev/stune/rt/schedtune.prefer_idle"
    #if [ -e $stune_rt_prefer_idle ]; then
    #  write $stune_rt_prefer_idle "0"
    #  sendToLog "$stune_rt_prefer_idle=0"
    #fi

  elif [ "$1" = "3" ]; then
    if [ -e "/sys/devices/system/cpu/cpuidle/use_deepest_state" ]; then
      write /sys/devices/system/cpu/cpuidle/use_deepest_state "1"
      sendToLog "Enable deepest CPU idle state"
    fi

    # Disable krait voltage boost
    if [ -e "/sys/module/acpuclock_krait/parameters/boost" ]; then
      write /sys/module/acpuclock_krait/parameters/boost "Y"
      sendToLog "Enable Krait voltage boost"
    fi

    if [ -e "/sys/module/workqueue/parameters/power_efficient" ]; then
      lockFile /sys/module/workqueue/parameters/power_efficient "N"
      sendToLog "Power-save workqueues disabled, scheduling workqueues on awake CPUs to save power."
    fi

    sched_boost=/proc/sys/kernel/sched_boost
    if [ -e $sched_boost ]; then
      write $sched_boost "0"
      sendToLog "sched_boost=0"
    fi

    perf_cpu_time_max_percent=/proc/sys/kernel/perf_cpu_time_max_percent
    if [ -e $perf_cpu_time_max_percent ]; then
      write $perf_cpu_time_max_percent "5"
      sendToLog "perf_cpu_time_max_percent=5"
    fi

    sched_autogroup_enabled=/proc/sys/kernel/sched_autogroup_enabled
    if [ -e $sched_autogroup_enabled ]; then
      write $sched_autogroup_enabled "1"
      sendToLog "sched_autogroup_enabled=1"
    fi

    sched_child_runs_first=/proc/sys/kernel/sched_child_runs_first
    if [ -e $sched_child_runs_first ]; then
      write $sched_child_runs_first "1"
      sendToLog "sched_child_runs_first=1"
    fi

    sched_tunable_scaling=/proc/sys/kernel/sched_tunable_scaling
    if [ -e $sched_tunable_scaling ]; then
      write $sched_tunable_scaling "0"
      sendToLog "sched_tunable_scaling=0"
    fi

    sched_latency_ns=/proc/sys/kernel/sched_latency_ns
    if [ -e $sched_latency_ns ]; then
      write $sched_latency_ns "1000000"
      sendToLog "sched_latency_ns=1000000"
    fi

    sched_min_granularity_ns=/proc/sys/kernel/sched_min_granularity_ns
    if [ -e $sched_min_granularity_ns ]; then
      write $sched_min_granularity_ns "130000"
      sendToLog "sched_min_granularity_ns=130000"
    fi

    sched_wakeup_granularity_ns=/proc/sys/kernel/sched_wakeup_granularity_ns
    if [ -e $sched_wakeup_granularity_ns ]; then
      write $sched_wakeup_granularity_ns "750000"
      sendToLog "sched_wakeup_granularity_ns=750000"
    fi

    sched_migration_cost_ns=/proc/sys/kernel/sched_migration_cost_ns
    if [ -e $sched_migration_cost_ns ]; then
      write $sched_migration_cost_ns "3000000"
      sendToLog "sched_migration_cost_ns=3000000"
    fi

    sched_min_task_util_for_colocation=/proc/sys/kernel/sched_min_task_util_for_colocation
    if [ -e $sched_min_task_util_for_colocation ]; then
      write $sched_min_task_util_for_colocation "0"
      sendToLog "sched_min_task_util_for_colocation=0"
    fi

    sched_nr_migrate=/proc/sys/kernel/sched_nr_migrate
    if [ -e $sched_nr_migrate ]; then
      write $sched_nr_migrate "8"
      sendToLog "sched_nr_migrate=8"
    fi

    sched_schedstats=/proc/sys/kernel/sched_schedstats
    if [ -e $sched_schedstats ]; then
      write $sched_schedstats "0"
      sendToLog "sched_schedstats=0"
    fi

    # Disable touch boost
    touchboost=/sys/module/msm_performance/parameters/touchboost
    if [ -e $touchboost ]; then
      write $touchboost "0"
      sendToLog "$touchboost=0"
    fi

    touch_boost=/sys/power/pnpmgr/touch_boost
    if [ -e $touch_boost ]; then
      write $touch_boost "N"
      sendToLog "$touch_boost=N"
    fi

    #Disable CPU Boost
    boost_ms=/sys/module/cpu_boost/parameters/boost_ms
    if [ -e $boost_ms ]; then
      write $boost_ms "N"
      sendToLog "$boost_ms=N"
    fi

    sched_boost_on_input=/sys/module/cpu_boost/parameters/sched_boost_on_input
    if [ -e $sched_boost_on_input ]; then
      write $sched_boost_on_input "N"
      sendToLog "$sched_boost_on_input=N"
    fi

    stune_background_prefer_idle="/dev/stune/background/schedtune.prefer_idle"
    if [ -e $stune_background_prefer_idle ]; then
      write $stune_background_prefer_idle "0"
      sendToLog "$stune_background_prefer_idle=0"
    fi

    stune_foreground_prefer_idle="/dev/stune/foreground/schedtune.prefer_idle"
    if [ -e $stune_foreground_prefer_idle ]; then
      write $stune_foreground_prefer_idle "0"
      sendToLog "$stune_foreground_prefer_idle=0"
    fi

    stune_topapp_prefer_idle="/dev/stune/top-app/schedtune.prefer_idle"
    if [ -e $stune_topapp_prefer_idle ]; then
      write $stune_topapp_prefer_idle "1"
      sendToLog "$stune_topapp_prefer_idle=1"
    fi

    stune_topapp_schedtune_boost="/dev/stune/top-app/schedtune.boost"
    if [ -e $stune_topapp_schedtune_boost ]; then
      write $stune_topapp_schedtune_boost 1
      sendToLog "$stune_topapp_schedtune_boost=1"
    fi

    #stune_global_prefer_idle="/dev/stune/schedtune.prefer_idle"
    #if [ -e $stune_global_prefer_idle ]; then
    #  write $stune_global_prefer_idle "0"
    #  sendToLog "$stune_global_prefer_idle=0"
    #fi

    #stune_rt_prefer_idle="/dev/stune/rt/schedtune.prefer_idle"
    #if [ -e $stune_rt_prefer_idle ]; then
    #  write $stune_rt_prefer_idle "0"
    #  sendToLog "$stune_rt_prefer_idle=0"
    #fi
  fi

  cpusetTuner $1

  sendToLog "Successfully applied $profile CPU optimization"
  sendToLog "$divider"
}

entropy() {
  sendToLog "Updating kernel random parameters..."

  $BUSYBOX sysctl -e -w kernel.random.read_wakeup_threshold=64
  sendToLog "read_wakeup_threshold=64"

  $BUSYBOX sysctl -e -w kernel.random.write_wakeup_threshold=128
  sendToLog "write_wakeup_threshold=128"

  sendToLog "Updating kernel random parameters is done"
  sendToLog "$divider"
}

ioOptimization() {
  sendToLog "Activating I/O blocks optimization..."

  #This tuning parameter controls the maximum
  #number of inode table blocks that ext4's inode
  #table readahead algorithm will pre-read into
  #the buffer cache.  The default value is 32 blocks.
  ext4blocks="/sys/fs/ext4/*"
  for ext4block in $ext4blocks; do
    if [ -e "$ext4block/inode_readahead_blks" ]; then
      write "$ext4block/inode_readahead_blks" "32"
      sendToLog "Pre-read cache of ext4 in $ext4block set to 32"
    fi

    if [ -e "$ext4block/mb_group_prealloc" ]; then
      write "$ext4block/mb_group_prealloc" "64"
      sendToLog "mb_group_prealloc in $ext4block set to 64"
    fi

    if [ -e "$ext4block/inode_goal" ]; then
      write "$ext4block/inode_goal" "8"
      sendToLog "inode_goal in $ext4block set to 8"
    fi

    if [ -e "$ext4block/extent_max_zeroout_kb" ]; then
      write "$ext4block/extent_max_zeroout_kb" "0"
      sendToLog "extent_max_zeroout_kb in $ext4block set to 0"
    fi

    if [ -e "$ext4block/mb_max_to_scan" ]; then
      write "$ext4block/mb_max_to_scan" "0"
      sendToLog "mb_max_to_scan in $ext4block set to 0"
    fi

    if [ -e "$ext4block/mb_min_to_scan" ]; then
      write "$ext4block/mb_min_to_scan" "0"
      sendToLog "mb_min_to_scan in $ext4block set to 0"
    fi

    if [ -e "$ext4block/mb_stream_req" ]; then
      write "$ext4block/mb_stream_req" "0"
      sendToLog "mb_stream_req in $ext4block set to 0"
    fi

    if [ -e "$ext4block/mb_order2_req" ]; then
      write "$ext4block/mb_order2_req" "0"
      sendToLog "mb_order2_req in $ext4block set to 0"
    fi
  done

  blocks="/sys/block/*"
  for i in $blocks; do

    #This file allows to turn off the disk entropy contribution. Default
    #value of this file is '1'(on).
    if [ -e "$i/queue/add_random" ]; then
      write "$i/queue/add_random" "0"
      sendToLog "add_random=0 in $i"
    fi

    #This enables the user to disable the lookup logic involved with IO
    #merging requests in the block layer. By default (0) all merges are
    #enabled. When set to 1 only simple one-hit merges will be tried. When
    #set to 2 no merge algorithms will be tried (including one-hit or more
    #complex tree/hash lookups).
    #if [ -e "$i/queue/nomerges" ]; then
    #  write "$i/queue/nomerges" "2"
    #  sendToLog "nomerges=2 in $i"
    #fi

    #If this option is '1', the block layer will migrate request completions to the
    #cpu "group" that originally submitted the request. For some workloads this
    #provides a significant reduction in CPU cycles due to caching effects.
    #For storage configurations that need to maximize distribution of completion
    #processing setting this option to '2' forces the completion to run on the
    #requesting cpu (bypassing the "group" aggregation logic).
    if [ -e "$i/queue/rq_affinity" ]; then
      write "$i/queue/rq_affinity" "2"
      sendToLog "rq_affinity=2 in $i"
    fi

    #This controls how many requests may be allocated in the block layer for
    #read or write requests. Note that the total allocated number may be twice
    #this amount, since it applies only to reads or writes (not the accumulated
    #sum).
    #To avoid priority inversion through request starvation, a request
    #queue maintains a separate request pool per each cgroup when
    #CONFIG_BLK_CGROUP is enabled, and this parameter applies to each such
    #per-block-cgroup request pool.  IOW, if there are N block cgroups,
    #each request queue may have up to N request pools, each independently
    #regulated by nr_requests.
    if [ -e "$i/queue/nr_requests" ]; then
      write "$i/queue/nr_requests" "64"
      sendToLog "nr_requests=64 in $i"
    fi

    #Maximum number of kilobytes to read-ahead for filesystems on this block
    #device.
    case $i in
    *"/sys/block/sd"*)
      if [ -e "$i/queue/read_ahead_kb" ]; then
        write "$i/queue/read_ahead_kb" "256"
        sendToLog "read_ahead_kb=256 in $i"
      fi
      ;;
    *"/sys/block/dm-"*)
      if [ -e "$i/queue/read_ahead_kb" ]; then
        write "$i/queue/read_ahead_kb" "256"
        sendToLog "read_ahead_kb=256 in $i"
      fi
      ;;
    "/sys/block/mmcblk0")
      if [ -e "$i/queue/read_ahead_kb" ]; then
        write "$i/queue/read_ahead_kb" "256"
        sendToLog "read_ahead_kb=256 in $i"
      fi
      ;;
    "/sys/block/mmcblk1")
      if [ -e "$i/queue/read_ahead_kb" ]; then
        write "$i/queue/read_ahead_kb" "256"
        sendToLog "read_ahead_kb=256 in $i"
      fi
      ;;
    *)
      if [ -e "$i/queue/read_ahead_kb" ]; then
        write "$i/queue/read_ahead_kb" "128"
        sendToLog "read_ahead_kb=128 in $i"
      fi
      ;;
    esac

    # Tell scheduler that it's facing with non rotational drive to disable
    # unnecessary seek-reducing logic in the scheduler. We are not using rotational HDDs
    if [ -e "$i/queue/rotational" ]; then
      write "$i/queue/rotational" "0"
      sendToLog "rotational=0 in $i"
    fi

    scheduler=$(getScheduler "$i")

    IOSCHED="$i/queue/iosched"

    # deadline
    FIFO_BATCH="$IOSCHED/fifo_batch"
    FRONT_MERGES="$IOSCHED/front_merges"
    READ_EXPIRE="$IOSCHED/read_expire"
    WRITE_EXPIRE="$IOSCHED/write_expire"
    WRITES_STARVED="$IOSCHED/writes_starved"

    # anxiety
    MAX_WRITES_STARVED="$IOSCHED/max_writes_starved"

    # cfq
    BACK_SEEK_PENALTY="$IOSCHED/back_seek_penalty"
    FIFO_EXPIRE_ASYNC="$IOSCHED/fifo_expire_async"
    FIFO_EXPIRE_SYNC="$IOSCHED/fifo_expire_sync"
    GROUP_IDLE="$IOSCHED/group_idle"
    LOW_LATENCY="$IOSCHED/low_latency"
    QUANTUM="$IOSCHED/quantum"
    SLICE_ASYNC="$IOSCHED/slice_async"
    SLICE_ASYNC_RQ="$IOSCHED/slice_async_rq"
    SLICE_IDLE="$IOSCHED/slice_idle"
    SLICE_SYNC="$IOSCHED/slice_sync"
    TARGET_LATENCY="$IOSCHED/target_latency"

    # bfq
    MAX_BUDGET="$IOSCHED/max_budget"
    MAX_BUDGET_ASYNC_RQ="$IOSCHED/max_budget_async_rq"
    TIMEOUT_ASYNC="$IOSCHED/timeout_async"
    TIMEOUT_SYNC="$IOSCHED/timeout_sync"
    WR_COEOFF="$IOSCHED/wr_coeff"
    WR_MAX_SOFTRT_RATE="$IOSCHED/wr_max_softrt_rate"
    WR_MAX_TIME="$IOSCHED/wr_max_time"
    WR_MIN_IDLE_TIME="$IOSCHED/wr_min_idle_time"
    WR_MIN_INTER_ARR_ASYNC="$IOSCHED/wr_min_inter_arr_async"
    WR_RT_MAX_TIME="$IOSCHED/wr_rt_max_time"

    # row
    HP_READ_QUANTUM="$IOSCHED/hp_read_quantum"
    HP_SWRITE_QUANTUM="$IOSCHED/hp_swrite_quantum"
    LOW_STARV_LIMIT="$IOSCHED/low_starv_limit"
    LP_READ_QUANTUM="$IOSCHED/lp_read_quantum"
    LP_SWRITE_QUANTUM="$IOSCHED/lp_swrite_quantum"
    RD_IDLE_DATA="$IOSCHED/rd_idle_data"
    RD_IDLE_DATA_FREQ="$IOSCHED/rd_idle_data_freq"
    READ_IDLE="$IOSCHED/read_idle"
    READ_IDLE_FREQ="$IOSCHED/read_idle_freq"
    REG_STARV_LIMIT="$IOSCHED/reg_starv_limit"
    RP_READ_QUANTUM="$IOSCHED/rp_read_quantum"
    RP_SWRITE_QUANTUM="$IOSCHED/rp_swrite_quantum"
    RP_WRITE_QUANTUM="$IOSCHED/rp_write_quantum"

    # fiops
    ASYNC_SCALE="$IOSCHED/async_scale"
    READ_SCALE="$IOSCHED/read_scale"
    SYNC_SCALE="$IOSCHED/sync_scale"
    WRITE_SCALE="$IOSCHED/write_scale"

    # sio/sioplus
    ASYNC_READ_EXPIRE="$IOSCHED/async_read_expire"
    ASYNC_WRITE_EXPIRE="$IOSCHED/async_write_expire"
    SYNC_READ_EXPIRE="$IOSCHED/sync_read_expire"
    SYNC_WRITE_EXPIRE="$IOSCHED/sync_write_expire"

    # zen
    ASYNC_EXPIRE="$IOSCHED/async_expire"
    SYNC_EXPIRE="$IOSCHED/sync_expire"

    # Write log when found a scheduler in block
    # This log contains current scheduler in $i block
    if [ "$scheduler" != "none" ]; then
      sendToLog "Found $scheduler in $i"
    fi

    # deadline
    if [ "$scheduler" = "deadline" ]; then
      if [ -e "$FIFO_BATCH" ]; then
        write "$FIFO_BATCH" "8"
        sendToLog "fifo_batch=8 in $i"
      fi

      if [ -e "$FRONT_MERGES" ]; then
        write "$FRONT_MERGES" "1"
        sendToLog "front_merges=1 in $i"
      fi

      if [ -e "$READ_EXPIRE" ]; then
        write "$READ_EXPIRE" "250"
        sendToLog "read_expire=250 in $i"
      fi

      if [ -e "$WRITE_EXPIRE" ]; then
        write "$WRITE_EXPIRE" "2500"
        sendToLog "write_expire=2500 in $i"
      fi

      if [ -e "$WRITES_STARVED" ]; then
        write "$WRITES_STARVED" "1"
        sendToLog "writes_starved=1 in $i"
      fi

    # anxiety
    elif [ "$scheduler" = "anxiety" ]; then
      if [ -e "$MAX_WRITES_STARVED" ]; then
        write "$MAX_WRITES_STARVED" "4"
        sendToLog "max_writes_starved=4 in $i"
      fi

    # cfq
    elif [ "$scheduler" = "cfq" ]; then
      if [ -e "$BACK_SEEK_PENALTY" ]; then
        write "$BACK_SEEK_PENALTY" "1"
        sendToLog "back_seek_penalty=1 in $i"
      fi

      if [ -e "$FIFO_EXPIRE_ASYNC" ]; then
        write "$FIFO_EXPIRE_ASYNC" "330"
        sendToLog "fifo_expire_async=330 in $i"
      fi

      if [ -e "$FIFO_EXPIRE_SYNC" ]; then
        write "$FIFO_EXPIRE_SYNC" "80"
        sendToLog "fifo_expire_sync=80 in $i"
      fi

      if [ -e "$GROUP_IDLE" ]; then
        write "$GROUP_IDLE" "1"
        sendToLog "group_idle=1 in $i"
      fi

      if [ -e "$LOW_LATENCY" ]; then
        write "$LOW_LATENCY" "0"
        sendToLog "low_latency=0 in $i"
      fi

      if [ -e "$QUANTUM" ]; then
        write "$QUANTUM" "16"
        sendToLog "quantum=16 in $i"
      fi

      if [ -e "$SLICE_ASYNC" ]; then
        write "$SLICE_ASYNC" "50"
        sendToLog "slice_async=50 in $i"
      fi

      if [ -e "$SLICE_ASYNC_RQ" ]; then
        write "$SLICE_ASYNC_RQ" "2"
        sendToLog "slice_async_rq=2 in $i"
      fi

      if [ -e "$SLICE_IDLE" ]; then
        write "$SLICE_IDLE" "0"
        sendToLog "slice_idle=0 in $i"
      fi

      if [ -e "$SLICE_SYNC" ]; then
        write "$SLICE_SYNC" "60"
        sendToLog "slice_sync=60 in $i"
      fi

      if [ -e "$TARGET_LATENCY" ]; then
        write "$TARGET_LATENCY" "300"
        sendToLog "target_latency=300 in $i"
      fi

    # bfq
    elif [ "$scheduler" = "bfq" ]; then
      if [ -e "$BACK_SEEK_PENALTY" ]; then
        write "$BACK_SEEK_PENALTY" "1"
        sendToLog "back_seek_penalty=1 in $i"
      fi

      if [ -e "$FIFO_EXPIRE_ASYNC" ]; then
        write "$FIFO_EXPIRE_ASYNC" "250"
        sendToLog "fifo_expire_async=250 in $i"
      fi

      if [ -e "$FIFO_EXPIRE_SYNC" ]; then
        write "$FIFO_EXPIRE_SYNC" "120"
        sendToLog "fifo_expire_sync=120 in $i"
      fi

      if [ -e "$LOW_LATENCY" ]; then
        write "$LOW_LATENCY" "0"
        sendToLog "low_latency=0 in $i"
      fi

      if [ -e "$MAX_BUDGET" ]; then
        write "$MAX_BUDGET" "0"
        sendToLog "max_budget=0 in $i"
      fi

      if [ -e "$MAX_BUDGET_ASYNC_RQ" ]; then
        write "$MAX_BUDGET_ASYNC_RQ" "4"
        sendToLog "max_budget_async_rq=4 in $i"
      fi

      if [ -e "$SLICE_IDLE" ]; then
        write "$SLICE_IDLE" "0"
        sendToLog "slice_idle=0 in $i"
      fi

      if [ -e "$TIMEOUT_ASYNC" ]; then
        write "$TIMEOUT_ASYNC" "40"
        sendToLog "timeout_async=40 in $i"
      fi

      if [ -e "$TIMEOUT_SYNC" ]; then
        write "$TIMEOUT_SYNC" "120"
        sendToLog "timeout_sync=120 in $i"
      fi

      if [ -e "$WR_COEOFF" ]; then
        write "$WR_COEOFF" "20"
        sendToLog "wr_coeff=20 in $i"
      fi

      if [ -e "$WR_MAX_SOFTRT_RATE" ]; then
        write "$WR_MAX_SOFTRT_RATE" "7000"
        sendToLog "wr_max_softrt_rate=7000 in $i"
      fi

      if [ -e "$WR_MAX_TIME" ]; then
        write "$WR_MAX_TIME" "2250"
        sendToLog "wr_max_time=2250 in $i"
      fi

      if [ -e "$WR_MIN_IDLE_TIME" ]; then
        write "$WR_MIN_IDLE_TIME" "2000"
        sendToLog "wr_min_idle_time=2000 in $i"
      fi

      if [ -e "$WR_MIN_INTER_ARR_ASYNC" ]; then
        write "$WR_MIN_INTER_ARR_ASYNC" "500"
        sendToLog "wr_min_inter_arr_async=500 in $i"
      fi

      if [ -e "$WR_RT_MAX_TIME" ]; then
        write "$WR_RT_MAX_TIME" "300"
        sendToLog "wr_rt_max_time=300 in $i"
      fi

    # row
    elif [ "$scheduler" = "row" ]; then
      if [ -e "$HP_READ_QUANTUM" ]; then
        write "$HP_READ_QUANTUM" "90"
        sendToLog "hp_read_quantum=90 in $i"
      fi

      if [ -e "$HP_SWRITE_QUANTUM" ]; then
        write "$HP_SWRITE_QUANTUM" "5"
        sendToLog "hp_swrite_quantum=5 in $i"
      fi

      if [ -e "$LOW_STARV_LIMIT" ]; then
        write "$LOW_STARV_LIMIT" "10000"
        sendToLog "low_starv_limit=10000 in $i"
      fi

      if [ -e "$LP_READ_QUANTUM" ]; then
        write "$LP_READ_QUANTUM" "3"
        sendToLog "lp_read_quantum=3 in $i"
      fi

      if [ -e "$LP_SWRITE_QUANTUM" ]; then
        write "$LP_SWRITE_QUANTUM" "10"
        sendToLog "lp_swrite_quantum=10 in $i"
      fi

      if [ -e "$RD_IDLE_DATA" ]; then
        write "$RD_IDLE_DATA" "10"
        sendToLog "rd_idle_data=10 in $i"
      fi

      if [ -e "$RD_IDLE_DATA_FREQ" ]; then
        write "$RD_IDLE_DATA_FREQ" "25"
        sendToLog "rd_idle_data_freq=25 in $i"
      fi

      if [ -e "$READ_IDLE" ]; then
        write "$READ_IDLE" "10"
        sendToLog "read_idle=10 in $i"
      fi

      if [ -e "$READ_IDLE_FREQ" ]; then
        write "$READ_IDLE_FREQ" "25"
        sendToLog "read_idle_freq=25 in $i"
      fi

      if [ -e "$REG_STARV_LIMIT" ]; then
        write "$REG_STARV_LIMIT" "5000"
        sendToLog "reg_starv_limit=5000 in $i"
      fi

      if [ -e "$RP_READ_QUANTUM" ]; then
        write "$RP_READ_QUANTUM" "75"
        sendToLog "rp_read_quantum=75 in $i"
      fi

      if [ -e "$RP_SWRITE_QUANTUM" ]; then
        write "$RP_SWRITE_QUANTUM" "4"
        sendToLog "rp_swrite_quantum=4 in $i"
      fi

      if [ -e "$RP_WRITE_QUANTUM" ]; then
        write "$RP_WRITE_QUANTUM" "4"
        sendToLog "rp_write_quantum=4 in $i"
      fi

    # fiops
    elif [ "$scheduler" = "fiops" ]; then
      if [ -e "$ASYNC_SCALE" ]; then
        write "$ASYNC_SCALE" "5"
        sendToLog "async_scale=5 in $i"
      fi

      if [ -e "$READ_SCALE" ]; then
        write "$READ_SCALE" "3"
        sendToLog "read_scale=3 in $i"
      fi

      if [ -e "$SYNC_SCALE" ]; then
        write "$SYNC_SCALE" "2"
        sendToLog "sync_scale=2 in $i"
      fi

      if [ -e "$WRITE_SCALE" ]; then
        write "$WRITE_SCALE" "4"
        sendToLog "write_scale=4 in $i"
      fi

    #  sio/sioplus
    elif [ "$scheduler" = "sio" ] || [ "$scheduler" = "sioplus" ]; then
      if [ -e "$ASYNC_READ_EXPIRE" ]; then
        write "$ASYNC_READ_EXPIRE" "500"
        sendToLog "async_read_expire=500 in $i"
      fi

      if [ -e "$ASYNC_WRITE_EXPIRE" ]; then
        write "$ASYNC_WRITE_EXPIRE" "1500"
        sendToLog "async_write_expire=1500 in $i"
      fi

      if [ -e "$FIFO_BATCH" ]; then
        write "$FIFO_BATCH" "3"
        sendToLog "fifo_batch=3 in $i"
      fi

      if [ -e "$SYNC_READ_EXPIRE" ]; then
        write "$SYNC_READ_EXPIRE" "250"
        sendToLog "sync_read_expire=250 in $i"
      fi

      if [ -e "$SYNC_WRITE_EXPIRE" ]; then
        write "$SYNC_WRITE_EXPIRE" "1250"
        sendToLog "sync_write_expire=1250 in $i"
      fi

      if [ -e "$WRITES_STARVED" ]; then
        write "$WRITES_STARVED" "1"
        sendToLog "writes_starved=1 in $i"
      fi

    # zen
    elif [ "$scheduler" = "zen" ]; then
      if [ -e "$ASYNC_EXPIRE" ]; then
        write "$ASYNC_EXPIRE" "2500"
        sendToLog "async_expire=2500 in $i"
      fi

      if [ -e "$FIFO_BATCH" ]; then
        write "$FIFO_BATCH" "8"
        sendToLog "fifo_batch=8 in $i"
      fi

      if [ -e "$SYNC_EXPIRE" ]; then
        write "$SYNC_EXPIRE" "300"
        sendToLog "sync_expire=300 in $i"
      fi

    else
      if [ "$scheduler" != "none" ]; then
        sendToLog "Scheduler $scheduler in $i is not supported"
      fi
    fi

  done

  sendToLog "Activating of I/O blocks optimization is successful"
  sendToLog "$divider"
}

ioStats() {
  if [ "$1" = "0" ]; then
    blocks="/sys/block/*"
    for i in $blocks; do

      if [ -e "$i/queue/iostats" ]; then
        write "$i/queue/iostats" "1"
        sendToLog "iostats=1 in $i"
      fi

    done
  elif [ "$1" = "1" ]; then
    blocks="/sys/block/*"
    for i in $blocks; do

      if [ -e "$i/queue/iostats" ]; then
        write "$i/queue/iostats" "0"
        sendToLog "iostats=0 in $i"
      fi

    done
  fi
}

gpuOptimizer() {
  if [ "$1" = "1" ]; then
    profile="power saving"
  elif [ "$1" = "2" ]; then
    profile="balanced"
  elif [ "$1" = "3" ]; then
    profile="performance"
  fi

  sendToLog "Applying $profile GPU optimization..."

  # GPU related tweaks
  if [ -d "/sys/class/kgsl/kgsl-3d0" ]; then
    gpu="/sys/class/kgsl/kgsl-3d0"
  elif [ -d "/sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0" ]; then
    gpu="/sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0"
  elif [ -d "/sys/devices/soc/*.qcom,kgsl-3d0/kgsl/kgsl-3d0" ]; then
    gpu="/sys/devices/soc/*.qcom,kgsl-3d0/kgsl/kgsl-3d0"
  elif [ -d "/sys/devices/soc.0/*.qcom,kgsl-3d0/kgsl/kgsl-3d0" ]; then
    gpu="/sys/devices/soc.0/*.qcom,kgsl-3d0/kgsl/kgsl-3d0"
  elif [ -d "/sys/devices/platform/*.gpu/devfreq/*.gpu" ]; then
    gpu="/sys/devices/platform/*.gpu/devfreq/*.gpu"
  elif [ -d "/sys/devices/platform/gpusysfs" ]; then
    gpu="/sys/devices/platform/gpusysfs"
  elif [ -d "/sys/devices/*.mali" ]; then
    gpu="/sys/devices/*.mali"
  elif [ -d "/sys/devices/*.gpu" ]; then
    gpu="/sys/devices/*.gpu"
  elif [ -d "/sys/devices/platform/mali.0" ]; then
    gpu="/sys/devices/platform/mali.0"
  elif [ -d "/sys/devices/platform/mali-*.0" ]; then
    gpu="/sys/devices/platform/mali-*.0"
  elif [ -d "/sys/module/mali/parameters" ]; then
    gpu="/sys/module/mali/parameters"
  elif [ -d "/sys/class/misc/mali0" ]; then
    gpu="/sys/class/misc/mali0"
  elif [ -d "/sys/kernel/gpu" ]; then
    gpu="/sys/kernel/gpu"
  fi

  if [ "$memTotal" -lt 3072 ]; then
    resetprop ro.hwui.texture_cache_size $((memTotal * 10 / 100 / 2))
    resetprop ro.hwui.layer_cache_size $((memTotal * 5 / 100 / 2))
    resetprop ro.hwui.path_cache_size $((memTotal * 2 / 100 / 2))
    resetprop ro.hwui.r_buffer_cache_size $((memTotal / 100 / 2))
    resetprop ro.hwui.drop_shadow_cache_size $((memTotal / 100 / 2))
    resetprop ro.hwui.texture_cache_flushrate 0.3
  else
    resetprop ro.hwui.texture_cache_size $((memTotal * 10 / 100))
    resetprop ro.hwui.layer_cache_size $((memTotal * 5 / 100))
    resetprop ro.hwui.path_cache_size $((memTotal * 2 / 100))
    resetprop ro.hwui.r_buffer_cache_size $((memTotal / 100))
    resetprop ro.hwui.drop_shadow_cache_size $((memTotal / 100))
    resetprop ro.hwui.texture_cache_flushrate 0.3
  fi
  sendToLog "Optimized GPU caches"
  #dumpsys SurfaceFlinger --dispsync

  if [ -e /proc/gpufreq/gpufreq_limited_thermal_ignore ]; then
    if [ "$1" = "1" ]; then
      write /proc/gpufreq/gpufreq_limited_thermal_ignore "0"
      sendToLog "Enabled gpufreq thermal"

    elif [ "$1" = "2" ]; then
      write /proc/gpufreq/gpufreq_limited_thermal_ignore "1"
      sendToLog "Disabled gpufreq thermal"

    elif [ "$1" = "3" ]; then
      write /proc/gpufreq/gpufreq_limited_thermal_ignore "1"
      sendToLog "Disabled gpufreq thermal"
    fi
  fi

  # Dynamic voltage frequency scheduler for gpu on
  if [ -e /proc/mali/dvfs_enable ]; then
    write /proc/mali/dvfs_enable "1"
    sendToLog "dvfs enabled"
  fi

  if [ -e /sys/module/pvrsrvkm/parameters/gpu_dvfs_enable ]; then
    write /sys/module/pvrsrvkm/parameters/gpu_dvfs_enable "1"
    sendToLog "dvfs enabled"
  fi

  if [ -e /sys/module/simple_gpu_algorithm/parameters/simple_gpu_activate ]; then
    write /sys/module/simple_gpu_algorithm/parameters/simple_gpu_activate "1"
    sendToLog "Simple GPU algorithm enabled"
  fi

  # Adreno idler
  if [ -e /sys/module/adreno_idler/parameters/adreno_idler_active ]; then
    write /sys/module/adreno_idler/parameters/adreno_idler_active "Y"

    if [ "$1" = "1" ]; then
      write /sys/module/adreno_idler/parameters/adreno_idler_idleworkload "10000"
      write /sys/module/adreno_idler/parameters/adreno_idler_downdifferential "35"
      write /sys/module/adreno_idler/parameters/adreno_idler_idlewait "25"

    elif [ "$1" = "2" ]; then
      write /sys/module/adreno_idler/parameters/adreno_idler_idleworkload "6000"
      write /sys/module/adreno_idler/parameters/adreno_idler_downdifferential "15"
      write /sys/module/adreno_idler/parameters/adreno_idler_idlewait "25"

    elif [ "$1" = "3" ]; then
      write /sys/module/adreno_idler/parameters/adreno_idler_idleworkload "5000"
      write /sys/module/adreno_idler/parameters/adreno_idler_downdifferential "15"
      write /sys/module/adreno_idler/parameters/adreno_idler_idlewait "15"
    fi
    sendToLog "Enabled and tweaked adreno idler"
  fi

  # Adreno boost 0 for off , 1 for low , 2 for medium , 3 for high
  if [ -e $gpu/devfreq/adrenoboost ]; then
    if [ "$1" = "1" ]; then
      write $gpu/devfreq/adrenoboost "0"
      sendToLog "Adreno boost is set to 0"
    elif [ "$1" = "2" ]; then
      write $gpu/devfreq/adrenoboost "1"
      sendToLog "Adreno boost is set to 1"
    elif [ "$1" = "3" ]; then
      write $gpu/devfreq/adrenoboost "2"
      sendToLog "Adreno boost is set to 2"
    fi
  fi

  # GPU freq throttling
  if [ -e $gpu/throttling ]; then
    if [ "$1" = "1" ]; then
      write $gpu/throttling "1"
      sendToLog "GPU throttling enabled"
    elif [ "$1" = "2" ]; then
      write $gpu/throttling "1"
      sendToLog "GPU throttling enabled"
    elif [ "$1" = "3" ]; then
      write $gpu/throttling "0"
      sendToLog "GPU throttling disabled"
    fi
  fi

  # GPU idle timer, the time after the GPU going idle
  if [ -e $gpu/idle_time ]; then
    if [ "$1" = "1" ]; then
      write $gpu/idle_time "50"
      sendToLog "Setting GPU idle timer to 50"
    elif [ "$1" = "2" ]; then
      write $gpu/idle_time "200"
      sendToLog "Setting GPU idle timer to 200"
    elif [ "$1" = "3" ]; then
      write $gpu/idle_time "1000"
      sendToLog "Setting GPU idle timer to 1000"
    fi
  fi

  # Setting up the force GPU clock, this will keep clocks on until the idle timeout forces the power rail off
  if [ -e $gpu/force_clk_on ]; then
    if [ "$1" = "1" ]; then
      write $gpu/force_clk_on "0"
      sendToLog "Force clock disabled"
    elif [ "$1" = "2" ]; then
      write $gpu/force_clk_on "0"
      sendToLog "Force clock disabled"
    elif [ "$1" = "3" ]; then
      write $gpu/force_clk_on "1"
      sendToLog "Force clock enabled"
    fi
  fi

  # Keep the graphics power rail on permanently.
  # Enabling this can cause a pretty big drainage because the rail(power) is always on, so it'll be just on performance for now!
  if [ -e $gpu/force_rail_on ]; then
    if [ "$1" = "1" ]; then
      write $gpu/force_rail_on "0"
      sendToLog "force_rail_on disabled"
    elif [ "$1" = "2" ]; then
      write $gpu/force_rail_on "0"
      sendToLog "force_rail_on disabled"
    elif [ "$1" = "3" ]; then
      write $gpu/force_rail_on "1"
      sendToLog "force_rail_on enabled"
    fi
  fi

  if [ -e $gpu/force_no_nap ]; then
    write $gpu/force_no_nap "0"
    sendToLog "force_no_nap disabled"
  fi

  if [ -e $gpu/bus_split ]; then
    if [ "$1" = "1" ]; then
      write $gpu/bus_split "1"
      sendToLog "bus_split enabled"
    elif [ "$1" = "2" ]; then
      write $gpu/bus_split "1"
      sendToLog "bus_split enabled"
    elif [ "$1" = "3" ]; then
      write $gpu/bus_split "0"
      sendToLog "bus_split disabled"
    fi
  fi

  # Keep the bus vote on permanently, whatever that means I found it in some Qualcomm references
  # They mention that for full GPU performance it should be turned On. No side-effects
  if [ -e $gpu/force_bus_on ]; then
    if [ "$1" = "1" ]; then
      write $gpu/force_bus_on "0"
      sendToLog "force_bus_on disabled"
    elif [ "$1" = "2" ]; then
      write $gpu/force_bus_on "0"
      sendToLog "force_bus_on disabled"
    elif [ "$1" = "3" ]; then
      write $gpu/force_bus_on "1"
      sendToLog "force_bus_on enabled"
    fi
  fi

  sendToLog "GPU optimization has successfully applied $profile profile"
  sendToLog "$divider"
}

optimizeBuffers() {
  sendToLog "Changing GPU buffer count"

  setprop debug.egl.buffcount 4

  sendToLog "GPU buffer count set to 4"
  sendToLog "$divider"
}

renderOpenglesUsingGpu() {
  sendToLog "Setting GPU to render OpenGLES..."

  setprop debug.egl.hw 1

  sendToLog "GPU successfully set up to render OpenGLES"
  sendToLog "$divider"
}

useOpenglSkia() {
  sendToLog "Changing app rendering to skiagl..."

  setprop debug.hwui.renderer skiagl

  sendToLog "Rendering chaned to skiagl"
  sendToLog "$divider"
}

forceGpuRendering() {
  if [ "$1" -eq 0 ]; then
    sendToLog "Disabling force GPU rendering..."
    setprop persist.sys.ui.hw 0
    sendToLog "Force GPU rendering successfully disabled"
  elif [ "$1" -eq 1 ]; then
    sendToLog "Enabling force GPU rendering..."
    setprop persist.sys.ui.hw 1
    sendToLog "Force GPU rendering successfully enabled"
  fi

  sendToLog "$divider"
}

force4xMsaa() {
  if [ "$1" -eq 0 ]; then
    sendToLog "Disabling force 4x MSAA..."
    setprop debug.egl.force_msaa 0
    sendToLog "Force 4x MSAA successfully disabled"
  elif [ "$1" -eq 1 ]; then
    sendToLog "Enabling force 4x MSAA..."
    setprop debug.egl.force_msaa 1
    sendToLog "Force 4x MSAA successfully enabled"
  fi

  sendToLog "$divider"
}

netBuffers() {
  if [ "$1" = "1" ]; then
    profile="small"
  elif [ "$1" = "2" ]; then
    profile="big"
  fi

  sendToLog "Activating $profile net buffers..."

  if [ "$1" = "1" ]; then
    # Define TCP buffer sizes for various networks
    # ReadMin, ReadInitial, ReadMax, WriteMin, WriteInitial, WriteMax
    setprop net.tcp.buffersize.hspa 4096,32768,65536,4096,32768,65536
    setprop net.tcp.buffersize.umts 4096,32768,65536,4096,32768,65536
    setprop net.tcp.buffersize.edge 4096,32768,65536,4096,32768,65536
    setprop net.tcp.buffersize.gprs 4096,32768,65536,4096,32768,65536
    setprop net.tcp.buffersize.hsdpa 4096,32768,65536,4096,32768,65536
    setprop net.tcp.buffersize.wifi 4096,32768,65536,4096,32768,65536
    setprop net.tcp.buffersize.evdo_b 4096,32768,65536,4096,32768,65536
    setprop net.tcp.buffersize.lte 4096,32768,65536,4096,32768,65536
    setprop net.tcp.buffersize.default 4096,32768,12582912,4096,32768,12582912

  elif [ "$1" = "2" ]; then
    # Define TCP buffer sizes for various networks
    # ReadMin, ReadInitial, ReadMax, WriteMin, WriteInitial, WriteMax
    setprop net.tcp.buffersize.default 6144,87380,1048576,6144,87380,524288
    setprop net.tcp.buffersize.wifi 524288,1048576,2097152,524288,1048576,2097152
    setprop net.tcp.buffersize.umts 6144,87380,1048576,6144,87380,524288
    setprop net.tcp.buffersize.gprs 6144,87380,1048576,6144,87380,524288
    setprop net.tcp.buffersize.edge 6144,87380,524288,6144,16384,262144
    setprop net.tcp.buffersize.hspa 6144,87380,524288,6144,16384,262144
    setprop net.tcp.buffersize.lte 524288,1048576,2097152,524288,1048576,2097152
    setprop net.tcp.buffersize.hsdpa 6144,87380,1048576,6144,87380,1048576
    setprop net.tcp.buffersize.evdo_b 6144,87380,1048576,6144,87380,1048576
  fi

  sendToLog "Net buffers $profile activated"
  sendToLog "$divider"
}

rilTweaks() {
  sendToLog "Activating ril tweaks..."

  resetprop ro.ril.gprsclass 12
  sendToLog "GPRS Class changed to 12"

  resetprop ro.ril.hsdpa.category 28
  sendToLog "hsdpa category changed to 28"

  resetprop ro.ril.hsupa.category 7
  sendToLog "hsupa category changed to 7"

  sendToLog "Ril tweaks are activated"
  sendToLog "$divider"
}

netTweaks() {
  sendToLog "Applying net tweaks..."

  net=$($BUSYBOX ls -d /sys/class/net/*)
  for i in $net; do
    if [ -e "$i"/tx_queue_len ]; then
      write "$i"/tx_queue_len "1000"
      sendToLog "tx_queue_len=1000 in $i"
    fi
  done

  #for i in $(ls /sys/class/net); do
  #echo "1500" > /sys/class/net/"$i"/mtu
  #echo "mtu=1500 in $i" >> $LOG;
  #done

  echo "0" >/proc/sys/net/ipv4/conf/default/secure_redirects
  echo "0" >/proc/sys/net/ipv4/conf/default/accept_redirects
  echo "0" >/proc/sys/net/ipv4/conf/default/accept_source_route
  echo "0" >/proc/sys/net/ipv4/conf/all/secure_redirects
  echo "0" >/proc/sys/net/ipv4/conf/all/accept_redirects
  echo "0" >/proc/sys/net/ipv4/conf/all/accept_source_route
  echo "0" >/proc/sys/net/ipv4/ip_forward
  echo "0" >/proc/sys/net/ipv4/ip_dynaddr
  echo "0" >/proc/sys/net/ipv4/ip_no_pmtu_disc
  echo "0" >/proc/sys/net/ipv4/tcp_ecn
  echo "0" >/proc/sys/net/ipv4/tcp_timestamps
  echo "1" >/proc/sys/net/ipv4/tcp_tw_reuse
  echo "1" >/proc/sys/net/ipv4/tcp_fack
  echo "1" >/proc/sys/net/ipv4/tcp_sack
  echo "1" >/proc/sys/net/ipv4/tcp_dsack
  echo "1" >/proc/sys/net/ipv4/tcp_rfc1337
  echo "1" >/proc/sys/net/ipv4/tcp_tw_recycle
  echo "1" >/proc/sys/net/ipv4/tcp_window_scaling
  echo "1" >/proc/sys/net/ipv4/tcp_moderate_rcvbuf
  echo "1" >/proc/sys/net/ipv4/tcp_no_metrics_save
  echo "2" >/proc/sys/net/ipv4/tcp_synack_retries
  echo "2" >/proc/sys/net/ipv4/tcp_syn_retries
  echo "5" >/proc/sys/net/ipv4/tcp_keepalive_probes
  echo "30" >/proc/sys/net/ipv4/tcp_keepalive_intvl
  echo "30" >/proc/sys/net/ipv4/tcp_fin_timeout
  echo "1800" >/proc/sys/net/ipv4/tcp_keepalive_time
  echo "261120" >/proc/sys/net/core/rmem_max
  echo "261120" >/proc/sys/net/core/wmem_max
  echo "261120" >/proc/sys/net/core/rmem_default
  echo "261120" >/proc/sys/net/core/wmem_default

  sendToLog "Net tweaks applied"
  sendToLog "$divider"
}

disableMultitaskingLimitations() {
  sendToLog "Disabling multitasking limitations..."

  setprop MIN_HIDDEN_APPS false
  sendToLog "MIN_HIDDEN_APPS=false"

  setprop ACTIVITY_INACTIVE_RESET_TIME false
  sendToLog "ACTIVITY_INACTIVE_RESET_TIME=false"

  setprop MIN_RECENT_TASKS false
  sendToLog "MIN_RECENT_TASKS=false"

  setprop PROC_START_TIMEOUT false
  sendToLog "PROC_START_TIMEOUT=false"

  setprop CPU_MIN_CHECK_DURATION false
  sendToLog "CPU_MIN_CHECK_DURATION=false"

  setprop GC_TIMEOUT false
  sendToLog "GC_TIMEOUT=false"

  setprop SERVICE_TIMEOUT false
  sendToLog "SERVICE_TIMEOUT=false"

  setprop MIN_CRASH_INTERVAL false
  sendToLog "MIN_CRASH_INTERVAL=false"

  setprop ENFORCE_PROCESS_LIMIT false
  sendToLog "ENFORCE_PROCESS_LIMIT=false"

  sendToLog "Multitasking limitations disabled"
  sendToLog "$divider"
}

lowRamFlag() {
  if [ "$1" = "0" ]; then
    sendToLog "Disabling low RAM flag..."
    resetprop ro.config.low_ram false
    sendToLog "Low RAM flag disabled"

  elif [ "$1" = "1" ]; then
    sendToLog "Enabling low RAM flag..."
    resetprop ro.config.low_ram true
    sendToLog "Low RAM flag enabled"
  fi

  sendToLog "$divider"
}

oomKiller() {
  oom_kill_allocating_task=/proc/sys/vm/oom_kill_allocating_task

  if [ -e $oom_kill_allocating_task ]; then
    if [ "$1" = "0" ]; then
      sendToLog "Disabling OOM killer..."
      write $oom_kill_allocating_task "0"
      sendToLog "OOM killer disabled"
      sendToLog "$divider"
    elif [ "$1" = "1" ]; then
      sendToLog "Enabling OOM killer..."
      write $oom_kill_allocating_task "1"
      sendToLog "OOM killer enabled"
      sendToLog "$divider"
    fi
  fi

}

ramManagerBalanced() {

  fa=$(((memTotal * 5 / 2 / 100) * 1024 / 4))
  va=$(((memTotal * 3 / 100) * 1024 / 4))
  ss=$(((memTotal * 5 / 100) * 1024 / 4))
  ha=$(((memTotal * 7 / 100) * 1024 / 4))
  cp=$(((memTotal * 9 / 100) * 1024 / 4))
  ea=$(((memTotal * 11 / 100) * 1024 / 4))
  minFree="$fa,$va,$ss,$ha,$cp,$ea"

  # Higher values of oom_adj are more likely
  # to be killed by the kernel's oom killer.
  # The current foreground app has a oom_adj of 0
  adj="0,112,224,408,824,1000"

  # If you set this to lower than 1024KB, your system will
  # become subtly broken, and prone to deadlock under high loads, we don't allow it below 3072kb
  mfk=$((memTotal * 9 / 5))

  if [ "$mfk" -le "3072" ]; then
    mfk=3072
  fi

  # Extra free kbytes calculated based on min_free_kbytes
  efk=$((mfk * 16 / 5))

  if [ "$efk" -le 18432 ]; then
    efk=18432
  fi

  # Background app limit per ram size
  if [ "$memTotal" -le "1024" ]; then
    backgroundAppLimit="24"
  elif [ "$memTotal" -le "2048" ]; then
    backgroundAppLimit="28"
  elif [ "$memTotal" -le "3072" ]; then
    backgroundAppLimit="30"
  elif [ "$memTotal" -le "4096" ]; then
    backgroundAppLimit="36"
  else
    backgroundAppLimit="42"
  fi

  # Set 1 to reclaim resources quickly when needed.
  fastRun="0"

  oomReaper="1"
  adaptiveLmk="0"

  # How much memory of swap will be counted as free
  fudgeSwap="1024"

  sendToLog "Enabling balanced RAM manager profile"

  sync
  $BUSYBOX sysctl -w vm.drop_caches=3

  resetprop ro.sys.fw.bg_apps_limit $backgroundAppLimit
  resetprop ro.vendor.qti.sys.fw.bg_apps_limit $backgroundAppLimit
  sendToLog "Background app limit=$backgroundAppLimit"

  parameter_adj=/sys/module/lowmemorykiller/parameters/adj
  if [ -e $parameter_adj ]; then
    write $parameter_adj "$adj"
    sendToLog "adj=$adj"
  fi

  parameter_oom_reaper=/sys/module/lowmemorykiller/parameters/oom_reaper
  if [ -e $parameter_oom_reaper ]; then
    write $parameter_oom_reaper "$oomReaper"
    sendToLog "oom_reaper=$oomReaper"
  fi

  parameter_lmk_fast_run=/sys/module/lowmemorykiller/parameters/lmk_fast_run
  if [ -e $parameter_lmk_fast_run ]; then
    write $parameter_lmk_fast_run "$fastRun"
    sendToLog "lmk_fast_run=$fastRun"
  fi

  parameter_adaptive_lmk=/sys/module/lowmemorykiller/parameters/enable_adaptive_lmk
  if [ -e $parameter_adaptive_lmk ]; then
    write $parameter_adaptive_lmk "$adaptiveLmk"
    setprop lmk.autocalc false
    sendToLog "adaptive_lmk=$adaptiveLmk"
  fi

  parameter_fudge_swap=/sys/module/lowmemorykiller/parameters/fudgeswap
  if [ -e $parameter_fudge_swap ]; then
    write $parameter_fudge_swap "$fudgeSwap"
    sendToLog "fudge_swap=$fudgeSwap"
  fi

  parameter_minfree=/sys/module/lowmemorykiller/parameters/minfree
  if [ -e $parameter_minfree ]; then
    write $parameter_minfree "$minFree"
    sendToLog "minfree=$minFree"
  fi

  parameter_min_free_kbytes=/proc/sys/vm/min_free_kbytes
  if [ -e $parameter_min_free_kbytes ]; then
    write $parameter_min_free_kbytes "$mfk"
    sendToLog "min_free_kbytes=$mfk"
  fi

  parameter_extra_free_kbytes=/proc/sys/vm/extra_free_kbytes
  if [ -e $parameter_extra_free_kbytes ]; then
    write $parameter_extra_free_kbytes "$efk"
    sendToLog "extra_free_kbytes=$efk"
  fi

  sendToLog "Balanced RAM manager profile for $((memTotal))mb devices successfully applied"
  sendToLog "$divider"
}

ramManagerGaming() {

  fa=$(((memTotal * 3 / 2 / 100) * 1024 / 4))
  va=$(((memTotal * 2 / 100) * 1024 / 4))
  ss=$(((memTotal * 4 / 100) * 1024 / 4))
  ha=$(((memTotal * 7 / 100) * 1024 / 4))
  cp=$(((memTotal * 11 / 100) * 1024 / 4))
  ea=$(((memTotal * 15 / 100) * 1024 / 4))
  minFree="$fa,$va,$ss,$ha,$cp,$ea"

  # Higher values of oom_adj are more likely
  # to be killed by the kernel's oom killer.
  # The current foreground app has a oom_adj of 0
  adj="0,112,224,408,824,1000"

  # If you set this to lower than 1024KB, your system will
  # become subtly broken, and prone to deadlock under high loads, we don't allow it below 3072kb
  mfk=$((memTotal * 9 / 5))

  if [ "$mfk" -le "3072" ]; then
    mfk=3072
  fi

  # Extra free kbytes calculated based on min_free_kbytes
  efk=$((mfk * 16 / 5))

  if [ "$efk" -le 18432 ]; then
    efk=18432
  fi

  # Background app limit per ram size
  if [ "$memTotal" -le "1024" ]; then
    backgroundAppLimit="18"
  elif [ "$memTotal" -le "2048" ]; then
    backgroundAppLimit="22"
  elif [ "$memTotal" -le "3072" ]; then
    backgroundAppLimit="26"
  elif [ "$memTotal" -le "4096" ]; then
    backgroundAppLimit="30"
  else
    backgroundAppLimit="42"
  fi

  # Set 1 to reclaim resources quickly when needed.
  fastRun="1"

  oomReaper="1"
  adaptiveLmk="0"

  # How much memory of swap will be counted as free
  fudgeSwap="1024"

  sendToLog "Enabling gaming RAM manager profile"

  sync
  $BUSYBOX sysctl -w vm.drop_caches=3

  resetprop ro.sys.fw.bg_apps_limit $backgroundAppLimit
  resetprop ro.vendor.qti.sys.fw.bg_apps_limit $backgroundAppLimit
  sendToLog "Background app limit=$backgroundAppLimit"

  parameter_adj=/sys/module/lowmemorykiller/parameters/adj
  if [ -e $parameter_adj ]; then
    write $parameter_adj "$adj"
    sendToLog "adj=$adj"
  fi

  parameter_oom_reaper=/sys/module/lowmemorykiller/parameters/oom_reaper
  if [ -e $parameter_oom_reaper ]; then
    write $parameter_oom_reaper "$oomReaper"
    sendToLog "oom_reaper=$oomReaper"
  fi

  parameter_lmk_fast_run=/sys/module/lowmemorykiller/parameters/lmk_fast_run
  if [ -e $parameter_lmk_fast_run ]; then
    write $parameter_lmk_fast_run "$fastRun"
    sendToLog "lmk_fast_run=$fastRun"
  fi

  parameter_adaptive_lmk=/sys/module/lowmemorykiller/parameters/enable_adaptive_lmk
  if [ -e $parameter_adaptive_lmk ]; then
    write $parameter_adaptive_lmk "$adaptiveLmk"
    setprop lmk.autocalc false
    sendToLog "adaptive_lmk=$adaptiveLmk"
  fi

  parameter_fudge_swap=/sys/module/lowmemorykiller/parameters/fudgeswap
  if [ -e $parameter_fudge_swap ]; then
    write $parameter_fudge_swap "$fudgeSwap"
    sendToLog "fudge_swap=$fudgeSwap"
  fi

  parameter_minfree=/sys/module/lowmemorykiller/parameters/minfree
  if [ -e $parameter_minfree ]; then
    write $parameter_minfree "$minFree"
    sendToLog "minfree=$minFree"
  fi

  parameter_min_free_kbytes=/proc/sys/vm/min_free_kbytes
  if [ -e $parameter_min_free_kbytes ]; then
    write $parameter_min_free_kbytes "$mfk"
    sendToLog "min_free_kbytes=$mfk"
  fi

  parameter_extra_free_kbytes=/proc/sys/vm/extra_free_kbytes
  if [ -e $parameter_extra_free_kbytes ]; then
    write $parameter_extra_free_kbytes "$efk"
    sendToLog "extra_free_kbytes=$efk"
  fi

  sendToLog "Gaming RAM manager profile for $((memTotal))mb devices successfully applied"
  sendToLog "$divider"
}

ramManagerMultitasking() {

  fa=$(((memTotal * 2 / 100) * 1024 / 4))
  va=$(((memTotal * 3 / 100) * 1024 / 4))
  ss=$(((memTotal * 4 / 100) * 1024 / 4))
  ha=$(((memTotal * 6 / 100) * 1024 / 4))
  cp=$(((memTotal * 9 / 100) * 1024 / 4))
  ea=$(((memTotal * 12 / 100) * 1024 / 4))
  minFree="$fa,$va,$ss,$ha,$cp,$ea"

  # Higher values of oom_adj are more likely
  # to be killed by the kernel's oom killer.
  # The current foreground app has a oom_adj of 0
  adj="0,112,224,408,824,1000"

  # If you set this to lower than 1024KB, your system will
  # become subtly broken, and prone to deadlock under high loads, we don't allow it below 3072kb
  mfk=$((memTotal * 9 / 5))

  if [ "$mfk" -le "3072" ]; then
    mfk=3072
  fi

  # Extra free kbytes calculated based on min_free_kbytes
  efk=$((mfk * 16 / 5))

  if [ "$efk" -le 18432 ]; then
    efk=18432
  fi

  # Background app limit per ram size
  if [ "$memTotal" -le "1024" ]; then
    backgroundAppLimit="25"
  elif [ "$memTotal" -le "2048" ]; then
    backgroundAppLimit="30"
  elif [ "$memTotal" -le "3072" ]; then
    backgroundAppLimit="36"
  elif [ "$memTotal" -le "4096" ]; then
    backgroundAppLimit="42"
  else
    backgroundAppLimit="44"
  fi

  # Set 1 to reclaim resources quickly when needed.
  fastRun="0"

  oomReaper="1"
  adaptiveLmk="0"

  # How much memory of swap will be counted as free
  fudgeSwap="1024"

  sendToLog "Enabling multitasking RAM manager profile"

  sync
  $BUSYBOX sysctl -w vm.drop_caches=3

  resetprop ro.sys.fw.bg_apps_limit $backgroundAppLimit
  resetprop ro.vendor.qti.sys.fw.bg_apps_limit $backgroundAppLimit
  sendToLog "Background app limit=$backgroundAppLimit"

  parameter_adj=/sys/module/lowmemorykiller/parameters/adj
  if [ -e $parameter_adj ]; then
    write $parameter_adj "$adj"
    sendToLog "adj=$adj"
  fi

  parameter_oom_reaper=/sys/module/lowmemorykiller/parameters/oom_reaper
  if [ -e $parameter_oom_reaper ]; then
    write $parameter_oom_reaper "$oomReaper"
    sendToLog "oom_reaper=$oomReaper"
  fi

  parameter_lmk_fast_run=/sys/module/lowmemorykiller/parameters/lmk_fast_run
  if [ -e $parameter_lmk_fast_run ]; then
    write $parameter_lmk_fast_run "$fastRun"
    sendToLog "lmk_fast_run=$fastRun"
  fi

  parameter_adaptive_lmk=/sys/module/lowmemorykiller/parameters/enable_adaptive_lmk
  if [ -e $parameter_adaptive_lmk ]; then
    write $parameter_adaptive_lmk "$adaptiveLmk"
    setprop lmk.autocalc false
    sendToLog "adaptive_lmk=$adaptiveLmk"
  fi

  parameter_fudge_swap=/sys/module/lowmemorykiller/parameters/fudgeswap
  if [ -e $parameter_fudge_swap ]; then
    write $parameter_fudge_swap "$fudgeSwap"
    sendToLog "fudge_swap=$fudgeSwap"
  fi

  parameter_minfree=/sys/module/lowmemorykiller/parameters/minfree
  if [ -e $parameter_minfree ]; then
    write $parameter_minfree "$minFree"
    sendToLog "minfree=$minFree"
  fi

  parameter_min_free_kbytes=/proc/sys/vm/min_free_kbytes
  if [ -e $parameter_min_free_kbytes ]; then
    write $parameter_min_free_kbytes "$mfk"
    sendToLog "min_free_kbytes=$mfk"
  fi

  parameter_extra_free_kbytes=/proc/sys/vm/extra_free_kbytes
  if [ -e $parameter_extra_free_kbytes ]; then
    write $parameter_extra_free_kbytes "$efk"
    sendToLog "extra_free_kbytes=$efk"
  fi

  sendToLog "Multitasking RAM manager profile for $((memTotal))mb devices successfully applied"
  sendToLog "$divider"
}

virtualMemoryTweaks() {
  if [ "$1" = "1" ]; then
    profile="battery"
  elif [ "$1" = "2" ]; then
    profile="balanced"
  elif [ "$1" = "3" ]; then
    profile="performance"
  fi

  sendToLog "Activating $profile virtual memory tweaks..."

  sync

  leases_enable=/proc/sys/fs/leases-enable
  if [ -e $leases_enable ]; then
    write $leases_enable "1"
    sendToLog "leases_enable=1"
  fi

  # This file specifies the grace period (in seconds) that the kernel grants
  # to a process holding a file lease after it has sent a signal to that process
  # notifying it that another process is waiting to open the file.
  # If the lease holder does not remove or downgrade the lease within this grace period,
  # the kernel forcibly breaks the lease.

  lease_break_time=/proc/sys/fs/lease-break-time
  if [ -e $lease_break_time ]; then
    write $lease_break_time "20"
    sendToLog "lease_break_time=20"
  fi

  # dnotify is a signal used to notify a process about file/directory changes.
  dir_notify_enable=/proc/sys/fs/dir-notify-enable
  if [ -e $dir_notify_enable ]; then
    write $dir_notify_enable "0"
    sendToLog "dir_notify_enable=0"
  fi

  sendToLog "File system parameters are updated"

  enable_process_reclaim=/sys/module/process_reclaim/parameters/enable_process_reclaim
  if [ -e $enable_process_reclaim ]; then
    write $enable_process_reclaim "0"
    sendToLog "Reclaiming pages of inactive tasks disabled"
  fi

  # This parameter tells how much of physical RAM to take when swap is full
  overcommit_ratio=/proc/sys/vm/overcommit_ratio
  if [ -e overcommit_ratio ]; then
    write $overcommit_ratio "0"
    sendToLog "overcommit_ratio=0"
  fi

  oom_dump_tasks=/proc/sys/vm/oom_dump_tasks
  if [ -e $oom_dump_tasks ]; then
    write $oom_dump_tasks "0"
    sendToLog "OOM dump tasks are disabled"
  fi

  vfs_cache_pressure=/proc/sys/vm/vfs_cache_pressure
  if [ -e $vfs_cache_pressure ]; then
    if [ "$1" = "1" ]; then
      write $vfs_cache_pressure "20"
      sendToLog "vfs_cache_pressure=20"

    elif [ "$1" = "2" ]; then
      write $vfs_cache_pressure "75"
      sendToLog "vfs_cache_pressure=75"

    elif [ "$1" = "3" ]; then
      write $vfs_cache_pressure "200"
      sendToLog "vfs_cache_pressure=200"
    fi
  fi

  laptop_mode=/proc/sys/vm/laptop_mode
  if [ -e $laptop_mode ]; then
    write $laptop_mode "0"
    sendToLog "laptop_mode=0"
  fi

  swappiness=/proc/sys/vm/swappiness
  if [ -e $swappiness ]; then
    write $swappiness "100"
    sendToLog "swappiness=100"
  fi

  # page-cluster controls the number of pages up to which consecutive pages
  # are read in from swap in a single attempt. This is the swap counterpart
  # to page cache readahead.
  # The mentioned consecutivity is not in terms of virtual/physical addresses,
  # but consecutive on swap space - that means they were swapped out together.
  # It is a logarithmic value - setting it to zero means "1 page", setting
  # it to 1 means "2 pages", setting it to 2 means "4 pages", etc.
  # Zero disables swap readahead completely.
  # The default value is three (eight pages at a time).  There may be some
  # small benefits in tuning this to a different value if your workload is
  # swap-intensive.
  # Lower values mean lower latencies for initial faults, but at the same time
  # extra faults and I/O delays for following faults if they would have been part of
  # that consecutive pages readahead would have brought in.
  page_cluster=/proc/sys/vm/page-cluster
  if [ -e $page_cluster ]; then
    write $page_cluster "0"
    sendToLog "page_cluster=0"
  fi

  # vm.dirty_expire_centisecs is how long something can be in cache
  # before it needs to be written.
  # When the pdflush/flush/kdmflush processes kick in they will
  # check to see how old a dirty page is, and if it’s older than this value it’ll
  # be written asynchronously to disk. Since holding a dirty page in memory is
  # unsafe this is also a safeguard against data loss.
  dirty_expire_centisecs=/proc/sys/vm/dirty_expire_centisecs
  if [ -e $dirty_expire_centisecs ]; then
    if [ "$1" = "1" ]; then
      write $dirty_expire_centisecs "2000"
      sendToLog "dirty_expire_centisecs=2000"

    elif [ "$1" = "2" ]; then
      write $dirty_expire_centisecs "1000"
      sendToLog "dirty_expire_centisecs=1000"

    elif [ "$1" = "3" ]; then
      write $dirty_expire_centisecs "500"
      sendToLog "dirty_expire_centisecs=500"
    fi
  fi

  # vm.dirty_writeback_centisecs is how often the pdflush/flush/kdmflush processes wake up
  # and check to see if work needs to be done.
  dirty_writeback_centisecs=/proc/sys/vm/dirty_writeback_centisecs
  if [ -e $dirty_writeback_centisecs ]; then
    if [ "$1" = "1" ]; then
      write $dirty_writeback_centisecs "5000"
      sendToLog "dirty_writeback_centisecs=5000"

    elif [ "$1" = "2" ]; then
      write $dirty_writeback_centisecs "3000"
      sendToLog "dirty_writeback_centisecs=3000"

    elif [ "$1" = "3" ]; then
      write $dirty_writeback_centisecs "1000"
      sendToLog "dirty_writeback_centisecs=1000"
    fi
  fi

  # vm.dirty_background_ratio is the percentage of system memory(RAM)
  # that can be filled with “dirty” pages — memory pages that
  # still need to be written to disk — before the pdflush/flush/kdmflush
  # background processes kick in to write it to disk.
  # It can be 50% or less of dirtyRatio
  # If ( dirty_background_ratio >= dirty_ratio ) {
  # dirty_background_ratio = dirty_ratio / 2 (or 4)
  dirty_background_ratio=/proc/sys/vm/dirty_background_ratio
  if [ -e $dirty_background_ratio ]; then
    if [ "$1" = "1" ]; then
      write $dirty_background_ratio "10"
      sendToLog "dirty_background_ratio=10"
    elif [ "$1" = "2" ]; then
      write $dirty_background_ratio "10"
      sendToLog "dirty_background_ratio=10"
    elif [ "$1" = "3" ]; then
      write $dirty_background_ratio "5"
      sendToLog "dirty_background_ratio=5"
    fi
  fi

  # vm.dirty_ratio is the absolute maximum amount of system memory
  # that can be filled with dirty pages before everything must get committed to disk.
  # When the system gets to this point all new I/O blocks until dirty pages
  # have been written to disk. This is often the source of long I/O pauses,
  # but is a safeguard against too much data being cached unsafely in memory.
  dirty_ratio=/proc/sys/vm/dirty_ratio
  if [ -e $dirty_ratio ]; then
    if [ "$1" = "1" ]; then
      write $dirty_ratio "50"
      sendToLog "dirty_ratio=50"

    elif [ "$1" = "2" ]; then
      write $dirty_ratio "40"
      sendToLog "dirty_ratio=40"

    elif [ "$1" = "3" ]; then
      write $dirty_ratio "10"
      sendToLog "dirty_ratio=10"
    fi
  fi

  sendToLog "Virtual memory tweaks successfully applied $profile profile"
  sendToLog "$divider"
}

heapOptimization() {
  heapSize=$((memTotal * 3 / 16))

  # Don't use more than 512mb
  if [ "$heapSize" -gt "512" ]; then
    heapSize=512
  fi

  heapGrowthLimit=$((heapSize * 5 / 11))

  sendToLog "Activating heap optimization"

  # The ideal ratio of live to free memory. It's good to have a value between 0.2 and 0.9.
  # This limit the managed hepSize to heapsize*heaptargetutilization so it won't be full every time
  setprop dalvik.vm.heaptargetutilization 0.80
  sendToLog "heapTargetUtilization=0.80"

  # This is the heap size that Dalvik/ART assigns to every new ‘large’ App.
  # Large Apps are the ones that include the ‘android:largeHeap’ option in their manifest.
  # Note that many apps abuse this option, in an effort to increase their performance.
  setprop dalvik.vm.heapsize "$((heapSize))m"
  sendToLog "heapSize=$((heapSize))m"

  # This is the heap size that is assigned to standard Apps.
  # This should typically be no more than half the dalvik.vm.heapsize value.
  setprop dalvik.vm.heapgrowthlimit "$((heapGrowthLimit))m"
  sendToLog "heapgrowthlimit=$((heapGrowthLimit))m"

  # Forces the free memory to never be larger than the given value.
  setprop dalvik.vm.heapmaxfree 8m
  sendToLog "heapmaxfree=8m"

  # Forces the free memory to never be smaller than the given value.
  setprop dalvik.vm.heapminfree 2m
  sendToLog "heapminfree=2m"

  sendToLog "Heap optimization for $((memTotal))mb device activated"
  sendToLog "$divider"
}

# Get device info when starting the module.
# this will be done only on boot or executed service with sh over terminal
if [ "$#" -eq 0 ] || [ ! -e "$LOG" ] || [ ! -s "$LOG" ]; then
  loggingHeader
fi

# Check number of arguments and perform task based on it.
if [ "$#" -eq 3 ]; then
  $BUSYBOX sleep 0.5
  "$2" "$3"

  exit 0
elif [ "$#" -eq 2 ]; then
  $BUSYBOX sleep 0.5
  "$2"

  exit 0
else

  # Time in seconds when starting with profile applying
  # This will be later used for the time difference
  start=$($BUSYBOX date +%s)

  miscTweaks
  entropy
  ioOptimization
  netTweaks

  if [ "$($BUSYBOX cat "$DISABLE_DEBUGGING")" -eq 1 ]; then
    disableDebugging
  fi

  if [ "$($BUSYBOX cat "$IO_STATS")" -eq 0 ]; then
    ioStats 0
  elif [ "$($BUSYBOX cat "$IO_STATS")" -eq 1 ]; then
    ioStats 1
  fi

  if [ "$($BUSYBOX cat "$CPU_OPTIMIZER")" -eq 0 ]; then
    cpuOptimization 0
  elif [ "$($BUSYBOX cat "$CPU_OPTIMIZER")" -eq 1 ]; then
    cpuOptimization 1
  elif [ "$($BUSYBOX cat "$CPU_OPTIMIZER")" -eq 2 ]; then
    cpuOptimization 2
  elif [ "$($BUSYBOX cat "$CPU_OPTIMIZER")" -eq 3 ]; then
    cpuOptimization 3
  fi

  if [ "$($BUSYBOX cat "$GPU_OPTIMIZER")" -eq 1 ]; then
    gpuOptimizer 1
  elif [ "$($BUSYBOX cat "$GPU_OPTIMIZER")" -eq 2 ]; then
    gpuOptimizer 2
  elif [ "$($BUSYBOX cat "$GPU_OPTIMIZER")" -eq 3 ]; then
    gpuOptimizer 3
  fi

  if [ "$($BUSYBOX cat "$OPTIMIZE_BUFFERS")" -eq 1 ]; then
    optimizeBuffers
  fi

  if [ "$($BUSYBOX cat "$RENDER_OPENGLES_USING_GPU")" -eq 1 ]; then
    renderOpenglesUsingGpu
  fi

  if [ "$($BUSYBOX cat "$USE_OPENGL_SKIA")" -eq 1 ]; then
    useOpenglSkia
  fi

  if [ "$($BUSYBOX cat "$FORCE_GPU_RENDERING")" -eq 0 ]; then
    forceGpuRendering 0
  elif [ "$($BUSYBOX cat "$FORCE_GPU_RENDERING")" -eq 1 ]; then
    forceGpuRendering 1
  fi

  if [ "$($BUSYBOX cat "$FORCE_4XMSAA")" -eq 0 ]; then
    force4xMsaa 0
  elif [ "$($BUSYBOX cat "$FORCE_4XMSAA")" -eq 1 ]; then
    force4xMsaa 1
  fi

  if [ "$($BUSYBOX cat "$NET_BUFFERS")" -eq 1 ]; then
    netBuffers 1
  elif [ "$($BUSYBOX cat "$NET_BUFFERS")" -eq 2 ]; then
    netBuffers 2
  fi

  if [ "$($BUSYBOX cat "$RIL_TWEAKS")" -eq 1 ]; then
    rilTweaks
  fi

  if [ "$($BUSYBOX cat "$RAM_MANAGER")" -eq 1 ]; then
    ramManagerMultitasking
  elif [ "$($BUSYBOX cat "$RAM_MANAGER")" -eq 2 ]; then
    ramManagerBalanced
  elif [ "$($BUSYBOX cat "$RAM_MANAGER")" -eq 3 ]; then
    ramManagerGaming
  fi

  if [ "$($BUSYBOX cat "$DISABLE_MULTITASKING_LIMITATIONS")" -eq 1 ]; then
    disableMultitaskingLimitations
  fi

  if [ "$($BUSYBOX cat "$LOW_RAM_FLAG")" -eq 0 ]; then
    lowRamFlag 0
  elif [ "$($BUSYBOX cat "$LOW_RAM_FLAG")" -eq 1 ]; then
    lowRamFlag 1
  fi

  if [ "$($BUSYBOX cat "$OOM_KILLER")" -eq 0 ]; then
    oomKiller 0
  elif [ "$($BUSYBOX cat "$OOM_KILLER")" -eq 1 ]; then
    oomKiller 1
  fi

  if [ "$($BUSYBOX cat "$VIRTUAL_MEMORY_TWEAKS")" -eq 1 ]; then
    virtualMemoryTweaks 1
  elif [ "$($BUSYBOX cat "$VIRTUAL_MEMORY_TWEAKS")" -eq 2 ]; then
    virtualMemoryTweaks 2
  elif [ "$($BUSYBOX cat "$VIRTUAL_MEMORY_TWEAKS")" -eq 3 ]; then
    virtualMemoryTweaks 3
  fi

  if [ "$($BUSYBOX cat "$HEAP_OPTIMIZATION")" -eq 1 ]; then
    heapOptimization
  fi

  # End time of the script
  end=$($BUSYBOX date +%s)

  # Calculate how much took to set up L Speed parameters,
  # everything is calculated in seconds
  runtime=$((end - start))

  sendToLog "Applying took $runtime seconds"
  sendToLog "Successfully applied new parameters"
  sendToLog "$divider"

  exit 0
fi
exit 0
