/*
 *  fiddle.c $Revision: 1.6 $
 *  Fiddles with bits.
 */

/* Inherited from ATI. Tweaked to generate .def files for the JTAGJet
 * debugger.
 */

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


#define READ_BUF_SIZE 512
char *infile, **outfiles;
int num_outfiles;
FILE *ifp;
FILE *ofp;
int line_number;

char read_buf[READ_BUF_SIZE];
int rb_pos = -1;

int pad_count;


/*
 *  Output types. All constants should be forced
 *  to 32 bits since they are 16 bit wide in the 16 bit compiler.
 *
 *  Example:    unsigned long l = 1 << 31; // l = 0 in the 16 bit compiler.
 *
 */
#ifndef ATI_MSVC_COMPILER
const char *uint32String = "unsigned long";
const char *uint64String = "unsigned long long";
#define AX64BIT0  0x1LL
#define AX64MASK  0xffffffffffffffffLL
#define AX64S "LL"
#define AX64D "lld"
#define AX64X "llx"
#else
const char *uint32String = "unsigned long";
const char *uint64String = "unsigned __int64";
#define AX64BIT0  0x1i64
#define AX64MASK  0xffffffffffffffffi64
#define AX64S "i64"
#define AX64D "I64d"
#define AX64X "I64x"
#endif

typedef unsigned int u32;

typedef struct token_s {
    int type;
    char string[64];
    int value;
    int char_number;
} token_t;

/*
 *  token types
 */
#define T_STRUCT	 0
#define T_UNION		 1
#define T_ENUM		 2
#define T_VALUE		 3
#define T_ADDRESS	 4
#define T_OPEN		 5
#define T_CLOSE		 6
#define T_UINT_TYPE	 7
#define T_PAD_TYPE	 8
#define T_NAME		 9
#define T_INT		10
#define T_PLUS		11
#define T_SEMICOLON	12
#define T_EOF		13
#define T_UNKNOWN	14

token_t token;


#define TYPE_HEADER	\
    int type;		\
void *next;

typedef struct type_header_s {
    TYPE_HEADER
} type_header_t;

type_header_t *ordered_list;


typedef struct field_s {
    char *name;
    char *cname;
    int size;
    int type;
    int num_sub_fields;
    struct field_s *sub_fields;
} field_t;

typedef struct struct_s {
    TYPE_HEADER
        char *name;
    char *cname;
    u32 address; /* for def files */
    char access[32];  /* for def files */
    int size, pad_size, pad_count, total;
    int num_fields;
    field_t *fields;
} struct_t;


typedef struct member_s {
    char *name;
} member_t;

typedef struct union_s {
    TYPE_HEADER
        char *name;
    int size;
    int num_members;
    member_t *members;
} union_t;


typedef struct e_item_s {
    char *name;
    char *cname;
    int value;
} e_item_t;

typedef struct enum_s {
    TYPE_HEADER
        char *name;
    char *cname;
    int bits;
    int max;
    int num_items;
    e_item_t *items;
} enum_t;


typedef struct v_item_s {
    char *name;
    char *cname;
    int value;
    int bits;
    char type;
} v_item_t;

typedef struct value_s {
    TYPE_HEADER
        char *name;
    char *cname;
    int num_items;
    v_item_t *items;
} value_t;


/*
 *  prototypes
 */
void load_file_fdl(char *fname);
struct_t *load_struct();
int load_struct_field(field_t *f);
union_t *load_union();
enum_t *load_enum();
value_t *load_value();
int get_token();
void read_error(char *expected);
void store_file_def(char *filename);
void store_struct_def(FILE *fp, struct_t *s);
void store_struct_field_def(FILE *fp, field_t *field, u32 start_bit);

void store_file_h(char *filename);
void store_struct_h(struct_t *s);
int store_struct_field_h(field_t *f, char *name, char *cname, int start, int size);
void store_union_h(union_t *u);
void store_enum_h(enum_t *e);
void store_value_h(value_t *v);
void store_file_ha(char *filename);
void store_file_vpp(char *filename);
void store_struct_vpp(struct_t *s);
int store_struct_field_vpp(field_t *f, char *cname, int start);
void store_union_vpp(union_t *u);
void store_enum_vpp(enum_t *e);
void store_value_vpp(value_t *v);
void store_file_v(char *filename);
void store_struct_v(struct_t *s);
int store_struct_field_v(field_t *f, char *cname, int start);
void store_union_v(union_t *u);
void store_enum_v(enum_t *e);
void store_value_v(value_t *v);
void store_file_mch(char *filename);
void store_struct_mch(struct_t *s);
int store_struct_field_mch(field_t *f, char *cname, int start);
void store_union_mch(union_t *u);
void store_enum_mch(enum_t *e);
void store_value_mch(value_t *v);
void store_file_pcf(char *filename);
void store_struct_pcf(struct_t *s);
int store_struct_field_pcf(field_t *f, char *cname, int start, int total_size);
char *strcap(char *s);
char *strlower(char *s);
void parse_args(int argc, char **argv);
void usage(void);
char *bits_str(int bits, int value);
char *hex_str(int bits, int value);
char *pre_underscore(char *s);
const char *uint_string(int size);
char *make_def_name(const char *fname);


int
main(int argc, char **argv)
{
    int i;
    char *ext;

    parse_args(argc, argv);

    load_file_fdl(infile);

    for (i = 0; i < num_outfiles; i++)
    {
        if (NULL != (ext = strrchr(outfiles[i], '.')))
        {
            ext++;
            if (strcmp(ext, "h") == 0)
                store_file_h(outfiles[i]);
            else if (strcmp(ext, "vpp") == 0)
                store_file_vpp(outfiles[i]);
            else if (strcmp(ext, "v") == 0)
                store_file_v(outfiles[i]);
            else if (strcmp(ext, "mch") == 0)
                store_file_mch(outfiles[i]);
            else if (strcmp(ext, "ha") == 0)
                store_file_ha(outfiles[i]);
            else if (strcmp(ext, "pcf") == 0)
                store_file_pcf(outfiles[i]);
#ifdef JTAGJET
            else if (strcmp(ext, "def") == 0)
                store_file_def(outfiles[i]);
#endif /* JTAGJET */
            else
                fprintf(stderr, "fiddle:  Do not know how to store \"%s\"\n",
                        outfiles[i]);
        }
        else
            fprintf(stderr, "fiddle:  Do not know how to store \"%s\"\n",
                    outfiles[i]);
    }

    return 0;
}


void
load_file_fdl(char *fname)
{
    type_header_t *last, *tmp;

    if ((ifp = fopen(fname, "r")) == NULL)
    {
        fprintf(stderr, "fiddle:  Unable to open \"%s\".\n", fname);
        exit(1);
    }

    line_number = 0;
    last = NULL;

    while (1)
    {
        switch(get_token())
        {
            case T_STRUCT:
                tmp = (type_header_t*)load_struct();
                break;
            case T_UNION:
                tmp = (type_header_t*)load_union();
                break;
            case T_ENUM:
                tmp = (type_header_t*)load_enum();
                break;
            case T_VALUE:
                tmp = (type_header_t*)load_value();
                break;
            case T_EOF:
                if (last)
                    last->next = NULL;
                fclose(ifp);
                return;
            default:
                read_error("type");
                tmp = NULL;
        }

        if (last == NULL)
            ordered_list = tmp;
        else
            last->next = tmp;
        last = tmp;
    }
}


