program define pwupdate
version 11.0
	syntax [anything(everything equalok)], [local] *

	if ("`local'"=="") {

		local updateserver = "http://www.panelwhiz.eu/pwcontrol/update.php"
		local authenticate = "rEHDK4hynR"

		local update_needed = 1

		di as text `"Contacting {browse "http://www.panelwhiz.eu":http://www.panelwhiz.eu}..."'

		capture findfile pw__update.ado
		if (!_rc) {
			pwupdate_checkversion `r(fn)'
			local offline_version `r(version)'

			if ("`offline_version'"!="") {
				tempfile checkfirstline
				capture copy "`updateserver'?checkpwupdate&authenticate=`authenticate'" "`checkfirstline'", replace
				// On error, update_needed still is 1
				if (!_rc) {
					pwupdate_checkversion `checkfirstline'
					local online_version `r(version)'

					if ("`offline_version'"=="`online_version'") {
						local update_needed = 0
						}

					capture erase "`checkfirstline'"
					}
				}
			}

		if (`update_needed') {
			di as text "Downloading new update software... " _c
			tempfile updateprogram
			capture copy "`updateserver'?getpwupdate&authenticate=`authenticate'" "`updateprogram'", replace
			if (!_rc) {
				clear programs
				clear mata

				capture noisily run "`updateprogram'"
				if (_rc) {
					di
					di as error "pwupdate encountered an error while reading the update program"
					di as error `"please contact {browse "mailto:service@panelwhiz.eu":service@panelwhiz.eu}"'
					di as error "please quote any error message(s) above and any return code below"
					exit _rc
					}

				capture erase "`updateprogram'"

				di as text "Done."
				di
				}
			else {
				di
				di as error "pwupdate encountered an error while downloading the update program"
				di as error "please make sure that your computer is connected to the internet"
				di as error "please also check your proxy settings for Stata and `=c(os)'"
				di as error `"please contact {browse "mailto:service@panelwhiz.eu":service@panelwhiz.eu}"'
				di as error "please quote any error message(s) above and any return code below"
				exit _rc
				}
			}
		else {
			di as text "Update software is up-to-date."
			di
			}
		}

	capture noisily pw__update `anything', `options'
	if (_rc) {
		di as error "pwupdate encountered an error while running pw__update"
		di as error `"please contact {browse "mailto:service@panelwhiz.eu":service@panelwhiz.eu}"'
		di as error "please quote any error message(s) above and any return code below"
		exit _rc
		}
end

program define pwupdate_checkversion, rclass
	tempname fh
	capture file open `fh' using "`0'", read text
	// On error don't return anything
	if (!_rc) {
		file read `fh' firstline
		file close `fh'

		tokenize `firstline'

		if ("`1'"=="*!" & "`2'"=="PANELWHIZ") {
			return local version `3'
			}
		}
end