#!/bin/sh

interval=0.01

cputime_get()
{
while read -a cputime < /proc/stat
do
	sleep ${interval} & tpid=$!

	#read -a cputime < /proc/stat
	unset cputime[0]

	prev_total=${total:-0}
	prev_active=${active:-0}

	total=0
	for v in "${cputime[@]}"; do
		let "total += $v"
	done
	let "active = ${total} - ${cputime[3]} - ${cputime[4]}"
	let "diff_total = $total - $prev_total"
	let "diff_usage = ($diff_total != 0) ? (10000 * ($active - $prev_active) / $diff_total / 100) : 0"

	echo "$diff_usage"

	wait $tpid
done
exit
}

#tsl_str="$(tput tsl)"
#fsl_str="$(tput fsl)"

if false; then
while true; do
	sleep ${interval} & tpid=$!
	read -a cputime < /proc/stat
	echo "${cputime[*]:1}"
	wait $tpid
done | awk '{
	old_active=0
	old_total=0
	while (getline > 0)
	{
		old_active = active
		old_total = total
		active = $1 + $2 + $3 + $6 + $7 + $8 + $9 + $10
		total = active + $4 + $5
		dtotal = total - old_total
		printf "%f\n", (old_total == 0 || dtotal == 0) ? 0 : 100 * (active - old_active) / dtotal
		fflush()
	}
}'
exit
fi

if true; then
	free -h -s ${interval} | stdbuf -i0 -o0 grep 'Mem' | awk '{printf "%0.1f\n", 100.0 * $3 / $2;}'
fi

{ TERM=xterm+sl
prev_total=0
prev_idle=0
while true; do
	sleep ${interval} & tpid=$!

	cputime_get
	echo "${diff_usage}"

	#mem=$( free -h --si | grep Mem | awk '{printf "%0.1f", 100.0 * $3 / $2}' )
	#status_text="${tsl_str}cpu: ${diff_usage}% mem: ${mem}%${fsl_str}"
	#echo "${status_text}"

	wait ${tpid}
done; }
#& ipid=$!

#bash
#memwatch
#htop -d10

#kill ${ipid}
tput dsl
