module GP_COUNT8_ADV(input CLK, input RST, output reg OUT,
                     input UP, input KEEP, output reg[7:0] POUT);

	parameter RESET_MODE 	= "RISING";
	parameter RESET_VALUE   = "ZERO";

	parameter COUNT_TO		= 8'h1;
	parameter CLKIN_DIVIDE	= 1;

	reg[7:0] count = COUNT_TO;

	initial begin
		if(CLKIN_DIVIDE != 1) begin
			$display("ERROR: CLKIN_DIVIDE values other than 1 not implemented");
			$finish;
		end
	end

	//Combinatorially output underflow flag whenever we wrap low
	always @(*) begin
		if(UP)
			OUT <= (count == 8'hff);
		else
			OUT <= (count == 8'h0);
		POUT <= count;
	end

	//POR or SYSRST reset value is COUNT_TO. Datasheet is unclear but conversations w/ Silego confirm.
	//Runtime reset value is clearly 0 except in count/FSM cells where it's configurable but we leave at 0 for now.
	generate
		case(RESET_MODE)

			"RISING": begin
				always @(posedge CLK, posedge RST) begin

					//Resets
					if(RST) begin
						if(RESET_VALUE == "ZERO")
							count	<= 0;
						else
							count	<= COUNT_TO;
					end

					//Main counter
					else if(KEEP) begin
					end
					else if(UP) begin
						count		<= count + 1'd1;
						if(count == 8'hff)
							count	<= COUNT_TO;
					end
					else begin
						count		<= count - 1'd1;

						if(count == 0)
							count	<= COUNT_TO;
					end

				end
			end

			"FALLING": begin
				always @(posedge CLK, negedge RST) begin

					//Resets
					if(!RST) begin
						if(RESET_VALUE == "ZERO")
							count	<= 0;
						else
							count	<= COUNT_TO;
					end

					//Main counter
					else if(KEEP) begin
					end
					else if(UP) begin
						count		<= count + 1'd1;
						if(count == 8'hff)
							count	<= COUNT_TO;
					end
					else begin
						count		<= count - 1'd1;

						if(count == 0)
							count	<= COUNT_TO;
					end

				end
			end

			"BOTH": begin
				initial begin
					$display("Both-edge reset mode for GP_COUNT8_ADV not implemented");
					$finish;
				end
			end

			"LEVEL": begin
				always @(posedge CLK, posedge RST) begin

					//Resets
					if(RST) begin
						if(RESET_VALUE == "ZERO")
							count	<= 0;
						else
							count	<= COUNT_TO;
					end

					else begin

						if(KEEP) begin
						end
						else if(UP) begin
							count		<= count + 1'd1;
							if(count == 8'hff)
								count	<= COUNT_TO;
						end
						else begin
							count		<= count - 1'd1;

							if(count == 0)
								count	<= COUNT_TO;
						end
					end

				end
			end

			default: begin
				initial begin
					$display("Invalid RESET_MODE on GP_COUNT8_ADV");
					$finish;
				end
			end

		endcase
	endgenerate

endmodule