*! version 1.0.1  Statalist distribution 22feb1999
/*
	stbutil install 47 [, replace]
	stbutil uninstall 47
	stbutil query 47
*/

program define stbutil
	version 6
	gettoken cmd 0 : 0, parse(" ,")
	gettoken issue 0 : 0, parse(" ,")

	confirm integer number `issue'

	if "`cmd'"=="install" {
		StbI `issue' `0'
	}
	else if "`cmd'"=="uninstall" {
		StbU `issue' `0'
	}
	else if "`cmd'"=="query" {
		StbQ `issue' `0'
	}
	else 	error 198
end

program define StbI
	gettoken issue 0 : 0, parse(" ,")
	syntax [, REPLACE]
	preserve
	LoadToc `issue'

	if "`replace'" != "" {
		local replace ", replace"
	}


	set more off
	local i 1
	while `i' <= _N {
		local pkg = pkg[`i']
		di
		di in gr "-> net install `pkg'`replace'"
		capture noi net install `pkg'`replace'
		if _rc==1 {
			exit 1
		}
		local i = `i' + 1
	}
end


program define StbU
	gettoken issue 0 : 0, parse(" ,")
	syntax
	preserve
	LoadToc `issue'

	di
	di in gr _col(11) "Package" _col(34) "Result"
	di in gr _col(11) _dup(35) "-"

	local i 1
	while `i' <= _N {
		local pkg = pkg[`i']
		capture ado uninstall `pkg'
		if _rc == 0 {
			di in gr _col(11) "`pkg'" _col(34) "uninstalled"
		}
		else {
			if _rc == 1 {
				exit 1
			}
			di in gr _col(11) "`pkg'" _col(34) "not found"
		}
		local i = `i' + 1
	}
end

program define LoadToc
	args issue

	quietly net from http://www.stata.com/stb/stb`issue'

	tempfile toc
	copy http://www.stata.com/stb/stb`issue'/stata.toc `"`toc'"'

	tempvar loc
	quietly {
		drop _all
		infix str pkg 1-40 using `"`toc'"'
		keep if substr(pkg,1,2)=="p "
		if _N==0 {
			noi di in gr "(nothing to load)"
			exit
		}
		replace pkg = trim(substr(pkg,3,.))
		gen byte `loc' = index(pkg," ")
		replace pkg = trim(substr(pkg,1,`loc'))
		drop `loc'
		compress pkg
	}
end