#!/usr/bin/perl

# input:
#	Identifier a=1 b=2 c="hello world"
# args:
#	a c
# shows:
#	Identifer 1 "hello world"

$prog=$0;
$prog =~ s,.*/,,;
$usage="Usage: $prog [-q|[-h] [-f] [-i <delimiter>] [-o <delimiter>] [-n] <fields>...]
	-h		show field headers
	-f		force field (even if it is not present)
	-i delim	use delimiter character instead of space in input stream
				each field still needs to be x=y patterns
	-o delim	use delimiter character instead of space in output stream
	-n		tab/newline on each output field (conflicts with -o)
	-q		query available headers (ignores other options)
";
$quot="\"";

$fflg=0;
$hflg=0;
$qflg=0;
$idelim=" ";
$odelim=" ";
while ($ARGV[0] =~ /^-/) {
	if ($ARGV[0] eq "--") {
		shift;
		last;
	}
	if ($ARGV[0] eq "-f") {
		$fflg=1;
		shift;
		next;
	}
	if ($ARGV[0] eq "-h") {
		$hflg=1;
		shift;
		next;
	}
	if ($ARGV[0] eq "-n") {
		$odelim="\n\t";
		shift;
		next;
	}
	if ($ARGV[0] eq "-q") {
		$qflg=1;
		shift;
		next;
	}
	if ($ARGV[0] eq "-i") {
		$idelim=$ARGV[1];
		shift;
		shift;
		next;
	}
	if ($ARGV[0] =~ /^-i.$/) {
		$idelim=substr($ARGV[0], 2, 1);
		shift;
		next;
	}
	if ($ARGV[0] eq "-o") {
		$odelim=$ARGV[1];
		shift;
		shift;
		next;
	}
	if ($ARGV[0] =~ /^-o.$/) {
		$odelim=substr($ARGV[0], 2, 1);
		shift;
		next;
	}
	print STDERR $usage;
	exit 1;
}

if (!$qflg && $#ARGV == -1) {
	print STDERR $usage;
	exit 1;
}

while ($l=<STDIN>) {
	$l =~ s/[\r\n]//g;
	@cols = &qspl($idelim, $l);
	if ($qflg) {
		shift @cols;
		foreach $col (@cols) {
			($vn, $vv) = &qspl("=", $col, 2);
			if (!$avail{$vn}) {
				print "$vn\n";
				$avail{$vn}=1;
			}
		}
		next;
	}
	if ($cols[0] =~ /$odelim/) {
		print $quot . $cols[0] . $quot;
	} else {
		print $cols[0];
	}
	shift @cols;
	%val=();
	@pcols=();
	foreach $col (@cols) {
		($vn, $vv) = &qspl("=", $col, 2);
		if ($vn =~ /^".*"$/) {
			$vn =~ s/^"//;
			$vn =~ s/"$//;
		}
		if ($vv =~ /^".*"$/) {
			$vv =~ s/^"//;
			$vv =~ s/"$//;
		}
		push @pcols, $vn;
		$val{$vn}=$vv;
	}
	if ($#ARGV != 0 || $ARGV[0] ne "*") {
		@pcols=@ARGV;
	}
	foreach $arg (@pcols) {
		$oq=0;
		if (!exists $val{$arg} && $fflg == 0) {
			next;
		}
		if (exists $val{$arg} || $hflg) {
			print $odelim;
		}
		if ($hflg) {
			if ($arg =~ /$odelim/) {
				$oq=1;
				print $quot;
			}
			print "$arg=";
		}
		if ($oq == 0 && $val{$arg} =~ /$odelim/) {
			$oq=1;
			print $quot;
		}
		print $val{$arg};
		if ($oq == 1) {
			print $quot;
		}
	}
	print "\n";
}

# quoted split function:
#	qspl(ch, str)
# splits str on ch, but not when quoted
# returns array
sub qspl() {
	local ($c, $s, $m)=@_;
	local @a;
	local $v;
	local $q;
	local $i;
	local $e;

	if (!$m) {
		$m=length($s);
	}
	@a=();
	$q=0;

	$i=0;
	$e="";
	for ($i=0; $i < length($s); $i++) {
		$v=substr($s, $i, 1);
		if ($m > 1) {
			if ($q) {
				if ($v eq $quot) {
					$q=0;
				}
			} elsif ($v eq $quot) {
				$q=1;
			} elsif ($v eq $c) {
				push @a, $e;
				$e="";
				$m--;
				next;
			}
		}
		$e .= $v;
	}
	push @a, $e;

	return @a;
}
