// 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/3/b/RAM16K.hdl
/**
 * Memory of 16K 16-bit registers.
 * If load is asserted, the value of the register selected by
 * address is set to in; Otherwise, the value does not change.
 * The value of the selected register is emitted by out.
 */
CHIP RAM16K {
    IN in[16], load, address[14];
    OUT out[16];

    PARTS:

    // Figuring out which RAM4k to write to
    DMux4Way(
        in=load,
        sel=address[12..13],
        a=load01,
        b=load02,
        c=load03,
        d=load04
    );

    // Writing the correct RAM address inside the register
    RAM4K(in=in, load=load01, address=address[0..11],out=ram4Kout01);
    RAM4K(in=in, load=load02, address=address[0..11],out=ram4Kout02);
    RAM4K(in=in, load=load03, address=address[0..11],out=ram4Kout03);
    RAM4K(in=in, load=load04, address=address[0..11],out=ram4Kout04);
    
    // Reading the selected RAM Register
    Mux4Way16(
        a=ram4Kout01,
        b=ram4Kout02,
        c=ram4Kout03,
        d=ram4Kout04,
        sel=address[12..13],
        out=out
    );
}