Could anyone clarify this sentence for me:

"Fóru þeir þá út á skip, en at því hugði Án, hvar hann skyldi þess
koma sér, at öllum þætti sér mest mein at."

It's from Áns saga bogsveigis. The context is that Án, a typically
troublsome young man, and bourgeoning saga hero, has just convinced
his more upstanding but conventional elder brother to let him come
along to visit the king.

"Then they went out onto the ship," is easy enough, "and/but An
wondered..."

But what exactly is "hvar hann skyldi þess koma sér"? At a guess,
could it be that he "wondered where to put himself" on the ship?
What does the genitive 'þess' relate to?

Does the first 'at' go with 'hugði'--"he wondered [about the
following thing]"--or is 'at því...at' equivalent to 'því...at' "for
this reason...because"?

In other words, is An (a) wondering where he should put himself,
given that everyone thinks he's trouble? Or (b) is he wondering
where to go "so as to / in order to" make everyone think the worst
of him?

Or is he wondering why they think this about him, what he's done to
get this reaction? I'm a bit confused...

Can the second 'sér' in theory refer to either An or the sailors?

Llama Nom