/* struct format:
 *  struct (name) (size) (pad) [(address) (access_modes)] 
 *  { 
 *     [ [(size) (type) (field_name)] [(size) (pad)] ]*
 *  }
 */
struct_t*
load_struct()
{
    struct_t *s;

    s = (struct_t*)malloc(sizeof(struct_t));
    s->type = T_STRUCT;
    pad_count = 0;

    if (get_token() != T_NAME)
        read_error("struct name");
    s->name = strdup(token.string);
    s->cname = strcap(s->name);

    
    if (get_token() != T_INT)
        read_error("struct size");
    s->size = token.value;

#ifdef JTAGJET
    if (get_token() != T_INT)
        read_error("struct pad"); /* Pad mandatory  XXX horti */
    s->pad_size = token.value;
    
    if (get_token() == T_INT) {  /* Optional stuff for def files */
        s->address = token.value;
        if ( get_token() != T_NAME) 
            read_error("struct def extensions: access");
        if (strcmp(token.string, "r") == 0)
            strcpy(s->access, "read");
        else if (strcmp(token.string, "w") == 0)
            strcpy(s->access, "write");
        else 
            strcpy(s->access, "read write");
    }
    
    if (get_token() != T_OPEN)
        read_error("'{'");
#else
    switch (get_token()) {
        case T_INT:
            s->pad_size = token.value;
            if (get_token() != T_OPEN)
                read_error("'{'");
            break;
        case T_OPEN:
            s->pad_size = s->size;
        default:
            read_error("struct pad size, or '{'");
    }
#endif /* JTAGJET */
    
    s->fields = malloc(sizeof(field_t) * s->size);
    s->num_fields = 0;
    s->total = 0;

    while (get_token() != T_CLOSE)
    {
        s->total += load_struct_field(&s->fields[s->num_fields]);
        s->num_fields++;
    }

    s->pad_count = pad_count;
    if (s->total > s->size)
    {
        fprintf(stderr,
                "fiddle: Error:  "
                "Total size of fields in %s is too large(%d > %d).\n",
                s->name, s->total, s->size);

        exit(1);
    }
    return s;
}


int
load_struct_field(field_t *f)
{
    if (token.type != T_INT)
        read_error("field size");
    f->size = token.value;

    f->type = get_token();
    if (f->type == T_PAD_TYPE)
    {
        f->name = strdup("padXXXXX");
        sprintf(f->name+3, "%d", pad_count);
        f->cname = strcap(f->name);
        pad_count++;
    }
    else
    {
        if (get_token() != T_NAME)
            read_error("field name");
        f->name = strdup(token.string);
        f->cname = strcap(f->name);
    }

    f->num_sub_fields = 0;

    if (get_token() != T_SEMICOLON)
    {
        if (token.type != T_OPEN)
            read_error("';' or '{'");

        /*
         *  load sub fields
         */
        f->sub_fields = malloc(sizeof(field_t) * f->size);
        while (get_token() != T_CLOSE)
        {
            load_struct_field(&f->sub_fields[f->num_sub_fields]);
            f->num_sub_fields++;
        }
    }

    return f->size;
}


union_t*
load_union()
{
    union_t *u;
    int count;

    u = (union_t*)malloc(sizeof(union_t));
    u->type = T_UNION;

    if (get_token() != T_NAME)
        read_error("union name");
    u->name = strdup(token.string);

    if (get_token() != T_INT)
        read_error("union size");
    u->size = token.value;

    if (get_token() != T_OPEN)
        read_error("'{'");

    count = 4;
    u->members = (member_t*)malloc(sizeof(member_t) * count);
    u->num_members = 0;

    while (get_token() != T_CLOSE)
    {
        if (u->num_members == count)
        {
            count *= 2;
            u->members = (member_t*)realloc(u->members,
                    sizeof(member_t) * count);
        }

        if (token.type != T_NAME)
            read_error("union member name");
        u->members[u->num_members].name = strdup(token.string);

        if (get_token() != T_SEMICOLON)
            read_error("';'");

        u->num_members++;
    }

    return u;
}


enum_t*
load_enum()
{
    enum_t *e;
    int cur_value, count;

    e = (enum_t*)malloc(sizeof(enum_t));
    e->type = T_ENUM;

    if (get_token() != T_NAME)
        read_error("enum name");
    e->name = strdup(token.string);
    e->cname = strcap(e->name);

    if (get_token() != T_INT)
        read_error("enum size");
    e->bits = token.value;
    e->max = (1 << token.value) - 1;

    if (get_token() != T_OPEN)
        read_error("'{'");

    cur_value = 0;
    count = 4;
    e->items = (e_item_t*)malloc(sizeof(e_item_t) * count);
    e->num_items = 0;

    while (get_token() != T_CLOSE)
    {
        if (e->num_items == count)
        {
            count *= 2;
            e->items = (e_item_t*)realloc(e->items, sizeof(e_item_t) * count);
        }

        if (token.type == T_PAD_TYPE)
        {
            cur_value++;

            if (get_token() != T_SEMICOLON)
                read_error("';'");
        }
        else
        {
            if (token.type == T_INT)
            {
                cur_value = token.value;
                get_token();
            }

            e->items[e->num_items].value = cur_value;

            if (token.type != T_NAME)
                read_error("enum item name");
            e->items[e->num_items].name = strdup(token.string);
            e->items[e->num_items].cname = strcap(e->items[e->num_items].name);

            if (cur_value > e->max)
            {
                fprintf(stderr,
                        "fiddle: Error at line %d character %d.\n"
                        "Value %d for \"%s\" too great for %d bit enum.\n",
                        line_number, token.char_number,
                        cur_value, token.string, e->bits);
            }

            if (get_token() != T_SEMICOLON)
                read_error("';'");

            cur_value++;
            e->num_items++;
        }
    }

    return e;
}


value_t*
load_value()
{
    value_t *v;
    int count;

    v = (value_t*)malloc(sizeof(value_t));
    v->type = T_VALUE;

    if (get_token() != T_NAME)
        read_error("value name");
    v->name = strdup(token.string);
    v->cname = strcap(v->name);

    if (get_token() != T_OPEN)
        read_error("'{'");

    count = 4;
    v->items = (v_item_t*)malloc(sizeof(v_item_t) * count);
    v->num_items = 0;

    while (get_token() != T_CLOSE)
    {
        if (v->num_items == count)
        {
            count *= 2;
            v->items = (v_item_t*)realloc(v->items, sizeof(v_item_t) * count);
        }

        if (token.type != T_INT)
            read_error("value item size");
        v->items[v->num_items].bits = token.value;

        if (get_token() != T_INT)
            read_error("value item value");
        v->items[v->num_items].value = token.value;

        if (get_token() != T_NAME || strlen(token.string) != 1 ||
                (token.string[0] != 'b' &&
                 token.string[0] != 'd' &&
                 token.string[0] != 'h'))
            read_error("value item type");
        v->items[v->num_items].type = token.string[0];

        if (get_token() != T_NAME)
            read_error("value item name");
        v->items[v->num_items].name = strdup(token.string);
        v->items[v->num_items].cname = strcap(v->items[v->num_items].name);

        if (get_token() != T_SEMICOLON)
            read_error("';'");

        v->num_items++;
    }

    return v;
}


