#!/bin/bash

basedir=$(dirname $(readlink -f $BASH_SOURCE))
. $basedir/common.sh

our_asteroid=26,29

declare -A asteroids
declare -A asteroid_angles

read_file input.txt

# calculate angles to each asteroid from us
for asteroid in ${!asteroids[@]}; do
    if [ $asteroid == $our_asteroid ]; then
        continue
    fi

    # otherwise, get the angle from us to there
    angle=$(get_angle $our_asteroid $asteroid)

    # see if we've already got this angle as a key, if so append to it,
    # otherwise set it
    if [ ${asteroid_angles[$angle]+a} ]; then
        asteroid_angles[$angle]+="|$asteroid"
    else
        asteroid_angles[$angle]=$asteroid
    fi
done

zapped_count=0

sorted_angles=( "$(get_angles_list asteroid_angles)" )

for (( round=0; round<3; round++ )); do
    for angle in $sorted_angles; do
        if [ ${asteroid_angles[$angle]+a} ]; then
            echo "$angle: ${asteroid_angles[$angle]}"
            closest=$(get_closest_asteroid "${asteroid_angles[$angle]}")
            #echo "      - closest $closest"
            # blow up the closest!
            newlist=$(remove_asteroid_from_string ${asteroid_angles[$angle]} $closest)
            if [ "x$newlist" == "x" ]; then
                unset asteroid_angles[$angle]
            else
                asteroid_angles[$angle]=$newlist
            fi
            zapped_count=$((zapped_count+1))

            echo "$zapped_count: $closest"

            if [ $zapped_count -eq 200 ]; then
                echo "The 200th asteroid to be zapped was $closest"
                break 2
            fi
        fi
    done
done

echo "And we're done."
