```
/** Exact per-reagent totals of a pour log, counted in thousandths. */
export function doseTotals(log: [string, string][]): Record<string, string> {
  const thousandths: Record<string, number> = {};
  const places: Record<string, number> = {};
  for (const [reagent, amount] of log) {
    const written = /^-?\d+(?:\.(\d{1,3}))?$/.exec(amount);
    if (written === null) {
      throw new Error("amount is not a decimal of at most three places: " + amount);
    }
    const digits = written[1] ?? "";
    const sign = amount.startsWith("-") ? -1 : 1;
    const bare = amount.replace("-", "").replace(".", "");
    thousandths[reagent] = (thousandths[reagent] ?? 0) + sign * Number(bare) * Math.pow(10, 3 - digits.length);
    places[reagent] = Math.max(places[reagent] ?? 0, digits.length);
  }
  const totals: Record<string, string> = {};
  for (const reagent in thousandths) {
    const totalThousandths = thousandths[reagent];
    const decimalPlaces = places[reagent];
    if (totalThousandths === 0) {
      totals[reagent] = "0";
    } else {
      let totalString = totalThousandths.toString();
      if (decimalPlaces > 0) {
        totalString = totalString.padStart(decimalPlaces + 3, '0').slice(0, decimalPlaces + 3);
        if (totalString.length > decimalPlaces + 2) {
          totalString = totalString.slice(0, -1); // Remove the last digit
        }
      } else {
        totalString = Math.round(totalThousandths).toString();
      }
      totals[reagent] = sign === -1 ? "-" + totalString : totalString;
    }
  }
  return totals;
}
```