int
get_token()
{
    while (1)
    {
        if (rb_pos == -1)
        {
            if (fgets(read_buf, READ_BUF_SIZE, ifp) == NULL)
            {
                token.type = T_EOF;
                return T_EOF;
            }
            line_number++;
            rb_pos = 0;
        }

        while (read_buf[rb_pos] == ' ' || read_buf[rb_pos] == '\t')
            rb_pos++;

        if (read_buf[rb_pos] == '#' || read_buf[rb_pos] == '\n')
            rb_pos = -1;
        else
        {
            char first_char;
            int i;

            /*
             *  identify token
             */
            first_char = token.string[0] = read_buf[rb_pos++];
            i = 1;
            token.char_number = rb_pos;

            if (first_char >= '0' && first_char <= '9')
            {
                token.type = T_INT;
                if (first_char == '0' &&
                        (read_buf[rb_pos] == 'x' || read_buf[rb_pos] == 'X'))
                {
                    token.string[i++] = read_buf[rb_pos++];
                    while ((read_buf[rb_pos] >= '0' &&
                                read_buf[rb_pos] <= '9') ||
                            (read_buf[rb_pos] >= 'a' &&
                             read_buf[rb_pos] <= 'f') ||
                            (read_buf[rb_pos] >= 'A' &&
                             read_buf[rb_pos] <= 'F'))
                        token.string[i++] = read_buf[rb_pos++];
                    token.string[i] = '\0';
                    token.value = strtoul(token.string, NULL, 16);
                }
                else
                {
                    while (read_buf[rb_pos] >= '0' && read_buf[rb_pos] <= '9')
                        token.string[i++] = read_buf[rb_pos++];
                    token.string[i] = '\0';
                    token.value = atoi(token.string);
                }
            }
            else if ((first_char >= 'a' && first_char <= 'z') ||
                    (first_char >= 'A' && first_char <= 'Z') ||
                    first_char == '_')
            {
                while ((read_buf[rb_pos] >= 'a' && read_buf[rb_pos] <= 'z') ||
                        (read_buf[rb_pos] >= 'A' && read_buf[rb_pos] <= 'Z') ||
                        (read_buf[rb_pos] >= '0' && read_buf[rb_pos] <= '9') ||
                        read_buf[rb_pos] == '_')
                    token.string[i++] = read_buf[rb_pos++];
                token.string[i] = '\0';
                if (strcmp(token.string, "struct") == 0)
                    token.type = T_STRUCT;
                else if (strcmp(token.string, "union") == 0)
                    token.type = T_UNION;
                else if (strcmp(token.string, "enum") == 0)
                    token.type = T_ENUM;
                else if (strcmp(token.string, "value") == 0)
                    token.type = T_VALUE;
                else if (strcmp(token.string, "uint") == 0)
                    token.type = T_UINT_TYPE;
                else if (strcmp(token.string, "pad") == 0)
                    token.type = T_PAD_TYPE;
                else
                    token.type = T_NAME;
            }
            else
                switch (first_char)
                {
                    case '{':
                        token.type = T_OPEN;
                        token.string[1] = '\0';
                        break;
                    case '}':
                        token.type = T_CLOSE;
                        token.string[1] = '\0';
                        break;
                    case '+':
                        token.type = T_PLUS;
                        token.string[1] = '\0';
                        break;
                    case ';':
                        token.type = T_SEMICOLON;
                        token.string[1] = '\0';
                        break;
                    default:
                        token.type = T_UNKNOWN;
                        token.string[1] = '\0';
                        break;
                }

            return token.type;
        }
    }
}


void
read_error(char *expected)
{
    fprintf(stderr,
            "fiddle: Read Error:  "
            "Illegal token \"%s\" at line %d character %d.\n",
            token.string, line_number, token.char_number);
    fprintf(stderr, "Expected %s.\n", expected);
    exit(1);
}


void
store_file_h(char *fname)
{
    type_header_t *tmp;
    char def_name[80], *s1, *s2;
    int i;

    if ((ofp = fopen(fname, "w")) == NULL)
    {
        fprintf(stderr, "fiddle:  Unable to open \"%s\".\n", fname);
        exit(1);
    }

    /*
     *  write header
     */
    fprintf(ofp, "/*\n");
    fprintf(ofp, " *  %s\n", fname);
    fprintf(ofp, " *\n");
    fprintf(ofp, " *  NOTE: This is a generated file.  DO NOT HAND EDIT.\n");
    fprintf(ofp, " *\n");
    fprintf(ofp, " *  Generated from %s\n", infile);
    fprintf(ofp, " */\n");
    fprintf(ofp, "\n");

    /*
     *  make def_name
     */
    if ((s1 = strrchr(fname, '/')) == NULL)
        s1 = fname;

    if ((s2 = strrchr(s1, '\\')) == NULL)
        s2 = s1;

    if ('\\' == *s2 || '/' == *s2 )
        s2++;   /* skip slash */

    for (i = 0; s2[i] != '\0'; i++)
        if (s2[i] >= 'a' && s2[i] <= 'z')
            def_name[i+6] = s2[i] + ('A' - 'a');
        else
            def_name[i+6] = s2[i];
    def_name[0] = '_';
    def_name[1] = '_';
    def_name[2] = 'F';
    def_name[3] = 'D';
    def_name[4] = 'L';
    def_name[5] = '_';
    def_name[i+4] = '_';
    def_name[i+6] = '_';
    def_name[i+7] = '_';
    def_name[i+8] = '\0';

    fprintf(ofp, "#ifndef %s\n", def_name);
    fprintf(ofp, "#define %s\n", def_name);
    fprintf(ofp, "\n");
    fprintf(ofp, "\n");

#ifndef JTAGJET  /* XXX horti */
    //XXX Vimal:
    fprintf(ofp, "#ifdef EPPC\n");
    fprintf(ofp, "#include <private/fdl_assert.h>\n");
    fprintf(ofp, "#else\n");
    fprintf(ofp, "#define FDL_ASSERT(c) \n");
    fprintf(ofp, "#endif\n");
#endif /* !JTAGJET */

    /*
     *  Store structs, unions, and enums.
     */
    for (tmp = ordered_list; tmp != NULL; tmp = tmp->next)
    {
        switch (tmp->type)
        {
            case T_STRUCT:
                store_struct_h((struct_t*)tmp);
                break;
            case T_UNION:
                store_union_h((union_t*)tmp);
                break;
            case T_ENUM:
                store_enum_h((enum_t*)tmp);
                break;
            case T_VALUE:
                store_value_h((value_t*)tmp);
                break;
        }
    }

    fprintf(ofp, "\n");
    fprintf(ofp, "#endif /* %s */\n", def_name);

    fclose(ofp);
}

#ifdef JTAGJET
/* functions to generate def file for JTAGJet */
void
store_struct_header_def(FILE *fp, char *name, char *access,
        u32 address, u32 size)
{
  fprintf(fp,"\nRegister { Name = \"%s\"; Addr = 0x%x; Memory = \"\"; Size = %u; Access = %s; Help = \"%s\";\n", name, address, size, access, name);
}

