#include <vo_stdio.h>
#include <string.h>
#include <sysmemory.h>
#include <extSymbols.h>
#include "printsymbol.h"
#include "env.h"

extern __mem_y u_int16 extSymbolSize;

u_int16 PrintSymbolRaw(const char *s) {
  u_int32 crc32 = SymbolCrunchStringCalcCrc32(s);
  int retVal = 0;

  {
    struct ExtSymbol __mem_y *sym = SymbolFindByCrc(crc32);
    if (sym) {
      printf("RAM CRC 0x%08lx, addr 0x%04x: %s", crc32, sym->addr, s);
      if ((u_int16)(sym->lib) == 2) {
	struct EnvVariable *env = (struct EnvVarible *)sym->addr;
	printf("(%s)=%s", env->name, env->value);
      }
      printf("\n");
      retVal++;
    }
  }
  if (extSymbolSearchRom) {
    struct ExtSymbolRom *h = SymbolFindRomByCrc(crc32);
    if (h) {
      printf("ROM CRC 0x%08lx, addr 0x%04x: %s\n", crc32, h->addr, s);
      retVal++;
    }
  }

  return retVal;
}

void PrintSymbol(const char *s) {
  char *s2 = NULL;
  u_int16 found;

  if (!strcmp(s, "-")) {
    struct ExtSymbol __mem_y *yp = extSymbol;
    struct ExtSymbolRom *xp = extSymbolRom;
    int i, n=0;
#if 1
    for (i=0; i<extSymbolRomSize; i++) {
      if (xp->crc32) {
	printf("ROM CRC 0x%08lx, addr 0x%04x\n", xp->crc32, xp->addr);
	n++;
      }
      xp++;
    }
#endif
    printf("Total %d/%d ROM symbols\n", n, extSymbolRomSize);
    n = 0;
    for (i=0; i<extSymbolSize; i++) {
      if (yp->crc32) {
	printf("RAM CRC 0x%08lx, addr 0x%04x", yp->crc32, yp->addr);
	if ((u_int16)(yp->lib) == 2) {
	  struct EnvVariable *env = (struct EnvVarible *)yp->addr;
	  printf(", %04x=%04x, %s=%s",
		 env->name, env->value, env->name, env->value);
	}
	printf("\n");
	n++;
      }
      yp++;
    }
    printf("Total %d/%d RAM symbols\n", n, extSymbolSize);
    return;
  }

  found = PrintSymbolRaw(s);

  
  if ((s2 = malloc(strlen(s)+5))) {
    s2[0] = '+';
    strcpy(s2+1, s);
    found += PrintSymbolRaw(s2);

    s2[0] = '_';
    found += PrintSymbolRaw(s2);

    strcpy(s2, "_vo_");
    strcat(s2+4, s+(s[0]=='_'));
    found += PrintSymbolRaw(s2);
    free(s2);
    s2 = NULL;
  }

  if (!found) {
    printf("SYM %s not found\n", s);
  }
}
