#!/usr/bin/gawk -f
#
# Default preprocessor filter for 'dsv' data format, called by
# readfmtdata_dsv.m.
#
# The script takes stdin for input data stream and outputs processed data
# to stdout. It needs several arguments:
#
# 	    NODE_ID : the WebObs node ID
#	         FS : addiionnal input field separator
#	HEADER_LINE : number of uncommented header lines
#	    TEST_NF : tests the number of fields (0 will not)
#
# General behavior:
# 	- lines starting with # or % are ignored (comments)
# 	- header lines are counted outside comments
# 	- characters / : \t and - (except for negative numbers) are
# 	  always considered as field separator
# 	- space is also a separator, but consecutive spaces are trimed
# 	- empty fields with be replaced by NaN
# 	- number of fields is counted after all separators have been applied
#
#
# Authors: Xavier Béguin (EOS), François Beauducel (IPGP) / WEBOBS
# Created: 2018-06-18
# Updated: 2018-07-28

BEGIN {
	# the id of the node, not used in this script
	NODE_ID=ARGV[1]
	# input field separator
	FS=ARGV[2]
	# number of header lines to ignore
	header_line=ARGV[3]
	# fixed number of fields for a valid line
	# (0 forces a minimum of 3)
	test_fields=ARGV[4]
	# output field separator
	OFS=";"
	# tells awk not to consider arguments as files to read
	ARGC=1
}

# removes any comment and updates NR
/^[#%].*/ { NR--; next }

# ignores header lines
NR <= header_line { next }


{
	# replaces - after a digit by FS (note: gensub does not replaces input like gsub...)
	$0=gensub(/([0-9])-/, "\\1" FS,"g");
	# replaces letter 'T' by FS for ISO date format yyyymmddTHHMMSS
	$0=gensub(/([0-9])T([0-9])/, "\\1" FS "\\2","g");
	# trim spaces in each field of the line
	for(i=1; i < NF; i++) {
		gsub(/^ +| +$/, "", $i)
	}
	# reduces multiple spaces
	gsub(/ +/, " ")
	# replaces / : and space by the OFS
	gsub(/[\/:\t ]/, FS)
}

# applies field test filtering
test_fields && NF != test_fields { next }
!test_fields && NF <= 3 { next }

{
	# forces substitution of FS by OFS in all cases (updating $0)
	$1=$1
	# removes all non-numerical character
	# ('-' at the end if the [] avoids the need to escape it)
	gsub(sprintf("[^0-9eE.+-%s]", OFS), "")
	# replaces empty fields value by NaN
	sub("^" OFS, "NaN" OFS)
	sub(OFS "$", OFS "NaN")
	gsub(OFS "\\s*" OFS, OFS "NaN" OFS)
	gsub(OFS "\\s*" OFS, OFS "NaN" OFS)
	# print result line (with OFS) to stdout
	print $0
}

