################################################################################
#
#   Common functions for different projects
#
################################################################################

# Write console message in red
proc write_red { msg } {
    puts -nonewline "\033\[1;31m"
    puts $msg
    puts -nonewline "\033\[0m"
}

# Write console message in green
proc write_green { msg } {
    puts -nonewline "\033\[1;32m"
    puts $msg
    puts -nonewline "\033\[0m"
}

# Write console message in green
proc write_yellow { msg } {
    puts -nonewline "\033\[1;33m"
    puts $msg
    puts -nonewline "\033\[0m"
}

# Write console message in green
proc write_blue { msg } {
    puts -nonewline "\033\[1;34m"
    puts $msg
    puts -nonewline "\033\[0m"
}

# Write console message in different colors
proc write_msg { msg severity } {
    switch ${severity} {
        "1" {
            write_green $msg
        }
        "2" {
            write_yellow $msg
        }
        "3" {
            write_red $msg
        }
        default {
            write_blue $msg
        }
    }
}

# Returns the number of CPUs for the build
# To set the build number of threads in Vivado
proc get_number_cpus {} {
    global tcl_platform env
    switch ${tcl_platform(platform)} {
        "windows" {
            return $env(NUMBER_OF_PROCESSORS)
        }
        "unix" {
            if {![catch {open "/proc/cpuinfo"} f]} {
                set cores [regexp -all -line {^processor\s} [read $f]]
                close $f
                if {$cores > 0} {
                    return $cores
                }
            }
        }
        default {
            write_msg "Unknown System" "3"
            return 1
        }
    }
}

# Define Vhdl src
proc add_vhdl_src { lib src} {
    lappend ::user_list(SRC_VHDL) ${src}
    lappend ::user_list(LIB_VHDL) ${lib}
}

#  Define Vhdl08 src
proc add_vhdl08_src { lib src} {
    lappend ::user_list(SRC_VHDL08) ${src}
    lappend ::user_list(LIB_VHDL08) ${lib}
}

# Define Verilog/SystemVerilog src
proc add_source { src } {
    lappend ::user_list(SRC_VERILOG) ${src}
}

# Define Constraint files
proc add_constraint { file } {
    lappend ::user_list(CONSTRAINT) ${file}
}

# Define array property
proc set_user_property { name value } {
    lappend ::user_list(PROP_NAME) ${name}
    lappend ::user_list(PROP_VAL) ${value}
}

# Return list
proc get_list { list_name } {
    return [ set ::user_list(${list_name}) ]
}

# Return list size
proc get_list_size { list_name } {
    return [ llength [ get_list ${list_name} ] ]
}

# Check if verilog source is SystemVerilog
proc enable_sv_compilation { filename } {
    set extension [ file extension $filename ]
    if { [ string equal ${extension} ".sv" ] } {
        return 1
    } else {
        return 0
    }
}