void
store_struct_field_def(FILE *fp, field_t *field, u32 end_bit)
{
   int start_bit;
   char bitstr[32];
   
   start_bit = end_bit - field->size + 1;
   if ( end_bit == start_bit )
       sprintf(bitstr,"%d", end_bit);
   else
       sprintf(bitstr,"%d-%d", end_bit, start_bit);
   fprintf(fp, "\tField { Name = \"%s\"; Bits = \"%s\"; Help = \"%s\"; }\n",
           field->cname, bitstr, field->cname);
}

void
store_struct_trailer_def(FILE *fp)
{
  fprintf(fp,"\n}\n");
}

void
store_struct_def(FILE *fp, struct_t *s)
{
    int end_bit = 31;
    int i, sum; 
    store_struct_header_def(fp, s->cname, s->access, s->address, 
            s->size);
    for (i = s->num_fields - 1, sum = 0; i >= 0 ; i--) {
        store_struct_field_def(fp, &s->fields[i], end_bit);
        end_bit -= s->fields[i].size;
    }
    store_struct_trailer_def(fp);
}

void 
store_header_def(FILE *fp)
{
    fprintf(fp, "// This is a generated file.  DO NOT HAND EDIT.\n");
    fprintf(fp, "// Generated from %s\n\n", infile);
    fprintf(fp,"Ident = \"DefCpu\"; // CPU definition file - do not change this line!\n");
    fprintf(fp,"Register { Group = \"SYS\"; Help = \"System Registers\";}\n");
}

void
store_file_def(char *fname)
{
    type_header_t *tmp;
    char def_name[80], *s1, *s2;
    int i;

    if ((ofp = fopen(fname, "w")) == NULL) {
        fprintf(stderr, "fiddle:  Unable to open \"%s\".\n", fname);
        exit(1);
    }
    store_header_def(ofp);
    for (tmp = ordered_list; tmp != NULL; tmp = tmp->next) {
        switch (tmp->type) {
            case T_STRUCT:
                store_struct_def(ofp, (struct_t*)tmp);
                break;
            case T_UNION:
                store_union_h((union_t*)tmp);
                break;
            case T_ENUM:
                store_enum_h((enum_t*)tmp);
                break;
            case T_VALUE:
                store_value_h((value_t*)tmp);
                break;
        }
    }
    fprintf(ofp, "\n");
    fclose(ofp);
}

void
store_struct_header_h(FILE *fp, char *name, u32 address)
{
  fprintf(fp,"#define %s_ADDR   0x%x\n", name, address); 

}
#endif /* JTAGJET */

void
store_struct_h(struct_t *s)
{
    int i, j, sum;

    fprintf(ofp, "/*\n");
    fprintf(ofp, " *  %s struct\n", s->name);
    fprintf(ofp, " */\n");

#ifdef JTAGJET
    store_struct_header_h(ofp, s->cname, s->address);
#endif /* JTAGJET */
    for (i = 0, sum = 0; i < s->num_fields; i++)
        sum = store_struct_field_h(&s->fields[i], s->name, s->cname, sum, s->size);

    fprintf(ofp, "#define %s_TOTAL_SIZE\t%d\n",
            s->cname, s->total);
    if (s->total < s->size)
        fprintf(ofp, "#define %s_UNUSED_SIZE\t%d\n\n",
                s->cname, s->size - s->total);

    /*
     *  combiner define
     */
    fprintf(ofp, "#define %s(", s->cname);
    for (i = 0, j = 0; i < s->num_fields; i++)
        if (s->fields[i].type != T_PAD_TYPE)
        {
            fprintf(ofp, "%s%s",
                    (j)? ", " : "",
                    s->fields[i].name);
            j++;
        }
    fprintf(ofp, ") \\\n");
    for (i = 0, j = 0; i < s->num_fields; i++)
        if (s->fields[i].type != T_PAD_TYPE)
        {
            fprintf(ofp, "%s(((%s)(%s)) << %s_%s_SHIFT)",
                    (j)? " | \\\n\t " : "\t(",
                    uint_string(s->size),
                    s->fields[i].name, s->cname, s->fields[i].cname);
            j++;
        }
    fprintf(ofp, ")\n\n");
}


int
store_struct_field_h(field_t *f, char *name, char *cname, int start, int size)
{
    int i, sum;

    fprintf(ofp, "#define %s_%s_SIZE\t%d\n", cname, f->cname, f->size);
    fprintf(ofp, "#define %s_%s_SHIFT\t%d\n", cname, f->cname, start);
    if (size > 32)
    {
        fprintf(ofp, "#define %s_%s_MASK\t0x%08" AX64X AX64S "\n",
                cname, f->cname,
                (f->size < 64) ? ((AX64BIT0 << f->size) - 1) << start : AX64MASK);
    }
    else
    {
        fprintf(ofp, "#define %s_%s_MASK\t0x%08x\n",
                cname, f->cname,
                (f->size < 32) ? ((0x1 << f->size) - 1) << start : 0xffffffff);
    }
    fprintf(ofp,
            "#define %s_GET_%s(%s) \\\n"
            "\t((((%s)(%s)) & %s_%s_MASK) >> %s_%s_SHIFT)\n",
            cname,
            f->cname,
            name,
            uint_string(size),
            name,
            cname,
            f->cname,
            cname,
            f->cname);
    fprintf(ofp, "#define %s_SET_%s(%s, %s) { \\\n", 
            cname,
            f->cname,
            name,
            f->name);
    fprintf(ofp, "\tFDL_ASSERT(!((%s) & ~((1 << %s_%s_SIZE)-1))); \\\n",
            f->name,
            cname,
            f->cname);
    fprintf(ofp,
            "\t%s = (((%s)(%s)) & ~%s_%s_MASK) | (((%s)(%s)) << %s_%s_SHIFT);\\\n}\n",
            name,
            uint_string(size),
            name,
            cname,
            f->cname,
            uint_string(size),
            f->name,
            cname,
            f->cname);

    for (i = 0, sum = start; i < f->num_sub_fields; i++)
        sum = store_struct_field_h(&f->sub_fields[i], name, cname, sum, size);

    return start + f->size;
}



void
store_union_h(union_t *u)
{
    int i;

    fprintf(ofp, "/*\n");
    fprintf(ofp, " *  %s union\n", u->name);
    fprintf(ofp, " */\n");

    /*
     *  union
     */
    fprintf(ofp, "typedef union {\n");
    fprintf(ofp, "    %s val;\n", uint_string(u->size));
    for (i = 0; i < u->num_members; i++)
        fprintf(ofp, "    %s_t %s;\n",
                u->members[i].name, u->members[i].name);
    fprintf(ofp, "} %s_u;\n", u->name);
    fprintf(ofp, "\n");
}


void
store_enum_h(enum_t *e)
{
    int i, j;

    fprintf(ofp, "/*\n");
    fprintf(ofp, " *  %s enum\n", e->name);
    fprintf(ofp, " */\n");

    for (i = 0, j = 0; i <= e->max; i++)
        if (j < e->num_items && e->items[j].value == i)
        {
            fprintf(ofp, "#define %s\t0x%08x\n",
                    e->items[j].cname, e->items[j].value);
            j++;
        }
        else
            fprintf(ofp, "#define %s_UNUSED_%d\t0x%08x\n",
                    e->cname, i, i);
    fprintf(ofp, "\n");
}


