Text annotation appearance stream

Hi, I am trying to implement word wrapping in a text annotation appearance stream via the function below:

if my first block of text is shorter than the width all works correctly, but if the first text run is wiser and I try to adjust it before calling WriteElement, then nothing displays in the annotation.

Any advice would be appreciated.

void MyWriteTextRun(ElementWriter &writer, ElementBuilder &build, const char text_run, double para_width)
{
const char
para_end = text_run + strlen(text_run);
double cur_width = 0;
bool bAdjustedLine = false;

while (text_run < para_end)
{
const char *text_run_end = NULL;
const char *text_run_end_adjusted = NULL;
const char *text_run_space = strchr(text_run, ’ ');
const char *text_run_hrt = strchr(text_run, ‘\n’);

bAdjustedLine = false;

if ((text_run_space) && (text_run_hrt))
{
if (text_run_space < text_run_hrt)
{
text_run_end_adjusted = text_run_end = text_run_space;
text_run_hrt = NULL;
}
else
{
text_run_end = text_run_hrt;
text_run_end_adjusted = text_run_hrt - 2;
}
}
else if (text_run_space)
{
text_run_end_adjusted = text_run_end = text_run_space;
text_run_hrt = NULL;
}
else if (text_run_hrt)
{
text_run_end = text_run_hrt;
text_run_end_adjusted = text_run_hrt - 2;
}

if (!text_run_end) text_run_end = text_run_end_adjusted = para_end - 1;

Element element = build.CreateTextRun(text_run, UInt32(text_run_end_adjusted-text_run+1));

//writer.WriteElement(element);

if (cur_width + element.GetTextLength() <= para_width)
{
writer.WriteElement(element);
cur_width += element.GetTextLength();
}
else
{
// IF CURRENT ELEMENT IS LONGER THAN RECTANGLE THEN SHORTEN
if (cur_width + element.GetTextLength() > para_width)
{
if (cur_width > 0)
{
writer.WriteElement(build.CreateTextNewLine()); // New line
cur_width = 0;
}

if (text_run_hrt)
{
text_run_end = text_run_end_adjusted;
text_run_hrt = NULL;
}

while((cur_width + element.GetTextLength() > para_width) && (text_run_end > text_run+2))
{
text_run_end–;
text_run_end_adjusted–;
element = build.CreateTextRun(text_run, UInt32(text_run_end_adjusted-text_run+1));

bAdjustedLine = true;
}

}

writer.WriteElement(element);
cur_width += element.GetTextLength();

if (bAdjustedLine)
{
writer.WriteElement(build.CreateTextNewLine()); // New line
cur_width = 0;
}

}

if (text_run_hrt)
{
writer.WriteElement(build.CreateTextNewLine()); // New line
cur_width = 0;
}
text_run = text_run_end+1;

text_run_end = NULL;
}

}