#!/usr/bin/awk -f

function check_lang(prg, cfmt,x,y,lang,m1,m2) {
	cfmt = CONVFMT
	lang = ENVIRON["LANG"]
	CONVFMT = "%+.3e"
	x = 1.23
	y = "" x
	if("+1.230e+00"!=y) {
		# try to change language to "C" at run time
		ENVIRON["LANG"] = "C"
		x = 1.23
		y = "" x
		if("+1.230e+00"!=y) {
			m1 = ": numeric format of language '"
			m2 = "' not supported"
			print prg m1 lang m2 >> "/dev/stderr"
			m1 = ": set the environment variable LANG to C before running "
			print prg m1 prg >> "/dev/stderr"
			err = 1
			exit 1
		}
	}
	CONVFMT = cfmt
}

function print_usage(msg, m1) {
	if(msg!="") print "splabs: " msg >> "/dev/stderr"
	m1 = "[-h|-l] (RUN|PFILE|-) TYPE [BEGIN [END]]"
	print "usage: splabs " m1 >> "/dev/stderr"
	print "TYPE is one of: LP BP HB PD TR UZ RO EP MX" >> "/dev/stderr"
	err = 1
	exit 1
}

function exists(fname, status) {
	status = getline < fname
	close(fname)
	return ( status != -1 )
}

function run_name(run, fname) {
	if(run == "-") return run
	
	fname = "data/p." run
	if(exists(fname)) return fname
	
	fname = run
	if(exists(fname)) return fname
	
	print "splabs: run or file '" run "' does not exist" >> "/dev/stderr"
	err = 1
	exit 1
}

BEGIN {
	check_lang("splabs")
	
	if(ARGC < 2 || ARGV[1] == "-h") print_usage()
	if(ARGC < 3) print_usage("too few arguments")
	
	use_labs = 0
	curr_arg = 1
	
	if(ARGC > curr_arg && ARGV[curr_arg]=="-l") {
		if(ARGC < 4) print_usage("too few arguments")
		use_labs = 1
	}
	curr_arg += use_labs

	ARGV[1] = run_name(ARGV[curr_arg++])
	
	sptype = ARGV[curr_arg++];
	if(sptype == "RO") sptype = "  "
	
	if(ARGC > curr_arg) first=ARGV[curr_arg++]
	else                first=-1

	if(ARGC > curr_arg) last=ARGV[curr_arg++]
	else                last=-1
	
	if(ARGC > curr_arg) print_usage("too many arguments")

	count = 0
	labs  = ""
	
	bd_types[1]  = "BP"
	bd_types[2]  = "LP"
	bd_types[3]  = "HB"
	bd_types[4]  = "  "
	bd_types[-4] = "UZ"
	bd_types[5]  = "LP"
	bd_types[6]  = "BP"
	bd_types[7]  = "PD"
	bd_types[8]  = "TR"
	bd_types[9]  = "EP"
	bd_types[-9] = "MX"

	ARGC = 2
}

$0 == "" { next }

$1 != 0 {
	pt_type = $3 % 10
	if(bd_types[pt_type]==sptype) {
		if(use_labs)   count = $4
		else         ++count
		if     (first==-1                  ) labs = labs " " $4
		else if(first<=count && last==-1   ) labs = labs " " $4
		else if(first<=count && count<=last) labs = labs " " $4
	}
}

END {
	if(err == "") print labs
}