void
store_value_h(value_t *v)
{
    int i;

    fprintf(ofp, "/*\n");
    fprintf(ofp, " *  %s value\n", v->name);
    fprintf(ofp, " */\n");

    for (i = 0; i < v->num_items; i++)
        switch (v->items[i].type)
        {
            case 'b':
            case 'h':
                fprintf(ofp, "#define %s\t0x%s\n",
                        v->items[i].cname,
                        hex_str(v->items[i].bits, v->items[i].value));
                break;
            case 'd':
                fprintf(ofp, "#define %s\t%d\n",
                        v->items[i].cname, v->items[i].value);
                break;
        }
    fprintf(ofp, "\n");
}


/*
 * Assembler output file.  This generates a file with an array,
 * each of whose items is structure containing the bit width, mask, and
 * shift information for each field.  It also contains an identifier
 * of the structure that it came from.
 * Identifiers for each structure are produced, as are identifiers for
 * each structure's fields (there's one identifier space for all fields of
 * all structures, so field names must be unique across structures).
 * It also produces a second array, each item of which contains a string
 * with an index into the first array and a value (the idea is that when
 * the string is encountered, it means to set the indicated field to
 * the indicated value.
 */
/*
 * XXX for now, we use 64 bit values for everything in case any structure
 * is more than 32 bits.  This could be slow.
 */
/*
 * XXX The enums must be of the form FIELD_VALUE, where FIELD is the
 * field name that the enum pertains to and VALUE is anything.  The
 * undescore must be present, but there is no error checking.
 *
 * XXX The addition of subfields has caused this format to become something
 * of a hack.  If subfields of a field are present, then the subfields
 * are used instead of the field.  This isn't recursive.
 */

void
store_file_ha(char *fname)
{
    type_header_t *tmp;
    struct_t *s;
    field_t *f;
    enum_t *e;
    value_t *v;
    char def_name[64], *s1, *s2;
    int i, j, k;
    int sum;
    int first;

    if ((ofp = fopen(fname, "w")) == NULL)
    {
        fprintf(stderr, "fiddle:  Unable to open \"%s\".\n", fname);
        exit(1);
    }

    /*
     *  write header
     */
    fprintf(ofp, "/*\n");
    fprintf(ofp, " *  %s\n", fname);
    fprintf(ofp, " *\n");
    fprintf(ofp, " *  NOTE: This is a generated file.  DO NOT HAND EDIT.\n");
    fprintf(ofp, " *\n");
    fprintf(ofp, " *  Generated from %s\n", infile);
    fprintf(ofp, " */\n");
    fprintf(ofp, "\n");

    /*
     *  make def_name
     */
    if ((s1 = strrchr(fname, '/')) == NULL)
        s1 = fname;

    if ((s2 = strrchr(s1, '\\')) == NULL)
        s2 = s1;

    if ('\\' == *s2 || '/' == *s2 )
        s2++;   /* skip slash */

    for (i = 0; s2[i] != '\0'; i++)
        if (s2[i] >= 'a' && s2[i] <= 'z')
            def_name[i+2] = s2[i] + ('A' - 'a');
        else
            def_name[i+2] = s2[i];
    def_name[0] = '_';
    def_name[1] = '_';
    def_name[i-1] = '_';
    def_name[i] = '_';
    def_name[i+1] = '\0';

    fprintf(ofp, "#ifndef %s\n", def_name);
    fprintf(ofp, "#define %s\n", def_name);
    fprintf(ofp, "\n");
    fprintf(ofp, "\n");

    /*
     *  Store symbolic structure names
     */
    j = 0;
    for (tmp = ordered_list; tmp != NULL; tmp = tmp->next)
    {
        if (tmp->type == T_STRUCT)
        {
            s = (struct_t*)tmp;
            fprintf(ofp, "#define S_%s\t%d\n", s->cname, j++);
        }
    }
    fprintf(ofp,"\n\n#define NSTRUCTS %d\n\n", j);
#ifdef ATI_MSVC_COMPILER
    fprintf(ofp,"typedef __int64 UINST[NSTRUCTS];\n\n");
#else
    fprintf(ofp,"typedef long long UINST[NSTRUCTS];\n\n");
#endif

    /*
     *  Store symbolic field names
     */
    j = 0;
    for (tmp = ordered_list; tmp != NULL; tmp = tmp->next)
    {
        if (tmp->type == T_STRUCT)
        {
            s = (struct_t*)tmp;
            for (i=0; i<s->num_fields; i++)
            {
                if (s->fields[i].num_sub_fields == 0)
                    fprintf(ofp, "#define %s\t%d\n", s->fields[i].cname, j++);
                else
                {
                    for (k=0; k<s->fields[i].num_sub_fields; k++)
                        fprintf(ofp, "#define %s\t%d\n",
                                s->fields[i].sub_fields[k].cname, j++);
                }
            }
        }
    }
    fprintf(ofp,"\n#define NFIELDS %d\n\n", j);

    fprintf(ofp, "#define SET_FIELD_VALUE(u, id, value) \\\n");
#ifdef ATI_MSVC_COMPILER
    fprintf(ofp,"\t\tu[uf[id].sId] = (u[uf[id].sId] & ~uf[id].mask) | (((__int64)value)<<uf[id].shift)\n");
#else
    fprintf(ofp,"\t\tu[uf[id].sId] = (u[uf[id].sId] & ~uf[id].mask) | (((long long)value)<<uf[id].shift)\n");
#endif
    fprintf(ofp, "#define GET_FIELD_VALUE(u, id) \\\n");
    fprintf(ofp, "\t\t((u[uf[id].sId] & uf[id].mask) >> uf[id].shift)\n\n");

    /*
     *  Store struct field data
     */
    fprintf(ofp,"struct ufield {\nchar fieldId;\nchar nbits;\nchar sId;\n");
#ifdef ATI_MSVC_COMPILER
    fprintf(ofp,"char shift;\nunsigned __int64 mask;\n};\n\n");
#else
    fprintf(ofp,"char shift;\nunsigned long long mask;\n};\n\n");
#endif
    fprintf(ofp,"typedef struct ufield UFIELD;\n\n");
    fprintf(ofp,"#ifdef UFIELD_INIT\n");
    fprintf(ofp,"UFIELD uf[NFIELDS] = {\n");

    for (tmp = ordered_list; tmp != NULL; tmp = tmp->next)
    {
        if (tmp->type == T_STRUCT)
        {
            s = (struct_t*)tmp;
            sum = 0;
            for (i=0; i<s->num_fields; i++)
            {
                if (s->fields[i].num_sub_fields == 0)
                {
                    fprintf(ofp, "  { %s, %d, S_%s, %d, 0x%016" AX64X AX64S " },\n",
                            s->fields[i].cname, s->fields[i].size, s->cname, sum,
                            (s->fields[i].size < 64) ?
                            ((AX64BIT0 << s->fields[i].size) - 1) << sum :
                            AX64MASK);
                    sum += s->fields[i].size;
                }
                else
                {
                    for (k=0; k<s->fields[i].num_sub_fields; k++)
                    {
                        f = &(s->fields[i].sub_fields[k]);
                        fprintf(ofp, "  { %s, %d, S_%s, %d, 0x%016" AX64X AX64S " },\n",
                                f->cname, f->size, s->cname, sum,
                                (f->size < 64) ?
                                ((AX64BIT0 << f->size) - 1) << sum : AX64MASK);
                        sum += f->size;
                    }
                }
            }
        }
    }
    fprintf(ofp,"};\n");
    fprintf(ofp, "#endif /* UFIELD_INIT */\n\n");
    fprintf(ofp, "extern UFIELD uf[];\n\n");

    for (tmp = ordered_list; tmp != NULL; tmp = tmp->next)
    {
        switch (tmp->type)
        {
            case T_STRUCT:
                break;
            case T_UNION:
                fprintf(stderr,
                        "fiddle: unions ignored in ha output: %s\n",
                        ((union_t*)tmp)->name);
                break;
            case T_ENUM:
                e = (enum_t*)tmp;
                for (i = 0; i < e->num_items; i++)
                    fprintf(ofp, "#define %s\t0x%x\n",
                            e->items[i].cname, e->items[i].value);
                fprintf(ofp,"\n");
                break;
            case T_VALUE:
                v = (value_t*)tmp;
                for (i = 0; i < v->num_items; i++)
                    fprintf(ofp, "#define %s\t%d\n",
                            v->items[i].cname, v->items[i].value);
                fprintf(ofp, "\n");
                break;
        }
    }
    fprintf(ofp,"#ifdef ASSEMBLER\n");
    /*
     * Store structure widths
     */
    fprintf(ofp,"int sWidths[NSTRUCTS] = {\n\t");
    first = 1;
    for (tmp = ordered_list; tmp != NULL; tmp = tmp->next)
    {
        if (tmp->type == T_STRUCT)
        {
            s = (struct_t*)tmp;
            if (first)
                fprintf(ofp, "%d", s->size);
            else
                fprintf(ofp, ", %d", s->size);
            first = 0;
        }
    }
    fprintf(ofp," };\n\n");

    /*
     * Define token structure
     */
    fprintf(ofp,"struct token {\n");
    fprintf(ofp,"char token[30];\nint fieldId;\nint fieldValue;\n");
    fprintf(ofp,"};\n\ntypedef struct token TOKEN;\n\n");
    fprintf(ofp,"TOKEN tk[] = {\n");

    for (tmp = ordered_list; tmp != NULL; tmp = tmp->next)
    {
        switch(tmp->type) {
            case T_ENUM:
                e = (enum_t*)tmp;
                for (i = 0, j = 0; i <= e->max; i++)
                    if (j < e->num_items && e->items[j].value == i)
                    {
                        fprintf(ofp, "{\"%s\", %s, %s},\n",
                                strlower(e->items[j].cname),
                                pre_underscore(e->items[j].cname),
                                e->items[j].cname);
                        j++;
                    }
                break;
            case T_VALUE:
                v = (value_t*)tmp;
                for (i = 0; i < v->num_items; i++)
                {
                    fprintf(ofp, "{\"%s\", %s, %s},\n",
                            strlower(v->items[i].cname),
                            pre_underscore(v->items[i].cname),
                            v->items[i].cname);
                }
                break;
        }
    }
    fprintf(ofp,"};\n");
    fprintf(ofp, "#endif /* ASSEMBLER */\n");

    fprintf(ofp, "#endif /* %s */\n", def_name);

    fclose(ofp);
}


