#!/usr/bin/gawk -f
#
# Usage: generate_table.sh < ${board}.txt
#
# Takes the file generated by collect.sh and generates an ASCII
# table that can be inserted into the README.md.

BEGIN {
  labels[0] = "Baseline"
  labels[1] = "Baseline+pinMode+digitalRead"
  labels[2] = "ButtonConfig"
  labels[3] = "ButtonConfigFast1"
  labels[4] = "ButtonConfigFast2"
  labels[5] = "ButtonConfigFast3"
  labels[6] = "Encoded4To2ButtonConfig"
  labels[7] = "Encoded8To3ButtonConfig"
  labels[8] = "EncodedButtonConfig"
  labels[9] = "LadderButtonConfig"
  record_index = 0
}
{
  u[record_index]["flash"] = $2
  u[record_index]["ram"] = $4
  record_index++
}
END {
  NUM_ENTRIES = record_index

  base_flash = u[0]["flash"]
  base_ram = u[0]["ram"]
  for (i = 0; i < NUM_ENTRIES; i++) {
    if (u[i]["flash"] != "-1") {
      u[i]["d_flash"] = u[i]["flash"] - base_flash
      u[i]["d_ram"] = u[i]["ram"] - base_ram
    } else {
      u[i]["d_flash"] = -1
      u[i]["d_ram"] = -1
    }
  }

  printf("+--------------------------------------------------------------+\n")
  printf("| functionality                   |  flash/  ram |       delta |\n")
  for (i = 0; i < NUM_ENTRIES; i++) {
    if (u[i]["flash"] == "-1") continue

    name = labels[i]
    if (name ~ /^Baseline$/ \
        || name ~ /^ButtonConfig$/ \
        || name ~ /^Encoded4To2ButtonConfig$/ \
        || name ~ /^LadderButtonConfig$/) {
      printf(\
        "|---------------------------------+--------------+-------------|\n")
    }
    printf("| %-31s | %6d/%5d | %5d/%5d |\n",
        name, u[i]["flash"], u[i]["ram"], u[i]["d_flash"], u[i]["d_ram"])
  }
  printf("+--------------------------------------------------------------+\n")
}
