cputmp=$(( $(cat /sys/class/thermal/thermal_zone0/temp)/100 ));cputmp=$(echo "$cputmp" | sed 's/./&./2') 
alias temp='echo -e "GPU: $( sudo vcgencmd measure_temp | cut -d'=' -f2)";echo -e "CPU: $(echo -e $cputmp )\x27C"'

alias volts='echo "$(vcgencmd measure_volts | cut -d= -f2)"' 

alias txt='sudo nano'
alias run='sudo bash'
alias dump='sudo tee'
alias ll='ls -la --color=always'
alias ss='sudo du -sh ./* | sort -hr'
alias wget='wget --no-check-certificate'

alias py='sudo python3'
alias autostart='sudo nano /opt/retropie/configs/all/autostart.sh'
alias retroarch='/opt/retropie/emulators/retroarch/bin/retroarch'
alias myip='hostname -I | cut -d" " -f1'
alias reload='clear && source /home/pi/.bashrc'
alias aliases='alias && cat /home/pi/.bash_aliases | grep -vi "^[#]" | grep -v aliases | grep "()" | cut -d" " -f1'
alias alias-edit='sudo nano /home/pi/.bash_aliases'
alias lsdev='ls -l --color=always /dev/ | cut -c 49- | less -R'
alias teensytest='evtest /dev/input/by-id/usb-Teensyduino_Serial_Keyboard_Mouse_Joystick_1008140-if02-event-kbd'
alias triggers='sudo nano /etc/triggerhappy/triggers.d/teensy.conf'

alias decolor.styles='sed -E "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})*)?[m,K,H,f,J]//gm"'
alias decolor.reset='sed -E "s/\x1B\([A-Z]{1}(\x1B\[[m,K,H,f,J])?//gm"'
alias decolor='decolor.styles | decolor.reset'

alias scan_coin='sudo scanmem -p `pidof retroarch` -c"option region_scan_level 3;reset"'
dump_coin() {
  sudo bash /home/pi/CAFCA/cmd/DUMP.sh "$@"
}

hex() {
printf "%02x\n" "${1}" | tr '[[:lower:]]' '[[:upper:]]'

}

config() {
  sudo bash /home/pi/ADMIN/CMD/CONFIG/CONFIG.sh "$@"
}

checkvolts() {
  STATUS=$(vcgencmd get_throttled | sed -n 's|^throttled=\(.*\)|\1|p')
  echo "$STATUS"
  if [[ ${STATUS} -ne 0 ]]; then
    echo ""
    if [ $((${STATUS} & 0x00001)) -ne 0 ]; then
      echo "Power is currently Under Voltage"
    elif [ $((${STATUS} & 0x10000)) -ne 0 ]; then
      echo "Power has previously been Under Voltage"
    fi
    if [ $((${STATUS} & 0x00002)) -ne 0 ]; then
      echo "ARM Frequency is currently Capped"
    elif [ $((${STATUS} & 0x20000)) -ne 0 ]; then
      echo "ARM Frequency has previously been Capped"
    fi
    if [ $((${STATUS} & 0x00004)) -ne 0 ]; then
      echo "CPU is currently Throttled"
    elif [ $((${STATUS} & 0x40000)) -ne 0 ]; then
      echo "CPU has previously been Throttled"
    fi
    if [ $((${STATUS} & 0x00008)) -ne 0 ]; then
      echo "Currently at Soft Temperature Limit"
    elif [ $((${STATUS} & 0x80000)) -ne 0 ]; then
      echo "Previously at Soft Temperature Limit"
    fi
    echo ""
  fi
}

joytest() {
  local arg=${1:-8}
  local del=${2:-1}
  while true; do clear && evdev-joystick --s "/dev/input/event$arg"; sleep "$del"; done
}

