/* alu.v - implementation of the ALU of the 9086 CPU

   This file is part of the 9086 project.

   Copyright (c) 2024 Efthymios Kritikos

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

`include "alu_header.v"

module ALU(input [15:0]A,input [15:0]B,output reg [15:0]OUT,input [`ALU_OP_BITS-1:0]op,output wire [7:0]FLAGS,input Wbit);
reg C_FLAG;
wire signed [15:0]SIGNED_B;
wire signed [7:0]SIGNED_8B;
assign SIGNED_B=B;
assign SIGNED_8B=B[7:0];

assign FLAGS={(Wbit==1)?OUT[15:15]:OUT[7:7],(Wbit==1) ? (OUT[15:0]=='h0000) : (OUT[7:0]=='h00),5'b0,C_FLAG};

always @ ( * ) begin
	if(Wbit==1)begin
		case (op)
			`ALU_OP_ADD: {C_FLAG,OUT}=A+B;
			`ALU_OP_ADD_SIGNED_B: {C_FLAG,OUT}=A+SIGNED_B;
			`ALU_OP_SUB: {C_FLAG,OUT}=A-B;
			`ALU_OP_SUB_REVERSE: {C_FLAG,OUT}=B-A;
			`ALU_OP_AND: begin C_FLAG=0;OUT=A&B; end
			`ALU_OP_OR:  begin C_FLAG=0;OUT=A|B; end
			`ALU_OP_XOR: begin C_FLAG=0;OUT=A^B; end
			`ALU_OP_SHIFT_LEFT: begin C_FLAG=(A&16'h8000)==16'h8000;OUT=A<<B; end
		endcase
	end else begin
		OUT[15:8]=8'b0;
		case (op)
			`ALU_OP_ADD: {C_FLAG,OUT[7:0]}=A[7:0]+B[7:0];
			`ALU_OP_ADD_SIGNED_B: {C_FLAG,OUT[7:0]}=A[7:0]+SIGNED_8B;
			`ALU_OP_SUB: {C_FLAG,OUT[7:0]}=A[7:0]-B[7:0];
			`ALU_OP_SUB_REVERSE: {C_FLAG,OUT[7:0]}=B[7:0]-A[7:0];
			`ALU_OP_AND: begin C_FLAG=0;OUT[7:0]=A[7:0]&B[7:0]; end
			`ALU_OP_OR:  begin C_FLAG=0;OUT[7:0]=A[7:0]|B[7:0]; end
			`ALU_OP_XOR: begin C_FLAG=0;OUT[7:0]=A[7:0]^B[7:0]; end
			`ALU_OP_SHIFT_LEFT: begin C_FLAG=(A&16'h80)==16'h80;OUT[7:0]=A[7:0]<<B; end
		endcase
	end
end

endmodule
