program drop _all
mata: mata clear
program grader

	version 10.0
	syntax anything(name=stub)
	local inf "`stub'.grades"
	set more off
	capt log close
	log using `stub'.smcl, replace
	local dt "$S_DATE $S_TIME"
	mata: mm_gr("`inf'")
	log close
	set more on
end

version 10
mata:
// from adoupdate
		void mm_gr(string scalar ffn)
{
        real scalar             fh
        string scalar           line
        string colvector        res

        fh = fopen(ffn, "r")

        pragma unset res
        while ((line=fget(fh))!=J(0,0,"")) {
              res = res \ line
        }
        fclose(fh)

		hdr = res[1,.]
// student names
		ns = strtoreal(tokens(res[2,.])[1])
		names = res[3::2+ns,.]
		snam = J(ns,2,"")
		for(i=1;i<=ns;i++) {
			snam[i,2::1] = tokens(names[i])
		}
ns
//	snam
// assignment names
		ngr = strtoreal(tokens(res[3+ns,.])[1])
ngr
		grnam = res[4+ns::3+ns+ngr,.] \ "Weighted Average"
grnam
		grval = res[4+ns+ngr::3+ns+2*ngr,.]
		pts = J(ngr,1,0)
		wt = J(ngr,1,0)
// assignment points, weights
		for(i=1;i<=ngr;i++) {
			tmp = tokens(grval[i])
			pts[i] = strtoreal(tmp[1,1])
			wt[i] = strtoreal(tmp[1,4])
		}
pts
wt
// grades themselves
		gr = J(ns,ngr,0)
		rown = 3+ns+2*ngr+1
		for(i=1;i<=ngr;i++) {
			gr[1::ns,i]  = strtoreal(tokens(res[rown])')
			rown = rown+2
		}
gr
// begin calculations
// scaled weights as rowvector
		scwt = (wt :/ colsum(wt))'
// scaled weights in terms of possible points
		scps = 100 :* scwt :/ (pts)'
// weighted grades
		scgr = gr :* scps
// total score
		totgr = rowsum(scgr)
		gr = gr,totgr
		stat = J(5,ngr+1,0)
		stat[1,.] = mean(gr)
		V = variance(gr)
		for(i=1;i<=ngr+1;i++) {
			stat[2,i] = sqrt(V[i,i])
		}
		stat[3::4,.] = colminmax(gr)
// from moremata
		stat[5,.] = mm_median(gr)
// ranks of each column, percentiles
		ord = runningsum(J(ns,1,1))
		sgr = gr,ord
		pts = pts \ 100
		printf("\n\nGrading for %50s\n",hdr)
		dt = st_local("dt")
		printf("as of %20s\n",dt)
		gr
		for(i=1;i<=ngr+1;i++) {
			sgr = sort(sgr,(i))
			sgrd = sgr[.,i]
			sgr[.,i] = 100*(ord :- 0.5) :/ ns
			sgrd = sgrd, sgr[.,i]
			printf("\n Grade %2.0f: %-20s\n", i, grnam[i])
			printf(" Possible: %5.0f Mean: %7.2f Median: %7.2f\n\n    Score Percentile\n", pts[i], stat[1,i], stat[5,i])
			for(j=ns;j>=1;j--) {
				printf("%9.2f  %9.2f\n", sgrd[j,1],sgrd[j,2])
			}
//			sgrd[ns::1,.]
		}
		sgr = sort(sgr,ngr+2)
		for(i=1;i<=ns;i++) {
				printf("\n\nGrading for %50s\n",hdr)
				printf("as of %20s\n\n",dt)
				printf("%15s %-15s\n\n",snam[i,1],snam[i,2])
				printf("Grade                   Score Possible   Median  Percentile\n")
				for(j=1;j<=ngr+1;j++) {
					printf("%-20s  %7.2f  %7.2f  %7.2f  %5.2f\n", grnam[j],gr[i,j],pts[j],stat[5,j],sgr[i,j])
				}
				printf("\n\n\n")
		}
}


end