[xsl] grouping problem...kinda?

Subject: [xsl] grouping problem...kinda?
From: tom a <tasmito@xxxxxxxxx>
Date: Fri, 21 Jan 2011 15:51:57 -0800 (PST)
I'd like to modify an element based on a sibling element that precedes it in
document order. eg:

Input A:
<doc>
  <p>1</p>
  <p class='a'>2</p>
  <p>3</p>
  <p>4</p>
  <p class='b'>5</p>
  <p>6</p>
  <p class='c'>7</p>
</doc>
Desired Output A:
<doc>
  <p>1</p>
  <p class='a'>2</p>
  <p class='a'>3</p>
  <p class='a'>4</p>
  <p class='b'>5</p>
  <p class='b'>6</p>
  <p
class='c'>7</p>
</doc>

So the <p>'s get the @class of the sibling <p> that
first precedes them, if any.

But the <p>s with @class can appear in any
order. eg:

Input B:
<doc>
  <p>1</p>
  <p class='b'>2</p>
  <p>3</p>
  <p>4</p>
  <p class='a'>5</p>
  <p>6</p>
  <p class='c'>7</p>
</doc>
Desired Output B:
<doc>
  <p>1</p>
  <p class='b'>2</p>
  <p class='b'>3</p>
  <p class='b'>4</p>
  <p class='a'>5</p>
  <p class='a'>6</p>
  <p
class='c'>7</p>
</doc>

This feels like a grouping problem, but I'm stumped.
Any help is greatly appreciated!

Current Thread