joy2key() {
  if [[ ${#} -gt 0 ]]; then
    local arg=$(echo "${1}" | tr '[:lower:]' '[:upper:]')
    bash /home/pi/ADMIN/CMD/joy2key/joy2key.sh "$arg"
  else
    echo -e "\nPlease provide argument!\n[ start | stop ]\n"
  fi
}

vkdump() {
  if [[ ! ${1} == help ]]; then 
    event=$(while read -r line; do
      [ "$(echo $line | grep -c Virtual)" -gt 0 ] \
      && echo "$line" | grep "Virtual Keyboard" | cut -d: -f1
    done< <(sudo timeout 1 evtest 2>&1))

    while true; do
      clear
      echo -e "Virtual Keyboard: $event\n"
      echo -e " Type your octal code now.\n i.e. \x27\\\033\x27 without apostrophes.\n"
      echo -n " > "

      read -r str

      timeout 2 evtest "$event" | grep -A100 --line-buffered Testing &

      printf "$str" > /tmp/vkbdd.fifo
      sleep 1
      printf "\n"
      echo -e "\nPress ENTER to continue."
      read -sr dummy
    done

else
  clear
  printf "\n OCTAL CODES:\n\n \
  '\\\040' : SPACE \n \
  '\\\033' : ESC \n \
  '\\\212' : F1 \n \
  '\\\216' : F5 \n \
  '\\\010' : R_ALT \n\n"
fi

}

txtf() {
  local file=
  local arg=

  declare -A txtfiles=( \
    [asoundrc]='/home/pi/.asoundrc' \
    [autostart]='/opt/retropie/configs/all/autostart.sh' \
    [boot]='/boot/boot.sh' \
    [bootlog]='/boot/boot.log' \
    [cafca]='/home/pi/CAFCA/CAFCA.sh' \
    [cafca_log]='/home/pi/CAFCA/log/CAFCA.log' \
    [cafca_states]='/home/pi/CAFCA/data/.states' \
    [cafca_settings]='/home/pi/CAFCA/data/.settings' \
    [cmdline]='/boot/cmdline.txt' \
    [config]='/boot/config.txt' \
    [emulationstation]='/opt/retropie/supplementary/emulationstation/emulationstation.sh' \
    [es-end]='/home/pi/ADMIN/CMD/ES/es-onend.sh' \
    [es-start]='/home/pi/ADMIN/CMD/ES/es-onstart.sh' \
    [es_settings]='/home/pi/.emulationstation/es_settings.cfg' \
    [es_systems]='/home/pi/.emulationstation/es_systems.cfg' \
    [pyserial]='/home/pi/ADMIN/CMD/PYTHON/SERIAL/serial_daemon.py' \
    [pyserial_log]='/home/pi/ADMIN/.log/serialpy.log' \
    [runcmd-start]='/opt/retropie/configs/all/runcommand-onstart.sh' \
    [runcmd-end]='/opt/retropie/configs/all/runcommand-onend.sh' \
    [settings]='/home/pi/ADMIN/.sys/.settings' \
    [sleep]='/home/pi/ADMIN/CMD/SLEEP/SLEEP.sh' \
    [states]='/home/pi/ADMIN/.sys/.states' \
    [thd_coin]='/home/pi/ADMIN/CMD/THD/TEENSY_COIN.sh' \
    [thd_conf]='/etc/triggerhappy/triggers.d/teensy.conf' \
    [thd_rst]='/home/pi/ADMIN/CMD/THD/TEENSY_RST.sh' \
  )

  if [ "${#}" -lt 1 ]; then
    clear
    for i in "${!txtfiles[@]}"; do
      echo -e "\x27$i\x27: ${txtfiles[$i]}"
    done
    sleep 1
    echo " "
    for i in "${!txtfiles[@]}"; do
      [ ! -f "${txtfiles[$i]}" ] && echo "${txtfiles[$i]} not found!"
    done
  else
    clear

    if [ "${#}" -gt 1 ]; then
      arg="${1}"
      file="${2}"
      echo -e " Press any key to run\n ${txtfiles[$file]}"
      read -srN1
      clear
      [[ $arg == run ]] && sudo bash "${txtfiles[$file]}"
    else
      file="${1}"
      echo -e " Press any key to edit\n ${txtfiles[$file]}"
      read -srN1
      sudo nano "${txtfiles[$file]}"
    fi
  fi
}

compare() {
  [ "${#}" -lt 2 ] && return

  local file1=${1}
  local file2=${2}
  local arg_str=${*}
  local new_str=

  file1_str=$(echo "$file1" | sed 's|/home/pi|~|')
  file2_str=$(echo "$file2" | sed 's|/home/pi|~|')

  new_str=$(echo "$file1_str $file2_str" | sed 's|/home/pi|~|g')

  if [[ ${#new_str} < $(tput cols) ]]; then
    new_str="$new_str"
  else
    file1_str=$(echo "$file1" | sed 's/[^/]*\//..\//g; s/[^/]\+//')
    file2_str=$(echo "$file2" | sed 's/[^/]*\//..\//g; s/[^/]\+//')
    new_str=$(echo "$file1_str $file2_str" | sed 's|/home/pi|~|g')
  fi
 
  clear
  echo ""
  echo -e "\n$new_str\n"

  local width=$(tput cols)
  diff -sy --width=55 "$file1" "$file2"

}

pkgdump() {
  [ "${#}" -lt 1 ] && return

  if [[ ${1} == "--installed" ]] \
  || [[ ${1} == "-installed" ]] \
  || [[ ${1} == "installed" ]] \
  || [[ ${1} == "--i" ]] \
  || [[ ${1} == "-i" ]] \
  || [[ ${1} == "i" ]]; then
    sudo apt list --installed \
    | awk '{$1=$1;print" "$0}' \
    | cut -d[ -f1 | cut -c -56 \
    | sudo tee /home/pi/ADMIN/.log/apt.list 2>&1
    sleep 2
    echo -e "\n SUCCES writing list to \x27/home/pi/ADMIN/.log/apt.list\x27\n"
  fi
}


curs() {
  local arg=${1}
  arg=$(echo "$arg" | sed -e "s/ \+//g")

  [[ "${arg:0:2}" == "--" ]] && arg="${arg:2}"
  [[ "${arg:0:1}" == "-" ]] && arg="${arg:1}"

  arg=$(echo "$arg" | tr '[:upper:]' '[:lower:]')

  case $arg in
   '1'|'on'|'true'|'yes'|'enabled')
     setterm --cursor on
     ;;
   '0'|'off'|'false'|'no'|'disabled')
     setterm --cursor off
     ;;
  esac
}


lsusr() {
  local stdoutput=$(sudo w)

  clear
  echo "$stdoutput" | awk '{$1=$1;print}' | \
  awk '{
   if(NR==1){
     split($0,users,",");
     print "\n"users[2]":\n"
   }else if(NR>2) {
     print " "$2"\t"$3     
   }
  }'
}

backup() {
  local backup_dir='/home/pi/ADMIN/.backup'
  local script_dir='/home/pi/ADMIN/CMD/BACKUP'

  if [[ "${#}" < 1 ]]; then
    clear
    sudo bash "$script_dir/backup.sh"

  elif [[ "${1}" == list ]]; then
    sudo 7z l "$backup_dir/BACKUP.zip" | awk '{print $6}' | tail -n +16
  fi
}

pids() {
  if [[ $1 == -v ]]; then
    ps -ef | grep -v grep | grep -i "${@:2}"
  elif [[ $1 == kill ]]; then 
    while read -r line; do echo "killing pid $line"; sudo kill -9 "$line"; done< <(ps -ef | grep -v grep | grep -i "${@:2}" | awk '{print $2}')
  else
    ps -ef | grep -v grep | grep -i "${@}" | awk '{print $2}' 
  fi
}


kill() {
 arg=${@}
 sudo kill -9 "$arg"
}


CRT() {
 local arg=${1:-'CONF'}
 arg=$(echo $arg | tr '[:lower:]' '[:upper:]')
 [ "$#" -lt 1 ] && return || echo "$arg"

 if [[ $arg == CONF ]]; then
   python3 "/opt/retropie/configs/all/CRT/config/Configuration Utility.py"

 elif [[ $arg == UTILITY ]]; then
   sudo nano /opt/retropie/configs/all/CRT/bin/ScreenUtilityFiles/config_files/utility.cfg

 elif [[ $arg == BGM ]]; then
   sudo nano /opt/retropie/configs/all/CRT/bin/ScreenUtilityFiles/bin/service_bgm/bgm.py

 fi
}

pyserial() {
  [ -c /dev/ttyACM0 ] && printf "$@" > /tmp/pyserial.fifo
}

upload() {
  expect /home/pi/ADMIN/CMD/FTP/sftp-upload.exp "$@"
}

exists() {
  [ -f "$@" ] && echo -e "\nfile \x27$@\x27 exists!\n" || echo -e "\nfile doesn't exist.\n"
}

play() {
  SDL_AUDIODRIVER='alsa' AUDIODEV='hw:1,0'
  ffplay -nodisp -autoexit -loglevel quiet "$@"
}

mod() {
  local path=
  [[ ${1} == ADMIN ]] && sudo chmod -R 775 /home/pi/ADMIN
}

tab() {
  local first=${1}
  local args="${*}"

  stdout="$(eval $args)"
  echo "$stdout" | awk '{print "  "$0}'
}


img() {
  tty=$(tty)

  if [[ $tty == /dev/tty* ]]; then
    sudo fbi -t 0 --once --noverbose "$@"
  elif [[ $tty == /dev/pts* ]]; then
    sudo fbi -T 1 -d /dev/fb0 --once --noverbose "$@"
  fi
  reset
}


press() {
  [ $# -lt 1 ] && return 
  local key=${1}
  key=$(echo $key | tr '[:upper:]' '[:lower:]')

  case $key in
    [aA-zZ])
      /usr/bin/printf $key > /tmp/vkbdd.fifo
      ;;
    [0-9])
      /usr/bin/printf $key > /tmp/vkbdd.fifo
      ;;
    'esc')
      /usr/bin/printf '\033' > /tmp/vkbdd.fifo
      ;; 
    'f4')
      /usr/bin/printf '\215' > /tmp/vkbdd.fifo
      ;;
    *)
      ;;
  esac
}


