program nscore, rclass byable(onecall)

*! version: 1.0.0 $
*! Author:  Mark Lunt
*! Date:    November 16, 2018 @ 12:50:03


   syntax varlist [if] [in], GENerate(string)

   foreach opt in  generate {
      if "``opt''" != "" {
         local tuoptions `tuoptions'`opt',
      }
   }

   capture trackuse, progname("nscore") av("2.0.0") aid("NA") options("`tuoptions'") package("nscores")
   if _rc != 0 {
      // trackuse failed: install latest version and retry
      capture net install ga_fragment, force replace from("http://personalpages.manchester.ac.uk/staff/mark.lunt")
      if _rc == 0 {
         capture trackuse , progname("nscore") av("2.0.0") aid("NA") options("`tuoptions'") package("nscores")
      }
   }


   local oldvarnum: word count `varlist'
   local newvarnum: word count `generate'

	if (`oldvarnum' ~= `newvarnum') {
		if `newvarnum' == 1 {
			local root `generate'
			if substr("`generate'", length("`generate'"),1) == "*" {
				local root = substr("`generate'", 1, length("`generate'") - 1)
			}
			local generate
			foreach num of numlist 1/`oldvarnum' {
				local generate `generate' `root'`num'
			}
		}
		else {
	 noi di as error ///
   	 "There must be the same number of new variables as old ones"
	 exit
  }
}

marksample touse, novarlist

local sortvars : sortedby
local byprefix
if "`_byvars'" ~= "" {
  local byprefix by `_byvars':
}
tempvar orig_order touse_now
gen `orig_order' = _n
gen `touse_now' = `touse'

foreach num of numlist 1/`oldvarnum' {
  local thisvar : word `num' of `varlist'
  local this_sc : word `num' of `generate'
  replace `touse_now' = `touse'
  replace `touse_now' = 0 if `thisvar' == .
  sort `_byvars' `touse_now' `thisvar' `orig_order'
  by `_byvars' `touse_now': gen `this_sc' = invnorm((_n-3/8)/(_N+1/4)) ///
         if `touse_now'
  char `thisvar'[nscore] `this_sc'
  char `this_sc'[inscore] `thisvar'
}

sort `orig_order'

if "`sortvars'" ~= "" {
  sort `sortvars'
}


end