/* Minimal printf for pedagogical purposes. 
 * Fucking printf, how does it work?
 * See
   http://www.reddit.com/r/programming/comments/c2ou5/what_does_the_printf_function_consist_of_in_c/
 * for context. A real printf is available at
   http://src.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/uts/common/os/printf.c
 */

#include <unistd.h>
#include <stdarg.h>
#include <string.h>

int vprintf(const char *fmt, va_list args) {
  const char *s, *to_output;
  int rv = 0;
  int val;

  for (s = fmt; *s; s++) {
    if (*s == '%') {
      switch (*++s) {
      case '%':
        to_output = "%";
        break;
      case 's':
        to_output = va_arg(args, const char*);
        break;
      default:
        to_output = "(format string error)";
        break;
      }
      /* In a real stdio, you would use fputs to buffer these writes. */
      val = write(1, to_output, strlen(to_output));
    } else {
      val = write(1, s, 1);
    }

    if (val == -1) return -1;
    rv += val;
  }
  return rv;
}

int printf(const char *fmt, ...) {
  va_list args;
  int rv;
  va_start(args, fmt);
  rv = vprintf(fmt, args);
  va_end(args);
  return rv;
}

#ifndef __GNUC__
#define __attribute__(x)
#endif

int main() __attribute__((weak));

int main(int argc, char **argv) {
  if (printf("This program, %s, is 100%% silly.\n", argv[0]) < 0) return 1;
  return 0;
}

