Faster/cleaner implementation of extractPath method