#include <stdio.h>
#include <stdarg.h>
#include <ctype.h>

#include "i2c.h"
#include "codegen.h"

void dump(char *s, ...)
{
  va_list ap;
  if (suppress_perms) return;
  va_start(ap, s);
    vfprintf(output_file, s, ap);
  va_end(ap);
  fflush(output_file);
}

// just to make the source call intentions clearer.  They all do the same,
// apart from a different indentation level for each.
void dump_code(char *s, ...)
{
  va_list ap;
  if (suppress_perms) return;
  // fprintf(output_file, "%s", code_indent);  fflush(output_file);
  va_start(ap, s);
    vfprintf(output_file, s, ap);
  va_end(ap);
  fflush(output_file);
}

char commentbuff[1024*1024];
char *cbp = commentbuff;

void dump_comment(char *s, ...)
{
  va_list ap;
  if (suppress_perms) return;
  if (suppress_icode) return;

  // Doesn't make sense to save these in the stack, but maybe saving them to an
  // array indexed by source line would work, which could be output along with
  // the actual source line.
  
  cbp += sprintf(cbp, "%s", comment_indent);  fflush(output_file);
  va_start(ap, s);
    cbp += vsprintf(cbp, s, ap);
  va_end(ap);
}

void dump_imp_source(char *s, ...)
{
  va_list ap;
  if (suppress_perms) return;
  fprintf(output_file, "%s", source_indent);  fflush(output_file);
  va_start(ap, s);
    vfprintf(output_file, s, ap);
  va_end(ap);
  fflush(output_file);
}

void hexdump_code(int lines)
{
  int i;
  long FROM;
  char line[16];
  if (suppress_perms) return;

  FROM = ftell(icode_file);
  while (lines --> 0) {
    for (i = 0; i < 16; i++) {
      line[i] = fgetc(icode_file);
    }
    int p = 16, q=0;

    dump_code("%08x:", q);
    for (i = 0; i < p; i++) {
      dump_code(" %02x", line[i]&255);
    }
    for (i = p; i < 16; i++) {
      dump_code("   ");
    }
    dump_code("  : ");
    for (i = 0; i < p; i++) {
      if (isprint(line[i])) {
        dump_code("%c", line[i]);
      } else {
        dump_code(".");
      }
    }
    for (i = p; i < 16; i++) {
      dump_code(" ");
    }
    dump_code("\n");
  }
  fseek(icode_file, FROM, SEEK_SET);
}
