// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/03/b/RAM4K.hdl

/**
 * Memory of 4K registers, each 16 bit-wide. Out holds the value
 * stored at the memory location specified by address. If load==1, then 
 * the in value is loaded into the memory location specified by address 
 * (the loaded value will be emitted to out from the next time step onward).
 */

CHIP RAM4K {
    IN in[16], load, address[12];
    OUT out[16];

    PARTS:
    DMux8Way16(in=in, sel=address[0..2], a=inA, b=inB, c=inC, d=inD,
                                         e=inE, f=inF, g=inG, h=inH);
    DMux8Way(in=load, sel=address[0..2], a=loadA, b=loadB, c=loadC, d=loadD,
                                         e=loadE, f=loadF, g=loadG, h=loadH);

    RAM512(in=inA, load=loadA, address=address[3..11], out=outA);
    RAM512(in=inB, load=loadB, address=address[3..11], out=outB);
    RAM512(in=inC, load=loadC, address=address[3..11], out=outC);
    RAM512(in=inD, load=loadD, address=address[3..11], out=outD);
    RAM512(in=inE, load=loadE, address=address[3..11], out=outE);
    RAM512(in=inF, load=loadF, address=address[3..11], out=outF);
    RAM512(in=inG, load=loadG, address=address[3..11], out=outG);
    RAM512(in=inH, load=loadH, address=address[3..11], out=outH);

    Mux8Way16(a=outA, b=outB, c=outC, d=outD,
              e=outE, f=outF, g=outG, h=outH, sel=address[0..2], out=out);
}