// CD4013B: dual D flip-flop with set and reset.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (7)
// and VDD (14), are left out.  Synthesizable.
//
// Each flip-flop stores D at the rising edge of its clock.  SET and RESET
// are active high and asynchronous: they act at once, without the clock.
// With SET and RESET both high the chip sets both Q and ~Q high; the model
// does the same while they are both high.  Do not release them at the same
// moment: which of the two wins is not defined.

module cd4013
(
    output logic q1,      // Pin 1
    output logic q1_n,    // Pin 2:  ~Q1
    input  logic clock1,  // Pin 3
    input  logic reset1,  // Pin 4:  1 = Q1 goes to 0 at once
    input  logic d1,      // Pin 5
    input  logic set1,    // Pin 6:  1 = Q1 goes to 1 at once
                          // Pin 7:  VSS
    input  logic set2,    // Pin 8
    input  logic d2,      // Pin 9
    input  logic reset2,  // Pin 10
    input  logic clock2,  // Pin 11
    output logic q2_n,    // Pin 12: ~Q2
    output logic q2       // Pin 13
                          // Pin 14: VDD
);

    logic r1, r2;

    always_ff @ (posedge clock1 or posedge reset1 or posedge set1)
        if (reset1)
            r1 <= 1'b0;
        else if (set1)
            r1 <= 1'b1;
        else
            r1 <= d1;

    always_ff @ (posedge clock2 or posedge reset2 or posedge set2)
        if (reset2)
            r2 <= 1'b0;
        else if (set2)
            r2 <= 1'b1;
        else
            r2 <= d2;

    assign q1   =   r1 | (set1 & reset1);
    assign q1_n = ~ r1 | (set1 & reset1);
    assign q2   =   r2 | (set2 & reset2);
    assign q2_n = ~ r2 | (set2 & reset2);

endmodule
