require 'RHDL'
####################################################
# CountDown counter - used by Divide
####################################################
class CountDown < RHDL::Design
  include RHDL
  def initialize(clk,rst,count,mod=8)
    super()
    c = 0 #variable, not a signal
    define_behavior {
      process(clk) {
        if clk.event and clk == 1
          if rst == 1
            c = mod-1
          else
            puts "c is: #{c}"
            if c == 0
              c = mod-1
              puts "c is now: #{c}"
            else
              c = c - 1
              puts "c is now: #{c}"
            end
          end
          count << c
        end
      }
    }
  end
end

#############################################
# Divide - divide clock freq by given number
#############################################
class Divide < RHDL::Design
  include RHDL
  def initialize(clk,rst,count,q,mod=8)
    super()
    mod10=CountDown.new(clk,rst,count,mod)
    define_behavior {
      process(count) {
        if count == 0
          q << 1
        else
          q << 0
        end
      }
    }
  end
end


if $0 == __FILE__
  include RHDL
  include Simulator
  clk = Signal(Bit(0))
  rst = Signal(Bit(0))
  q   = Signal(Bit())
  #count = Signal(BitVector('0000',4))
  count = Signal(0)
  div  =Divide.new(clk,rst,count,q,10)
  22.times do |i|
    step {clk << clk.inv; puts "clk=#{clk},rst=#{rst},count=#{count},q=#{q}"}
  end
  step
  rst << 1
  step
  step
  rst << 0
  step
end