permutations done, found a pretty nice algorithm