#!/bin/bash

declare -A num
declare -A siz

print_data() {
	echo "--------------"
	for key in "${!num[@]}"; do
		echo ${key}:${num[${key}]}:${siz[${key}]}
	done

	exit 1
}

# Print data if we press ctrl+c
trap print_data SIGINT

# Can't use find guten | while read line ... because this will spawn a
# sub-shell where all our updates will be lost.
while read line; do
	fn=$(basename -- $line)
	ext="${fn##*.}"
	if [ ! \( \( "${fn}" = "${ext}" \) -o \( -z "${ext}" \) \) ]; then
		fsize=$(stat -c "%s" $line)
		if [ -z ${num["${ext}"]} ]; then
			num+=(["${ext}"]=1)
			siz+=(["${ext}"]="${fsize}")
		else
			num+=(["${ext}"]=$(echo ${num["${ext}"]} + 1 \
				| BC_LINE_LENGTH=0 bc))
			siz+=(["${ext}"]=$(echo ${siz["${ext}"]} + ${fsize} \
				| BC_LINE_LENGTH=0 bc))
		fi
		>&2 echo "${ext}:${num["${ext}"]}:${siz["${ext}"]}"
	fi
done < <(find guten/)
print_data
