#!/bin/sh

conv() {
	while [ $# -gt 0 ]; do
		if printf "%s" "$1" | grep -qE '^[0-9]+$'; then
			if [ "$m" -eq 0 ]; then	
				printf "Decimal %s → Binary: " "$1"
			fi
			printf "%s" "$p"
			printf "obase=2; %s" "$1" | bc

		elif printf "%s" "$1" | grep -qE '^([0-9A-Fa-f]+|0x[0-9A-Fa-f]+)$'; then
			if [ "$m" -eq 0 ]; then
				printf "Hex %s → Binary: " "$1"
			fi
			printf "%s" "$p"
			printf "ibase=16; obase=2; %s" "$(printf "%s" "$1" | sed 'y/abcdef/ABCDEF/; s/^0x//')" | bc

		else
			printf "Error: '%s' is not a valid decimal or hexadecimal number\n" "$1" >&2
			stat=1

		fi
		shift
	done
	return "$stat"
}


main() {
	USAGE="usage: ${0} [-mnp] ..."
	if ! [ "$1" = "x" ] && ! [ -t 0 ]; then
		cat | tr '\n' ' ' | xargs tobin "x" "$@"
		return "$?"

	elif [ "$1" = "x" ]; then
		shift

	fi
	
	if [ $# -eq 0 ]; then
		printf "Error: No arguments provided\n%s\n" "$USAGE" >&2
		return 2

	fi
	
	stat=0	
	m=0; n=0; p=""
	while getopts "lmnp" flag; do
		case "$flag" in
			m) m=1; ;;
		       	n) n=1; ;;
			p) p="0b" ;;
			*) printf "%s\n" "$USAGE" >&2 ; return 2 ;;
		esac
	done

	shift $(( OPTIND - 1 ))
	
	t=$(conv "$@")
	stat=$?

	if [ "$n" -eq 1 ] && [ "$m" -eq 1 ]; then
		t=$(printf "%s" "$t" | tr '\n' ' ')

	elif [ "$n" -eq 1 ] && [ "$m" -eq 0 ]; then
		t=$(printf "%s" "$t" | tr '\n' ';')

	else
		t=$(printf "%s" "$t")

	fi
	
	printf "%s\n" "$t"	
	return "$stat"
}

main "$@"