/* Used in output_ha, above
 * XXX Ugly hack to extract field name as the part of the
 * enum/value name that's before the underscore!!!
 */
char *
pre_underscore(char *s)
{
    char *p;
    char *x = strdup(s);
    p = strchr(x, '_');
    if (p != NULL)
        *p = '\0';
    return x;
}


void
store_file_vpp(char *fname)
{
    type_header_t *tmp;

    if ((ofp = fopen(fname, "w")) == NULL)
    {
        fprintf(stderr, "fiddle:  Unable to open \"%s\".\n", fname);
        exit(1);
    }

    /*
     *  write header
     */
    fprintf(ofp, "/*\n");
    fprintf(ofp, " *  %s\n", fname);
    fprintf(ofp, " *\n");
    fprintf(ofp, " *  NOTE: This is a generated file.  DO NOT HAND EDIT.\n");
    fprintf(ofp, " *\n");
    fprintf(ofp, " *  Generated from %s\n", infile);
    fprintf(ofp, " */\n");
    fprintf(ofp, "\n");
    fprintf(ofp, "\n");

    /*
     *  Store structs, unions, and enums.
     */
    for (tmp = ordered_list; tmp != NULL; tmp = tmp->next)
    {
        switch (tmp->type)
        {
            case T_STRUCT:
                store_struct_vpp((struct_t*)tmp);
                break;
            case T_UNION:
                store_union_vpp((union_t*)tmp);
                break;
            case T_ENUM:
                store_enum_vpp((enum_t*)tmp);
                break;
            case T_VALUE:
                store_value_vpp((value_t*)tmp);
                break;
        }
    }

    fclose(ofp);
}

void
store_file_pcf(char *fname)
{
    type_header_t *tmp;

    if ((ofp = fopen(fname, "w")) == NULL)
    {
        fprintf(stderr, "fiddle:  Unable to open \"%s\".\n", fname);
        exit(1);
    }

    /*
     *  write header
     */
    fprintf(ofp, " #  NOTE: This is a generated file.  DO NOT HAND EDIT.\n");
    fprintf(ofp, " #\n");
    fprintf(ofp, " #  Generated from %s\n", infile);
    fprintf(ofp, " #\n");
    fprintf(ofp, "\n");
    fprintf(ofp, "\n");

    /*
     *  Store structs, unions, and enums.
     */
    for (tmp = ordered_list; tmp != NULL; tmp = tmp->next)
    {
        switch (tmp->type)
        {
            case T_STRUCT:
                store_struct_pcf((struct_t*)tmp);
                break;
            case T_UNION:
                //		store_union_pcf((union_t*)tmp);
                break;
            case T_ENUM:
                //		store_enum_pcf((enum_t*)tmp);
                break;
            case T_VALUE:
                //		store_value_vpp((value_t*)tmp);
                break;
        }
    }

    fclose(ofp);
}


void
store_struct_vpp(struct_t *s)
{
    int i, sum;

    fprintf(ofp, "/*\n");
    fprintf(ofp, " *  %s struct\n", s->name);
    fprintf(ofp, " */\n");

    /*
     *  field defines
     */
    for (i = 0, sum = 0; i < s->num_fields; i++)
        sum = store_struct_field_vpp(&s->fields[i], s->cname, sum);

    fprintf(ofp, ";$%s_TOTAL_SIZE = \t\"32'd%d\";\n",
            s->cname, s->total);
    fprintf(ofp, ";$%s_TOTAL_RANGE = \t\"%d:0\";\n",
            s->cname, s->total - 1);

    fprintf(ofp, "\n");
}

void
store_struct_pcf(struct_t *s)
{
    int i, sum;

    fprintf(ofp, "#\n");
    fprintf(ofp, "#  %s struct\n", s->name);
    fprintf(ofp, "#\n");

    // print header
    fprintf(ofp, "DEFINE REGFLD %s {\n",s->cname);

    /*
     *  field defines
     */
    for (i = 0, sum = 0; i < s->num_fields; i++)
        sum = store_struct_field_pcf(&s->fields[i], s->cname, sum, s->pad_size);

    fprintf(ofp, "}\n");
    fprintf(ofp, "\n");
}


