some interesting sub problems here.
left the output verbose as it's fun to watch
nicer output