*! qqplot2 version 1.0.0  NJC 19 August 1998
* qqplot version 3.1.2  09/11/94
program define qqplot2
	version 5.0
	local varlist "req ex min(2) max(2)"
	local if "opt"
	local in "opt"
	local options "TItle(str) *"
	parse "`*'"
	parse "`varlist'", parse(" ")
	tempvar VARY VARX CNT NEWX2
	quietly {
		gen `VARY'=`1' `if' `in'
		gen `VARX'=`2' `if' `in'
		gen long `CNT'=sum(`VARY'~=.)
		local cnty=`CNT'[_N]
		replace `CNT'=sum(`VARX'~=.)
		local cntx=`CNT'[_N]
		drop `CNT'
		if `cntx'==0 | `cnty'==0 { error 2000 }
		if `cnty'>`cntx' {
			_crcqqp2 `VARY' `cnty' `cntx'	/* qqalign */
		}
		if `cnty'<`cntx' {
			_crcqqp2 `VARX' `cntx' `cnty' 	/* qqalign */
		}
		_crcqqp1 `VARY' `VARX' `NEWX2'
		_crcslbl `VARY' `1'
		_crcslbl `NEWX2' `2'
                if "`title'" == "" {
                        local title "     Quantile-Quantile Plot"
                }
                else if "`title'" == "." {
                        local title " "
                }
	}
	noisily graph `VARY' `NEWX2' `NEWX2', `options' /*
		*/ ti("`title'") sy(oi) c(.l) sort
end

program define _crcqqp1 /* _qqalign */
	version 3.1
	tempvar YORDER
	quietly {
		sort %_1
		gen long %_YORDER=_n
		sort %_2
		gen %_3=%_2[%_YORDER]
	}
end

program define _crcqqp2 /* varname old# new# */	/* was qqcomp */
	version 3.0
	tempvar INT FRAC TEMP
	quietly {
		sort %_1
		gen long %_INT=(_n-0.5)*%_2/%_3+0.5
		gen %_FRAC=0.5+(_n-0.5)*%_2/%_3-%_INT
		gen %_TEMP=(1-%_FRAC)*%_1[%_INT]+%_FRAC*%_1[%_INT+1]
		replace %_1=%_TEMP
	}
end