int
store_struct_field_pcf(field_t *f, char *cname, int start, int total_size)
{
    int i, sum;

    fprintf(ofp, "%s   %d   %d\n",
            f->cname, (total_size - 1) - start - f->size+1, f->size);

    for (i = 0, sum = start; i < f->num_sub_fields; i++)
        sum = store_struct_field_pcf(&f->sub_fields[i], cname, sum, total_size);

    return start + f->size;
}

int
store_struct_field_vpp(field_t *f, char *cname, int start)
{
    int i, sum;

    fprintf(ofp, ";$%s_%s = \t\"%d:%d\";\n",
            cname, f->cname, start + f->size - 1, start);

    for (i = 0, sum = start; i < f->num_sub_fields; i++)
        sum = store_struct_field_vpp(&f->sub_fields[i], cname, sum);

    return start + f->size;
}


void
store_union_vpp(union_t *u)
{
}


void
store_enum_vpp(enum_t *e)
{
    int i, j;

    fprintf(ofp, "/*\n");
    fprintf(ofp, " *  %s enum\n", e->name);
    fprintf(ofp, " */\n");

    for (i = 0, j = 0; i <= e->max; i++)
        if (j < e->num_items && e->items[j].value == i)
        {
            fprintf(ofp, ";$%s = \t\"%d'b%s\";\n",
                    e->items[j].cname, e->bits,
                    bits_str(e->bits, e->items[j].value));
            j++;
        }
        else
            fprintf(ofp, ";$%s_UNUSED_%d = \t\"%d'b%s\";\n",
                    e->cname, i, e->bits, bits_str(e->bits, i));
    fprintf(ofp, "\n");
}


void
store_value_vpp(value_t *v)
{
    int i;

    fprintf(ofp, "/*\n");
    fprintf(ofp, " *  %s value\n", v->name);
    fprintf(ofp, " */\n");

    for (i = 0; i < v->num_items; i++)
        switch (v->items[i].type)
        {
            case 'b':
                fprintf(ofp, ";$%s = \t\"%d'b%s\";\n",
                        v->items[i].cname, v->items[i].bits,
                        bits_str(v->items[i].bits, v->items[i].value));
                break;
            case 'd':
                fprintf(ofp, ";$%s = \t\"%d'd%d\";\n",
                        v->items[i].cname, v->items[i].bits,
                        v->items[i].value);
                break;
            case 'h':
                fprintf(ofp, ";$%s = \t\"%d'h%s\";\n",
                        v->items[i].cname, v->items[i].bits,
                        hex_str(v->items[i].bits, v->items[i].value));
                break;
        }
    fprintf(ofp, "\n");
}


void
store_file_v(char *fname)
{
    type_header_t *tmp;
    char *def_name;

    if ((ofp = fopen(fname, "w")) == NULL)
    {
        fprintf(stderr, "fiddle:  Unable to open \"%s\".\n", fname);
        exit(1);
    }

    def_name = make_def_name(fname);

    fprintf(ofp, "`ifdef %s\n", def_name);
    fprintf(ofp, "`else\n");
    fprintf(ofp, "`define %s\n", def_name);

    /*
     *  write header
     */
    fprintf(ofp, "/*\n");
    fprintf(ofp, " *  %s\n", fname);
    fprintf(ofp, " *\n");
    fprintf(ofp, " *  NOTE: This is a generated file.  DO NOT HAND EDIT.\n");
    fprintf(ofp, " *\n");
    fprintf(ofp, " *  Generated from %s\n", infile);
    fprintf(ofp, " */\n");
    fprintf(ofp, "\n");
    fprintf(ofp, "\n");

    /*
     *  Store structs, unions, and enums.
     */
    for (tmp = ordered_list; tmp != NULL; tmp = tmp->next)
    {
        switch (tmp->type)
        {
            case T_STRUCT:
                store_struct_v((struct_t*)tmp);
                break;
            case T_UNION:
                store_union_v((union_t*)tmp);
                break;
            case T_ENUM:
                store_enum_v((enum_t*)tmp);
                break;
            case T_VALUE:
                store_value_v((value_t*)tmp);
                break;
        }
    }

    fprintf(ofp, "`endif // %s\n", def_name);
    fclose(ofp);
}


void
store_struct_v(struct_t *s)
{
    int i, sum;

    fprintf(ofp, "/*\n");
    fprintf(ofp, " *  %s struct\n", s->name);
    fprintf(ofp, " */\n");

    /*
     *  field defines
     */
    for (i = 0, sum = 0; i < s->num_fields; i++)
        sum = store_struct_field_v(&s->fields[i], s->cname, sum);

    fprintf(ofp, "`define %s_TOTAL_SIZE\t32'd%d\n",
            s->cname, s->total);
    fprintf(ofp, "`define %s_TOTAL_RANGE\t%d:0\n",
            s->cname, s->total - 1);

    fprintf(ofp, "\n");
}


int
store_struct_field_v(field_t *f, char *cname, int start)
{
    int i, sum;

    fprintf(ofp, "`define %s_%s\t%d:%d\n",
            cname, f->cname, start + f->size - 1, start);

    for (i = 0, sum = start; i < f->num_sub_fields; i++)
        sum = store_struct_field_v(&f->sub_fields[i], cname, sum);

    return start + f->size;
}


void
store_union_v(union_t *u)
{
}


void
store_enum_v(enum_t *e)
{
    int i, j;

    fprintf(ofp, "/*\n");
    fprintf(ofp, " *  %s enum\n", e->name);
    fprintf(ofp, " */\n");

    for (i = 0, j = 0; i <= e->max; i++)
        if (j < e->num_items && e->items[j].value == i)
        {
            fprintf(ofp, "`define %s\t%d'b%s\n",
                    e->items[j].cname, e->bits,
                    bits_str(e->bits, e->items[j].value));
            j++;
        }
        else
            fprintf(ofp, "`define %s_UNUSED_%d\t%d'b%s\n",
                    e->cname, i, e->bits, bits_str(e->bits, i));
    fprintf(ofp, "\n");
}


void
store_value_v(value_t *v)
{
    int i;

    fprintf(ofp, "/*\n");
    fprintf(ofp, " *  %s value\n", v->name);
    fprintf(ofp, " */\n");

    for (i = 0; i < v->num_items; i++)
        switch (v->items[i].type)
        {
            case 'b':
                fprintf(ofp, "`define %s\t%d'b%s\n",
                        v->items[i].cname, v->items[i].bits,
                        bits_str(v->items[i].bits, v->items[i].value));
                break;
            case 'd':
                fprintf(ofp, "`define %s\t%d'd%d\n",
                        v->items[i].cname, v->items[i].bits,
                        v->items[i].value);
                break;
            case 'h':
                fprintf(ofp, "`define %s\t%d'h%s\n",
                        v->items[i].cname, v->items[i].bits,
                        hex_str(v->items[i].bits, v->items[i].value));
                break;
        }
    fprintf(ofp, "\n");
}


