#!/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) {
	if(msg!="") print "printsp: " msg >> "/dev/stderr"
	print "usage: printsp [-h] (RUN|PFILE|-) [TYPE]" >> "/dev/stderr"
	print "TYPE is one of: LP BP HB PD TR UZ RO EP MX" >> "/dev/stderr"
	print "if TYPE is ommited then all points are shown" >> "/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 "printsp: run or file '" run "' does not exist" >> "/dev/stderr"
	err = 1
	exit 1
}

BEGIN {
	check_lang("printsp")
	
	if(ARGC < 2 || ARGV[1] == "-h") print_usage()

	ARGV[1] = run_name(ARGV[1])
	
	if(ARGC > 2) sptype=ARGV[2]
	else         sptype="all";
	
	if(ARGC > 3) print_usage("too many arguments")

	if(sptype=="RO") sptype="  "
	
	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 == "" { print; next }

$1 == 0 { last_line = substr($0,5) }

$1 != 0 {
	if(last_line != "") {
		print last_line
		last_line = ""
	}
	pt_type = $3 % 10
	if(sptype=="all") {
		if(pt_type in bd_types)
			print substr($0,5,8) bd_types[pt_type] substr($0,15)
	} else {
		if(bd_types[pt_type]==sptype)
			print substr($0,5,8) bd_types[pt_type] substr($0,15)
	}
}
