reviewed alongside upstream apiserver.go: corrected a few porting bugs, refactored code for readability