sbc.c 2.46 KB
#include "sbc.h"

char usage[] = "-o outfile file0 file1 ....";

main(int argc, char *argv[])


{
    extern char         *optarg;
    extern int          optind;
    s32
        i,
        c,
        nfiles,
        sizeSbank,
        bytes,
        nextPoint,
        extraBytes,
        seqLen;
    
    char
        buffer[BLOCK_SIZE],
        *progname = argv[0],
        *ofilename = 0;

    FILE
        *ofile,
        *ifile;
    
    ALSeqFile
        *sbank;

    if (argc<2){
        fprintf(stderr,"Usage: %s %s\n",progname, usage);
        exit(1);
    }

    while ((c = getopt(argc, argv, "o:")) != EOF) {        
        switch (c) {
            case 'o':
                ofilename = optarg;
                break;
        }
    }

    if (ofilename == NULL){
        ofile = fopen("tst.sbk", "w");
        nfiles = argc - 1;
    } else {
        if ((ofile = fopen(ofilename, "w")) == NULL){
            fprintf(stderr,"%s: could not open [%s] for output\n",progname, ofilename);
            exit(1);
        }
        nfiles = argc - 3;
    }
    sizeSbank = sizeof(ALSeqFile) + (nfiles - 1)*sizeof(ALSeqData);
    sbank = (ALSeqFile *) malloc(sizeSbank);

    /*
     * Write the header chunk
     */
    fwrite(sbank, sizeof(char), sizeSbank, ofile);
    nextPoint = sizeSbank;
    for (i=0; i<nfiles; i++){
        if ((ifile = fopen(argv[optind+i], "r")) == NULL){
            fprintf(stderr,"%s: could not open [%s] for input\n",progname, argv[optind+i]);
            exit(1);
        }
        
        /*
         * Copy input to output
         */
        seqLen = 0;
        bytes = BLOCK_SIZE;
        while(bytes == BLOCK_SIZE) {
            bytes = fread(buffer, sizeof(char), BLOCK_SIZE, ifile);
            fwrite(buffer, sizeof(char), bytes, ofile);
            seqLen += bytes;
        }

        /*
         * Fix up the pointer in the header
         */
        sbank->seqArray[i].offset = (u8 *) nextPoint;
        sbank->seqArray[i].len = seqLen;

        /*
         * Pad the sequence to 4 byte multiple
         */
        extraBytes = 0;
        if (seqLen & 0x3)
            extraBytes = 4 - seqLen & 0x3;
        fwrite(buffer, sizeof(char), extraBytes, ofile);
        
        nextPoint += seqLen + extraBytes;
        fclose(ifile);
    }

    /*
     * Write the final header
     */
    sbank->revision = AL_SEQBANK_VERSION;
    sbank->seqCount = nfiles;
    fseek(ofile, 0, SEEK_SET);
    fwrite(sbank, sizeof(char), sizeSbank, ofile);
    fclose(ofile);
}