#include <stdio.h>
#include <string.h>

#include <buffer.h>
#include <bio.h>
#include <pem.h>

char *ctype[] =
{
  "UNBLINDER",
  "BLINDED COIN",
  "SIGNED BLINDED COIN",
  "SIGNED COIN",
  "SIGNED TITLE"};

int main(int argc, char *argv[])
{
  long t, i;
  BIO *bi;
  unsigned char dbuf[4096], *p, cnline[256];
  unsigned long long ids[3];
  char *cn, *ch;

  p = dbuf;
  bi = BIO_new(BIO_s_file());

  if (!strstr(argv[0], "demime")) {
    t = fread(dbuf, 1, 4096, stdin);
    cn = ctype[dbuf[0]];
    memcpy(ids, &dbuf[1], 3 * sizeof(unsigned long long));
    p += 1 + 3 * sizeof(unsigned long long);

    sprintf(cnline, "%016qX %qX %016qX\n", ids[0], ids[1], ids[2]);

    t -= p - dbuf;
    BIO_set_fp(bi, stdout, 0);
    PEM_write_bio(bi, cn, cnline, p, t);
    BIO_free(bi);
  } else {
    BIO_set_fp(bi, stdin, 0);
    if (!PEM_read_bio(bi, &cn, &ch, &p, &t))
      return -1;
    BIO_free(bi);
    for (i = 0; i < 5; i++)
      if (!strcmp(cn, ctype[i]))
        break;
    fputc(i, stdout);
    sscanf(ch, "%qx %qx %qx", &ids[0], &ids[1], &ids[2]);
    fwrite(ids, 3, sizeof(unsigned long long), stdout);

    fwrite(p, 1, t, stdout);
  }
  return 0;
}
