#!/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 "filterbd: " msg >> "/dev/stderr"
	m1 = "[-h] (RUN|PFILE|-) (-tr COL) | (-l begin [end])"
	print "usage: filterbd " m1 >> "/dev/stderr"
	err = 1
	exit 1
}

function abs(x) { return x<0?-x:x }

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 "filterbd: run or file '" run "' does not exist" >> "/dev/stderr"
	err = 1
	exit 1
}

function filter_tr() {
	if(state==0) {
		print
		th1       = $(col+4)
		state     = 1
		was_blank = 0
	} else if(state==1) {
		th2            = $(col+4)
		looks_constant = (abs(th1-th2)/(1+abs(th1)+abs(th2))<1.0e-6)
		close_to_PI    = (abs(th2)%PI<1.0e-5) || ((PI-abs(th2)%PI)<1.0e-5)
		if( looks_constant && close_to_PI ) {
			if( !was_blank ) print ""
			was_blank = 1
		} else {
			was_blank = 0
			print
		}
		th1 = th2
	}
}

# BR  PT  TY  LAB  PAR  L2-NORM  ...
#  1   2   3   4    5      6
              
function filter_labs() {
 if($4 != 0) last_lab = $4
 if(first<=last_lab && (last_lab<last || last==-1)) print
 if(last_lab==last && $4!=0) print
}

BEGIN {
	check_lang("filterbd")
	
	if(ARGC < 2 || ARGV[1] == "-h") print_usage()
	if(ARGC < 4) print_usage("too few arguments")

	ARGV[1] = run_name(ARGV[1])
	
	mode = ARGV[2]
	if(mode == "-tr") {
		if(ARGC > 4) print_usage("too many arguments")
		col = ARGV[3]
	} else if(mode == "-l") {
		if(ARGC > 5) print_usage("too many arguments")
		first = ARGV[3]
		if(ARGC > 4) last = ARGV[4]
		else         last = -1
	} else {
		print_usage("unrecognised option: " mode)
	}

	state     = 0
	PI        = 3.1415927
	was_blank = 1
	last_lab  = 0
	ARGC      = 2
}

$0 == "" { if(!was_blank) print; was_blank = 1; state = 0; next }

$1 != 0 {
	if     (mode=="-tr") filter_tr()
	else if(mode=="-l" ) filter_labs()
}
