module aq_prio(
  clk,
  rst_b,
  valid,
  clr,
  sel
);
parameter NUM =2;

input            clk;
input            rst_b;
input  [NUM-1:0] valid;
input            clr;
output [NUM-1:0] sel;

reg    [NUM-1:0] prio [NUM-1:0];
reg    [NUM-1:0] unused [NUM-1:0];
wire   [NUM-1:0] sel;
wire   [NUM-1:0] clr_bus;

assign clr_bus[NUM-1:0] = {NUM{clr}} & sel[NUM-1:0];

genvar i;
generate
for(i=0; i<NUM; i=i+1) begin:PRIO_MATRIX_GEN
always@(posedge clk or negedge rst_b)
begin
  if (!rst_b)
    {prio[i][NUM-1:0], unused[i][NUM-1:0]} <= {{NUM{1'b0}}, {NUM{1'b1}}} << i;
  else if(|clr_bus[NUM-1:0]) begin
    prio[i][NUM-1:0] <= (clr_bus[NUM-1:0] == ({{(NUM-1){1'b0}},1'b1}<<i)) 
                      ? ~clr_bus[NUM-1:0] 
                      : prio[i][NUM-1:0] &~clr_bus[NUM-1:0];
  end
end
end
endgenerate

generate
for(i=0; i<NUM; i=i+1) begin: SEL_GEN
assign sel[i] = valid[i] && !(|(valid[NUM-1:0] & prio[i][NUM-1:0]));
end
endgenerate

endmodule