void
store_file_mch(char *fname)
{
    type_header_t *tmp;

    if ((ofp = fopen(fname, "w")) == NULL)
    {
        fprintf(stderr, "fiddle:  Unable to open \"%s\".\n", fname);
        exit(1);
    }

    /*
     *  write header
     */
    fprintf(ofp, "/*\n");
    fprintf(ofp, " *  %s\n", fname);
    fprintf(ofp, " *\n");
    fprintf(ofp, " *  NOTE: This is a generated file.  DO NOT HAND EDIT.\n");
    fprintf(ofp, " *\n");
    fprintf(ofp, " *  Generated from %s\n", infile);
    fprintf(ofp, " */\n");
    fprintf(ofp, "\n");
    fprintf(ofp, "\n");

    /*
     *  Store structs, unions, and enums.
     */
    for (tmp = ordered_list; tmp != NULL; tmp = tmp->next)
    {
        switch (tmp->type)
        {
            case T_STRUCT:
                store_struct_mch((struct_t*)tmp);
                break;
            case T_UNION:
                store_union_mch((union_t*)tmp);
                break;
            case T_ENUM:
                store_enum_mch((enum_t*)tmp);
                break;
            case T_VALUE:
                store_value_mch((value_t*)tmp);
                break;
        }
    }

    fclose(ofp);
}


void
store_struct_mch(struct_t *s)
{
    int i, sum;

    fprintf(ofp, "/*\n");
    fprintf(ofp, " *  %s struct\n", s->name);
    fprintf(ofp, " */\n");

    /*
     *  field defines
     */
    for (i = 0, sum = 0; i < s->num_fields; i++)
        sum = store_struct_field_mch(&s->fields[i], s->cname, sum);

    fprintf(ofp, "#define %s_TOTAL_SIZE\t32'd%d\n",
            s->cname, s->total);
    fprintf(ofp, "#define %s_TOTAL_RANGE\t%d:0\n",
            s->cname, s->total - 1);

    fprintf(ofp, "\n");
}


int
store_struct_field_mch(field_t *f, char *cname, int start)
{
    int i, sum;

    fprintf(ofp, "#define %s_%s\t%d:%d\n",
            cname, f->cname, start + f->size - 1, start);

    for (i = 0, sum = start; i < f->num_sub_fields; i++)
        sum = store_struct_field_mch(&f->sub_fields[i], cname, sum);

    return start + f->size;
}


void
store_union_mch(union_t *u)
{
}


void
store_enum_mch(enum_t *e)
{
    int i, j;

    fprintf(ofp, "/*\n");
    fprintf(ofp, " *  %s enum\n", e->name);
    fprintf(ofp, " */\n");

    for (i = 0, j = 0; i <= e->max; i++)
        if (j < e->num_items && e->items[j].value == i)
        {
            fprintf(ofp, "#define %s\t%d'b%s\n",
                    e->items[j].cname, e->bits,
                    bits_str(e->bits, e->items[j].value));
            j++;
        }
        else
            fprintf(ofp, "#define %s_UNUSED_%d\t%d'b%s\n",
                    e->cname, i, e->bits, bits_str(e->bits, i));
    fprintf(ofp, "\n");
}


void
store_value_mch(value_t *v)
{
    int i;

    fprintf(ofp, "/*\n");
    fprintf(ofp, " *  %s value\n", v->name);
    fprintf(ofp, " */\n");

    for (i = 0; i < v->num_items; i++)
        switch (v->items[i].type)
        {
            case 'b':
                fprintf(ofp, "#define %s\t%d'b%s\n",
                        v->items[i].cname, v->items[i].bits,
                        bits_str(v->items[i].bits, v->items[i].value));
                break;
            case 'd':
                fprintf(ofp, "#define %s\t%d'd%d\n",
                        v->items[i].cname, v->items[i].bits,
                        v->items[i].value);
                break;
            case 'h':
                fprintf(ofp, "#define %s\t%d'h%s\n",
                        v->items[i].cname, v->items[i].bits,
                        hex_str(v->items[i].bits, v->items[i].value));
                break;
        }
    fprintf(ofp, "\n");
}


char*
strcap(char *s)
{
    char *c;
    int i, n;

    n = strlen(s);
    c = (char*)malloc(n+1);

    for (i = 0; i < n; i++)
        if (s[i] >= 'a' && s[i] <= 'z')
            c[i] = s[i] + 'A' - 'a';
        else
            c[i] = s[i];

    c[n] = '\0';

    return c;
}


char
*strlower(char *s)
{
    char *c;
    int i, n;

    n = strlen(s);
    c = (char*)malloc(n+1);

    for (i = 0; i < n; i++)
        if (s[i] >= 'A' && s[i] <= 'Z')
            c[i] = s[i] + 'a' - 'A';
        else
            c[i] = s[i];

    c[n] = '\0';

    return c;
}


void
parse_args(int argc, char **argv)
{
    if (argc < 2)
        usage();

    infile = argv[1];

    outfiles = argv + 2;
    num_outfiles = argc - 2;
}


void
usage(void)
{
    fprintf(stderr,
            "usage: fiddle infile.fdl [outfile.h] [outfile.ha] [outfile.hw?]\n");
    exit(1);
}


char *
bits_str(int bits, int value)
{
    static char buf[33];
    int i, j;

    for (i = 0, j = bits-1; i < bits; i++, j--)
        if (value & (0x1 << j))
            buf[i] = '1';
        else
            buf[i] = '0';

    buf[i] = '\0';

    return buf;
}


char *
hex_str(int bits, int value)
{
    static char buf[9];
    int hex_chars;

    hex_chars = bits / 4 + ((bits % 4) ? 1 : 0);

    switch (hex_chars)
    {
        case 0:
        case 1:
            sprintf(buf, "%x", value);
            break;
        case 2:
            sprintf(buf, "%02x", value);
            break;
        case 3:
            sprintf(buf, "%03x", value);
            break;
        case 4:
            sprintf(buf, "%04x", value);
            break;
        case 5:
            sprintf(buf, "%05x", value);
            break;
        case 6:
            sprintf(buf, "%06x", value);
            break;
        case 7:
            sprintf(buf, "%07x", value);
            break;
        case 8:
            sprintf(buf, "%08x", value);
            break;
    }

    return buf;
}

const char *
uint_string(int size)
{
    if (size > 32)
        return uint64String;
    else
        return uint32String;
}


char *make_def_name(const char *fname)
{
    static char def_name[PATH_MAX];
    char *s1, *s2;
    int i;

    def_name[0] = '\0';

    if ((s1 = strrchr(fname, '/')) == NULL)
        s1 = (char *)fname;

    if ((s2 = strrchr(s1, '\\')) == NULL)
        s2 = s1;

    if ('\\' == *s2 || '/' == *s2 )
        s2++;   /* skip slash */

    for (i = 0; s2[i] != '\0'; i++)
        if (s2[i] >= 'a' && s2[i] <= 'z')
            def_name[i+6] = s2[i] + ('A' - 'a');
        else
            def_name[i+6] = s2[i];
    def_name[0] = '_';
    def_name[1] = '_';
    def_name[2] = 'F';
    def_name[3] = 'D';
    def_name[4] = 'L';
    def_name[5] = '_';
    def_name[i+4] = '_';
    def_name[i+6] = '_';
    def_name[i+7] = '_';
    def_name[i+8] = '\0';

    // fprintf(stderr, ">%s<\n", &def_name[0]);

    return &def_name[0];
}
