// Note: For this lab, we will be working with QRP Corporation's CQC-11 FPGA.
// The CQC-11 operates with a 125MHz clock.
// Your design for a tone generator must support the following 
// inputs/outputs:
// (NOTE: DO NOT CHANGE THE NAMES. OUR AUTOMATED GRADING TOOL
// REQUIRES THE USE OF THESE NAMES!)
// input clk - this will be connected to the 125MHz system clock
// input rst - this will be connected to the system board's reset bus
// input freq - a 32 bit integer indicating the required frequency
//              (0 - 9999.99Hz) formatted as follows:
//              32'hf1206 or 32'd987654 = 9876.54Hz
// output wave_out - a square wave output of the desired frequency
// you can create whatever other variables you need, but remember
// to initialize them to something!

`timescale 1ns/1ns
module tone_generator (
    input clk,
    input rst,
    input [31:0] freq,
    output wave_out
);
    // ---- DO NOT CHANGE THE CODE ABOVE THIS LINE ---- 
    // ---- IT IS NECESSARY FOR AUTOMATED ANALYSIS ----
    // TODO: Add your code below. 
    reg [31:0] counter;
    reg flip;
    assign wave_out = flip;
    real real_freq = freq/100.0;
    real real_interval = 125000000.0/real_freq/2.0;
    integer interval = ($rtoi(real_interval * 10) - ($rtoi(real_interval) * 10) > 4)? $rtoi(real_interval) + 1: $rtoi(real_interval);

    always @(posedge clk or posedge rst)
    begin
        if(rst==1)
            begin
                // Reset to 0 so we can go from 1 to interval in each loop.
                // If we reset to 1 as the loop does, that means our first loop would
                // start at 2 and thus be one rising clock edge short.
                counter <= 0;
                flip <= 0;
            end
        else
            begin
                if(counter == interval)
                    begin
                        counter <= 1;
                        flip <= ~flip;
                    end
                else
                    begin
                        counter <= counter + 1;                       
                    end
            end
    end
endmodule
