int i = 0;
while (i < format.length()) {
if (format.charAt(i) == '%') {
final String subStr = format.substring(i);
final MatchResult match = convPattern.exec(subStr);
if (match == null || match.getIndex() != 0) {
throw new IllegalArgumentException("Bad conversion at index " + i + " in format String: " + format);
}
if (match.getGroup(2) != null && !match.getGroup(2).equals("")) {
throw new UnsupportedOperationException("Flags are not yet supported in this implementation.");
}
// TODO: check preconditions and possibly throw IllegalFormatException
final Object arg;
final int width;
final int prec;
final String suffix;
final Conversion conv = getConversion(match.getGroup(5).charAt(0));
final boolean autoIndexed = match.getGroup(1) == null || match.getGroup(1).equals("");
if (conv.equals(Conversion.escLit) || conv.equals(Conversion.line)) {
arg = null;
}
else if (autoIndexed) {
arg = args[count];
}
else {
arg = args[Integer.valueOf(match.getGroup(1)) - 1];
}
if (match.getGroup(3) == null || match.getGroup(3).equals("")) {
width = 0;
}
else {
width = Integer.valueOf(match.getGroup(3));
}
if (match.getGroup(4) == null || match.getGroup(4).equals("")) {
prec = Integer.MAX_VALUE;
}
else {
prec = Integer.valueOf(match.getGroup(4));
}
if (match.getGroup(6) == null || match.getGroup(6).equals("")) {
suffix = "";
}
else {
suffix = match.getGroup(6);
}
final boolean upper = match.getGroup(5).toUpperCase().equals(match.getGroup(5));
String replacement;
try {
replacement = buildReplacement(conv, upper, width, prec, suffix, arg);
}
catch (Exception e) {
throw new IllegalArgumentException("Error processing substitution " + (count + 1) + ".\nFormat: "
+ originalFormat + "\nArgs: " + Arrays.toString(args), e);
}
buffer.append(replacement);
i += match.getGroup(0).length();
// Auto-index is incremented for non-explicitly indexed conversions
if (autoIndexed)
count += 1;
}