//
// MUX
//
// An Objective-C class for simulating a MUX.
//


#import "MUX.h"
#import "compmath.h"


@implementation MUX


- initNumBits:(int)nbits				// Number of bits.
	numselectbits:(int)nselbits			// Number of select bits.
	select:selnode					// Node of select lines.
	sources:(id *)sourceArray			// Array of sources.
	out:outnode					// Output node.
{
    int 	i;
    char	tempstr[50];
    
    [super init];

    if(nbits < 1) {
        fprintf(stderr, "MUX: Attempt to create a MUX with less than one bit per input!\n");
	exit(-1);
    }

    numbits = nbits;
    
    if(nselbits < 1) {
        fprintf(stderr, "MUX: Attempt to create a MUX with less than one select bit!\n");
	exit(-1);
    }
    
    numselectbits = nselbits;
    numinputs = pow2(nselbits);
    
    INITDEVTYPE("MUX");
    
    TESTNODE("SELECT", selnode, numselectbits);
    TESTNODE("OUT", outnode, numbits);
    for(i = 0; i < numinputs; i++) {
        sprintf(tempstr, "IN[%d]", i);
        TESTNODE(tempstr, sourceArray[i], numbits);
    }
    
    INS = (id *)malloc(numinputs * sizeof(id));
    
    SELECT = selnode;
    OUT = outnode;
    for(i = 0; i < numinputs; i++) {
        INS[i] = sourceArray[i];
//	fprintf(stderr, "MUX: Input %d is %p.\n", i, INS[i]);
    }
    
    return self;
}


- free
{
    free(INS);
    
    return [super free];
}


- cycle
{
    bit *selbits = [SELECT getBits];
    int i, index;
    
    index = 0;
    
    for(i = 0; i < numselectbits; i++) {
        index = index * 2;				// Shift index right;
	index = index + selbits[i];			// Add current bit;
    }
    
//    fprintf(stdout, "MUX: Putting input %d (", index);
//    [INS[index] dumpBinaryToFile:stdout];
//    fprintf(stdout, ") on output.\n");
    
    [OUT setBits:[INS[index] getBits]];			// Put appropriate input on OUT.
    
    return self;
}


@end


//
// End of file.
//