//
// Node
//
// An Objective-C class for nodes for connecting signals in a computer simulation.
//


#import "Node.h"


char	NODE_TESTDEVTYPE[255];				// For node size testing.


void TESTNODE(char *name, id nd, int num)
{
    if(nd == nil) {
        fprintf(stderr, "%s: Node %s nil!\n", NODE_TESTDEVTYPE, name);
	exit(-2);
    }
    
    if([nd numbits] != num) {
        fprintf(stderr, "%s: Node %s wrong size (%d bits)! Should be %d bits!\n",
		NODE_TESTDEVTYPE, name, [nd numbits], num);
	exit(-3);
    }
    
    return;
}


@implementation Node


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

    numbits = nbits;
    
    data = (bit *)malloc(numbits * sizeof(bit));
    
    for(i = 0; i < numbits; i++)			// Initialize the node to 0.
        data[i] = 0;
    
    return self;
}


- initNumBits:(int)nbits contents:(bit *)cont
{
    int i;
    
    [self initNumBits:nbits];
    
    for(i = 0; i < numbits; i++)
        data[i] = (cont[i] != 0);			// Force to be Boolean.
	
    return self;
}


- initNumBits:(int)nbits fill:(bit)cont
{
    int i;
    
    [self initNumBits:nbits];
    
    for(i = 0; i < numbits; i++)
        data[i] = (cont != 0);				// Force to be Boolean.
	
    return self;
}


- free
{
    free(data);
    
    return self;
}


- (int)numbits
{
    return numbits;
}


- setBits:(bit *)someData
{
    int i;
    
    for(i = 0; i < numbits; i++)
        data[i] = someData[i];

    return self;
}


- (bit *)getBits
{
    return data;
}


- dumpBinaryToFile:(FILE *)aFile
{
    int i;
    
    for(i = (numbits - 1); i >= 0; i--) {		// Dump binary form.
        fprintf(aFile, "%d", data[i]);
    }
    
    return self;
}


- dumpHexToFile:(FILE *)aFile
{
    int i;
    int sum;
    
    fprintf(aFile, "0x");
    sum = 0;
    for(i = (numbits - 1); i >= 0; i--) {		// Dump hex form.
        switch(i % 4) {
	    case 0: sum += data[i]; fprintf(aFile, "%X", sum); sum = 0; break;
	    case 1: sum += 2 * data[i]; break;
	    case 2: sum += 4 * data[i]; break;
	    case 3: sum += 8 * data[i]; break;
	}
    }
    
    return self;
}


- dumpWithName:(char *)aName toFile:(FILE *)aFile
{
    fprintf(aFile, "  %10s:  ", aName);			// Dump name.
    [self dumpBinaryToFile:aFile];
    
    fprintf(aFile, "  :  ");				// Dump spacer.
    [self dumpHexToFile:aFile];
    
    fprintf(aFile, "\n");				// Dump end-of-line.
    
    return self;
}


@end


//
// End of file.
//