private void ResolveWeakTypes(int start, int limit, sbyte level, sbyte sor, sbyte eor)
{
// Rule W1.
// Changes all NSMs.
sbyte preceedingCharacterType = sor;
for (int i = start; i < limit; ++i) {
sbyte t = resultTypes[i];
if (t == NSM) {
resultTypes[i] = preceedingCharacterType;
} else {
preceedingCharacterType = t;
}
}
// Rule W2.
// EN does not change at the start of the run, because sor != AL.
for (int i = start; i < limit; ++i) {
if (resultTypes[i] == EN) {
for (int j = i - 1; j >= start; --j) {
sbyte t = resultTypes[j];
if (t == L || t == R || t == AL) {
if (t == AL) {
resultTypes[i] = AN;
}
break;
}
}
}
}
// Rule W3.
for (int i = start; i < limit; ++i) {
if (resultTypes[i] == AL) {
resultTypes[i] = R;
}
}
// Rule W4.
// Since there must be values on both sides for this rule to have an
// effect, the scan skips the first and last value.
//
// Although the scan proceeds left to right, and changes the type values
// in a way that would appear to affect the computations later in the scan,
// there is actually no problem. A change in the current value can only
// affect the value to its immediate right, and only affect it if it is
// ES or CS. But the current value can only change if the value to its
// right is not ES or CS. Thus either the current value will not change,
// or its change will have no effect on the remainder of the analysis.
for (int i = start + 1; i < limit - 1; ++i) {
if (resultTypes[i] == ES || resultTypes[i] == CS) {
sbyte prevSepType = resultTypes[i-1];
sbyte succSepType = resultTypes[i+1];
if (prevSepType == EN && succSepType == EN) {
resultTypes[i] = EN;
} else if (resultTypes[i] == CS && prevSepType == AN && succSepType == AN) {
resultTypes[i] = AN;
}
}
}
// Rule W5.
for (int i = start; i < limit; ++i) {
if (resultTypes[i] == ET) {
// locate end of sequence
int runstart = i;
int runlimit = FindRunLimit(runstart, limit, new sbyte[] { ET });
// check values at ends of sequence
sbyte t = runstart == start ? sor : resultTypes[runstart - 1];
if (t != EN) {
t = runlimit == limit ? eor : resultTypes[runlimit];
}
if (t == EN) {
SetTypes(runstart, runlimit, EN);
}
// continue at end of sequence
i = runlimit;
}
}
// Rule W6.
for (int i = start; i < limit; ++i) {
sbyte t = resultTypes[i];
if (t == ES || t == ET || t == CS) {
resultTypes[i] = ON;
}
}
// Rule W7.
for (int i = start; i < limit; ++i) {
if (resultTypes[i] == EN) {
// set default if we reach start of run
sbyte prevStrongType = sor;
for (int j = i - 1; j >= start; --j) {
sbyte t = resultTypes[j];
if (t == L || t == R) { // AL's have been removed
prevStrongType = t;
break;
}
}
if (prevStrongType == L) {
resultTypes[i] = L;
}
}
}
}