#include "mangle.h"
#include <stdio.h>

const char* demangleandprint(const char *type) {
  const char *end = type;
  if (!type) {
    printf("<no type>");
    return 0;
  }
  if ((*type == 'v') && (!*(type+1))) {
    printf ("void");
    return 0;
  }
  switch (*type) {
  case 'i' : printf("int");
    end = type+1;
    break;
  case 'j' : printf("unsigned int");
    end = type+1;
    break;
  case 'P' : {
    end = demangleandprint(type+1);
    printf("*");
  } break;
  case 'R' : {
    end = demangleandprint(type+1);
    printf("&");
  } break;
  case 'N' : {
    type++;
    end++;
    while (*end != 'E') {
      end = demangleandprint(end);
      if (*end != 'E') printf("::");
    }
  } break;
  case '0':
  case '1':
  case '2':
  case '3':
  case '4':
  case '5':
  case '6':
  case '7':
  case '8':
  case '9': {
    unsigned l = 0;
    while ((*type >= '0') && (*type <= '9')) {
      l = l*10 + *type-'0';
      type++;
      end++;
    }
    for (unsigned i=0; i<l; i++, type++, end++) printf("%c", *type);
    break;
  }
  }
  return end;
}


void printvalue(void *data, const char *type) {
  if (!type) {
    printf("<no type>");
    return;
  }
  if ((*type == 'v') && (!*(type+1))) {
    printf ("void");
    return ;
  }
  if (!data) {
    printf("<no value>");
    return;
  } 
  switch (*type) {
  case 'i' : printf ("%d", *(int *)data); break;
  case 'j' : printf ("%d", *(unsigned int *)data); break;
  case 'P' :
  case 'R' :
  case 'N' : printf ("%x", *(unsigned int *)data); break;
  }
}

void castandprint(void *data, const char *type) {
  printf("(");
  demangleandprint(type);
  printf(")");
  printvalue(data, type);
}

