#!/usr/bin/fish

# Copyright (C) 2019 Tim Düsterhus
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

for algo in *
	if [ ! -d "$algo" ]
		continue
	end
	
	pushd $algo
	for k in *
		if [ ! -d "$k" ]
			continue
		end
		for file in $k/*
			begin
				if [ "$algo" != "uscensus.txt" ]
					echo "iteration,sum,max,avg,avgnonzero,maxperavg,maxperavgnonzero,avgccdist,avgccdistpermax"
					jq -s -r '
					map(
						{
							"movement": (
								.cluster_movement
								| to_entries
								| map(.value)
								| [
									(. |add),
									(. | max),
									(add / (. | length)),
									(try (
										map(select(. > 0))
										| (add / (. | length))
									) catch 0
									)
								]
								| . + [
									(try (.[1] / .[2]) catch 0),
									(try (.[1] / .[3]) catch 0)
								]
							),
							"avg_distance": (
								.center_center_distance
								| (add / (. | length))
							)
						}
						| (
							.movement
							+ [
								.avg_distance,
								try (.avg_distance / .movement[1]) catch 0
							]
						)
					)[]
					| @csv' < $file |nl -s','
				else
					echo "iteration,sum,max,avg,avgnonzero,maxperavg,maxperavgnonzero"
					jq -s -r '
					map(
						{
							"movement": (
								.cluster_movement
								| to_entries
								| map(.value)
								| [
									(. |add),
									(. | max),
									(add / (. | length)),
									(try (
										map(select(. > 0))
										| (add / (. | length))
									) catch 0
									)
								]
								| . + [
									(try (.[1] / .[2]) catch 0),
									(try (.[1] / .[3]) catch 0)
								]
							)
						}
						| (
							.movement
						)
					)[]
					| @csv' < $file |nl -s','
				end
			end > movement_{$k}_(basename $file)
		end
	end
	popd
end
