mkpak.c 2.72 KB
#include "bbclocal.h"
#include <stdio.h>

char block[BB_FL_BLOCK_SIZE];

typedef struct {
    u32 cid;
    u32 cont_id;
} binding_t;

int
main(int argc, char **argv)
{
    char *infile = NULL, *outfile = NULL;
    int rv = -1;
    char line[256]; 
    binding_t cp[MAX_CONT_PAK];
    binding_t *p;
    unsigned int count, cid, cont_id;
    FILE *fin, *fout;

    // Parse arguments
    while ((rv = getopt(argc, argv, "i:o:")) != -1) {
        switch (rv) {
        case 'i':
            infile = optarg;
            break;
        case 'o':
            outfile = optarg;
            break;
        default:
            printf("Usage: mkpak [-i file] [-o outfile]\n");
            goto out;
        }
    }

    for (count = 0; count < MAX_CONT_PAK; ++count) {
        cp[count].cid = 0;
        cp[count].cont_id = -1;
    }

    // Figure out input file
    if (infile == NULL) {
        fprintf(stderr, "Please enter the controller pak bindings in the format\n");
        fprintf(stderr, " pakid(0-11) cid(hex) cont_id(0-3)\n");
        fprintf(stderr, " (one entry per line)\n");
        fprintf(stderr, "---------------------\n");
        fin = stdin;
    }
    else {
        fin = fopen(infile, "r");
        if (fin == NULL) {
            sprintf(line, "Cannot open input file %s", infile);
            perror(line);
            goto out;
        }        
    }

    // Figure out output file
    if (outfile == NULL) {
        fout = stdout;
    }
    else {
        fout = fopen(outfile, "wb");
        if (fout == NULL) {
            sprintf(line, "Cannot open output file %s", outfile);
            perror(line);
            if (infile) {
                fclose(fin);
            }
            goto out;
        }
    }

    // Read input file
    while (fgets(line, sizeof line, fin))
    {
        if (sscanf(line, "%u %x %u", &count, &cid, &cont_id) < 3) {
            fprintf(stderr, "WARNING: Illegal format\n");
            continue;
        }
        
        if ((count < 0) || (count >= MAX_CONT_PAK)) {
            fprintf(stderr, "WARNING: pak id should be between 0 to %d\n",
                    MAX_CONT_PAK-1);
            continue;
        }

        if ((cont_id < 0) || (cont_id >= 4)) {
            fprintf(stderr, "WARNING: cont id should be between 0 to 3\n");
            continue;
        }

        cp[count].cid = cid;
        cp[count].cont_id = cont_id;
    }

    // Write binding file
    memset(block, 0x0, sizeof block);
    p = (binding_t *) block;
    for (count = 0; count < MAX_CONT_PAK; ++count) {
        p[count].cid = htonl(cp[count].cid);
        p[count].cont_id = htonl(cp[count].cont_id);
    }

    fwrite(block, 1, sizeof block, fout);
    rv = 0;

    if (infile) fclose(fin);
    if (outfile) fclose(fout);

out:
    return rv;
}