clocks() {
  printf "\nCLOCKS:\n\n"
  for src in arm core gpu emmc uart v3d h264 isp pwm vec pixel dpi hdmi; do
    echo -e "$src: $(vcgencmd measure_clock $src)" | \
    awk -v OFS=\n -F':|=' '{
      name = $1;
      val = $3;
      val /= 1000;
      unit=" hz"

      unit=(val >= 10000 ? "Mhz" : (val >= 100 ? "Khz" : " hz" ))
      val >= 10000 ? val /= 1000 : val=val;

      cmd = "echo \"" val "\" | sed \x27s/./&./4\x27";
      cmd | getline val_form;
      close(cmd);

      printf "%s\t%8.2f %s\n", name, val_form, unit

    }'
  done
  printf "\n\n"
}


doc() {
  [ "${#}" -lt 1 ] && return
  local doc_dir="/home/pi/ADMIN/DOCS"
  local first=${1}
  local args=${@}
  local cmd=${1}
  local name=

  if [[ "$cmd" == "read" ]] && [[ "${#}" > 1 ]]; then
    #[ "${#}" -gt 1 ] && name=${2} || return
    name=${2}

    [ -f "$doc_dir/$name.doc" ] \
      && sudo nano "$doc_dir/$name.doc" \
      || echo -e "\nFile not found."
  else
    if [[ "$cmd" == "write" ]] && [[ "${#}" > 1 ]]; then
      #if [ "${#}" -gt 1 ]; then
        cmd=${2}
        args=${@:3}
      #fi
    else
      args=${@:2}
    fi

    local file="$doc_dir/$cmd.doc"
    local maxlines=$(( $(tput lines) - 9 ))    

    clear
    echo -e "\n Writing to \x27$file\x27 \n"
    echo -e "$(echo $cmd | tr '[:lower:]' '[:upper:]') DOC\ncommand: \x27$cmd $args\x27\n" | sudo tee "$file" &>/dev/null
    eval "$cmd $args" 2>&1 | decolor | sudo tee -a "$file" &>/dev/null
    sleep 1

    file_len=$(( $(cat $file | wc -l) + 8 ))

    if [[ $file_len -lt $maxlines ]];then
      cat $file | awk -v len="$(tput cols)" '{print " "substr($0,0,len)}'
    else
      cat $file | awk -v len="$(tput cols)" -v rows="$maxlines" '{if (NR < rows) { print " "substr($0,0,len)}}'
      echo -e " ..."
    fi

    sleep 1
    echo -e "\n Read doc file now? (Y/n)\n"
    read -srN1 choice

    case $choice in
      [yY])
        sudo nano $file
        ;;

        *)
        ;;
    esac
  fi
}


