*! 1.0.4.1 Mead Over  21May2024
*! Forked from -matsum- 1.0.4  18Jun1997  Jeroen Weesie/ICS  STB-39 dm49

program define matsum2
        version 5.0

      * scratch

        tempname A OneC OneR

      * parse input

        if "`*'" == "" { exit }
        parse "`*'", parse(",")
        local A0 "`1'"
		confirm matrix `A0'
        capt mat `A' = `A0'
        if _rc {
            di in red "`A0' is undefined or an illegal matrix expression"
            exit 198
        }
        local nr = rowsof(`A')
        local nc = colsof(`A')

        mac shift
        local options " All(str) Column(str) Display Format(str) Row(str) Missingok"
        parse "`*'"

		if "`missingok'"~="" {
			di as txt "Option -missingok- invoked"
			local i = 1
			while `i' <= `nr' {
				local j = 1
				while `j' <= `nc' {
					tempname el
					scalar `el' = el(`A',`i',`j')
					if scalar(`el') >= . {
						mat def `A'[`i',`j'] = 0
						di as txt "  Element `A0'[`i',`j'] = " as res scalar(`el') as txt " , but is assumed equal to zero"
					}
					local j = `j' + 1
				}
				local i = `i' + 1
			}
		}

        if "`format'" != "" {
            local fmt "format(`format')"
        }

      * defaults

        if "`row'"=="" & "`column'"=="" & "`all'"=="" {
            local column "."
        }
        if "`row'"=="." {
            tempname Row
            local row "`Row'"
            local display "display"
        }
        if "`column'"=="." {
            tempname Col
            local column "`Col'"
            local display "display"
        }
        if "`all'"=="." {
            tempname All
            local all "`All'"
            local display "display"
        }

        mat `OneC' = J(`nc',1,1)
        mat `OneR' = J(1,`nr',1)

        if "`row'" != "" {            * compute row sums as a column vector

            mat `row' = `A' * `OneC'
            if "`display'" != "" {
                di in gr _n "row-wise sums of matrix `A0'[`nr',`nc']"
                mat list `row', noheader `fmt'
            }
        }

        if "`column'" != "" {         * compute column sums as a row vector

            mat `column' = `OneR' * `A'
            if "`display'" != "" {
                di in gr _n "column-wise sums of matrix `A0'[`nr',`nc']"
                mat list `column', noheader `fmt'
            }
        }

        if "`all'" != "" {            * sum over all elements

            if "`row'" != "" {
                mat `all' = `OneR' * `row'
            }
            else if "`column'" != "" {
                mat = `all' * `OneC'
            }
            else {
                mat `all' = `A' * `OneC'
                mat `all' = `OneR' * `all'
            }
            if "`display'" != "" {
                if "`format'" == "" {
                    local format "%10.2g"
                }
                di _n in gr "sum of elements of `A0'[`nr',`nc'] = " /*
                  */ in ye `format' `all'[1,1]
            }
        }
end