psef() {
  [ $# ] && arg="$1"
  clear
  case $arg in
    [rR])
      _psf | cut -c -56 | tail -n 999 | tac | head -n -2 | less -EKRX
      ;;
    [sS])
      _psf | awk '{$2=$3="";print first" "$0}' | sed 's/ \+/ /g' | awk '{first=$1;$1="";printf "%4d%s\n",first,$0}' | tail -n +4 | cut -c -56 | less -EKRX
      ;;
    *)
      _psf | cut -c -56 | less -EKRX
      ;;
  esac
}


_psf() {
  printf "\n" && ps -ef | \
  awk '{$1=$1;print}' | \
  awk -F' ' '{
    $3=$4=$6=$7="";
    rest=$0;
    print rest; 
  }' | sed -e "s/ \+/ /g" | \
  awk '{
    if (NR == 1){
      print "    "$2"  "$1" "$3" "$4"\n";
    }
    if (NR > 1){
      user=substr($1,0,5);
      printf " %6d %4s", $2, user;
      $1=$2=" ";
      print " "substr($0,5,length($0));
    }
  }'
}


installer() {
  [ ! $# ] && return
  args="${@}"
  arg="$1"
  file="$2"
  logfile="/home/pi/ADMIN/.log/installer.log"
  arc_name='/home/pi/ADMIN/.install/install.zip'
  [ -f $arc_name ] && sudo cp $arc_name "$arc_name.bak"

  echo "args: $args"
  echo "arg: $arg"
  echo "file: $file"

  if [[ $arg == "add" ]]; then
    ( sudo 7z a -r -tzip -p1234 "$arc_name" "$file" && sudo 7z l "$arc_name" 2>&1 )> >(sudo tee $logfile)
  elif [[ $arg == del ]]; then
    ( sudo 7z d -r -p1234 "$arc_name" "$file" && sudo 7z l "$arc_name" 2>&1 )> >(sudo tee $logfile)
  elif [[ $arg == list ]]; then
    sudo 7z l "$arc_name"
  fi
  echo -e "\nDONE!\n\nOutput logged in \x27$logfile\x27"
}

download() {
  local url=${1}
  local dir=${2:-'/home/pi/downloads'}

  valid=$(wget --method=HEAD --no-check-certificate $url 2>&1 | cut -d' ' -f 3 | grep -xcm1 exists.) &>/dev/null

  clear
  echo -e "\nRequesting $url\n"
  sleep 1
  echo -e "\n$(date):\n" | sudo tee ~/ADMIN/log/download.log &>/dev/null
  if ! (( valid )); then
    echo -e "URL Invalid.\n" && return
  else
    echo -n "URL valid." && sleep 1 && echo -e "..downloading to:"
    wget -v --no-check-certificate -P $dir $url 2>&1 \
    | grep --line-buffered -A100 "Length:" \
    | awk '{$1=$1;print}' | cut -d'(' -f1 \
    | awk -vDIR="$dir" -F'\\% ' '{
      if (NR == 2) {
        n=split($0,A,"/");
        lastf = substr(A[n],0,length(A[n])-2);
        delimiter = "\\=";          
        print DIR"/"lastf
      } else {
        n=split($2, parts, delimiter);

        if (n >= 2 ) {
          split($0,fields); 
          split(fields[1],first,".");
          split(fields[2],second,"\\=");
             
          print "\nDONE! ("first[1]"in "second[2]")\n"
        }
      } \
    }' 
  fi
}


alias-func() {
  [ $# -gt 0 ] && arg=${1}

  aliasfile='/home/pi/.bash_aliases'
  funcs=$(cat $aliasfile | grep -c "() {")

  declare -a rownums=()
  declare -a names=()
  declare -A entries=()

  empty_row="                                                        "
  tty_height=$(( $(tput lines) - 8 ))
  found_long_lines=0

  clear

  for ((i=1;i<=$funcs;i++)); do
    last_i=$((i - 1))
    grepstr=$(cat $aliasfile | grep -m"$i" "() {" | tail -n -1)

    name=$(echo "$grepstr" | cut -d'(' -f1)
    names["$i"]="$name"

    rownum=$(cat $aliasfile | grep -w -n -m1 "$grepstr" | cut -d: -f1)
    rownums["$i"]="$rownum"

    if [ "$i" -gt 1 ]; then
      lastrow="${rownums[$last_i]}"
      rownums["$last_i"]="$lastrow $rownum"

      skip=0

      [[ $( echo "${names[$last_i]}" | cut -c -1 ) == "_" ]] && skip=1
      [[ $( echo "${names[$last_i]}" | rev | cut -c -1 ) == '$' ]] && skip=1

      [[ $skip == 0 ]] && entries["${names[$last_i]}"]="${rownums[$last_i]}"

    fi
  done

   while true; do

     [ "${#entries[@]}" -gt 24 ] \
     && _list_entries | less -EKR \
     || _list_entries

     tput sc

     if [ ${#arg} -gt 0 ]; then
       entry="$arg"
       arg=
     else
       read -rp "  type entry: " entry
     fi

     if [[ -v entries[$entry] ]]; then
       sleep 0.5
       range="${entries[$entry]}"
       start=$(echo "$range" | cut -d' ' -f1)
       end=$(  echo "$range" | cut -d' ' -f2)

       page=$(cat $aliasfile | \
        awk -v page_start="$start" -v page_end="$end" '{
         if (NR >= page_start && NR < page_end) {
          if (NR == page_start || NR > (page_end)-3) {
            print "  \033[36m"$0"\033[0m"
          }else{
            if (length($0 > 56)) {
              print substr($0, 1, 56);
            } else {
              print "  "$0;
            }
          }
         }
        }')

       clear
       page_len=$(echo "$page" | wc -l)

       if [ "$page_len" -gt "$tty_height" ]; then
         echo "$page" | awk '{print $0}' | less -ERKX
       else
         echo "$page" | awk '{print $0}'
       fi

       long_lines=$(echo "$page" | grep -c ".\{55\}")

       if [ "$long_lines" -gt 0 ]; then
         found_long_lines=1
       fi

     else
       echo -e "\n  entry doesn't exist."
     fi

     echo -e "\n  press any key to return."
     read -srN1 dummy

     if [ "$found_long_lines" -gt 0 ]; then
       echo "$page" | decolor | sudo tee /tmp/alias-func
       clear
       echo -e "\nfound $long_lines long lines\n - read with nano? (Y/n)"

       read -srN1 read_choice
       case $read_choice in
         [yY])
           sudo nano /tmp/alias-func
           clear && sleep 1
           ;;
         *)
           ;;
       esac
     fi

     for ((r=17;r< "$(($(tput lines) - 2))";r++)); do
       tput cup $r 0
       echo "$empty_row"
     done
     tput rc
   done
}

_list_entries() {
   clear
   sleep 1
   echo -e "\n  ~/.bash_aliases functions:"
   echo -e "  ____________________________________________________\n"

   for i in "${!entries[@]}"; do      val1=$(echo "${entries[$i]}" | cut -d' ' -f1)
     val2=$(echo "${entries[$i]}" | cut -d' ' -f2)
     printf "  %9s\t%4d %4d\n" "$i" "$val1" "$val2"
   done
   echo -e "\n"
 }

unalias ll

ll() {
  arg=${1:-$PWD}

  [ ! -d $arg ] && arg="$PWD" 
  [ $(ls -l $arg | wc -l) -lt 2 ] && ls -l $arg && return
  
  clear
  _ll_list "$arg" | less -EKXR
    
}
_ll_list() {
  local folder="$1"
  local abs_path="$(realpath "$folder")"
  echo -e "$abs_path:\n"
  count=$(ls -l | awk 'NR==1 {print $0"\n"}')

  ls -la --group-directories-first $folder \
  | awk -vdir="$folder" '{
    
    RESET="\033[0m";RED="\033[31m";RED="\033[31m";CYAN="\033[36m";WHITE="\033[37m";
 
    BGCOLOR="\033[40m\033[37m";DIRCOLOR="\033[40m\033[36m";ROWCOLOR=WHITE;

    fname=$9;
    sub(".\\/","",fname);
    hidden=substr(fname,0,2);

    user=$3
    user == "root" ? user="su" : user=user;

    type=substr($1,0,2);

    if (type == "l") next;
    type=(type == "d" ? "D" : (hidden == "." ? hidden : type));
    type == "D" ? fname=fname "/" : fname=fname

    if (NF>9){
      for (i=9+1;i<=NF;i++){ fname = fname" "$i }
      fname = "\x27" fname "\x27";
    } else { fname=$9 }

    cmd = "stat -c \x27%a %n\x27 "dir"/"fname;
    cmd | getline statout
    close(cmd);

    split(statout,octal);
    rights=octal[1];

    size=$5;
    if (size >= 1024 * 1024) {
      size /= (1024 * 1024);
      unit="M"
    } else if (size >= 1024) {
      size /= 1024;
      unit="K"
    } else { unit="B" }

    date_str = $6" "$7" "$8;
    cmd = "date -d \"" date_str "\" +%m-%d\ %R";
    cmd | getline date_formatted;
    close(cmd);
    cmd = "date -d \"" time_str "\" +%R";
    cmd | getline time_formatted;
    close(cmd);

    if (NR > 3) {
      type == "D" ? ROWCOLOR=DIRCOLOR : ROWCOLOR=BGCOLOR
      printf "%s %s %s %s %3.0f%s %s %s\n", ROWCOLOR, type, rights, date_formatted, size, unit, fname, RESET
    }
  }'
  echo -e "\n $(find $folder -maxdepth 1 -type f | wc -l) files. - $(find $folder -maxdepth 1 -type d | wc -l) dir(s)\n"
}

