#!/usr/bin/env python

import binascii, sys, re
import sploit

pattern = re.compile(r"\s+")

def show_help():
	print sys.argv[0] + " input.hex output.bin"
	print "\tinput.hex - file containing the hex representation of the bytes. Specify \"-\" for reading the hex string from STDIN."
	print "\toutput.bin - the binary file generated by converting the hex representation of the input bytes. Specify \"-\" for writing the binary string to STDOUT."

def hextobin(infile, outfile):
	if infile == "-":
		hexstring = "".join(re.sub(pattern, "", line) for line in sys.stdin)
	else:
		try:
			with open(infile) as hexfile:
				hexstring = "".join(re.sub(pattern, "", line) for line in hexfile)
		except IOError:
			sploit.show_error("Could not read the input file. Check that the file exists and it can be read.")
	
	binstring = binascii.unhexlify(hexstring)
	
	if outfile == "-":
		sys.stdout.write(binstring)
	else:
		try:
			with open(outfile, "w") as binfile:
				binfile.write(binstring)
		except IOError:
			sploit.show_error("Could not write the output file. Check the permissions.")

if __name__ == "__main__":
	if len(sys.argv) != 3:
		show_help()
	else:
		hextobin(sys.argv[1], sys.argv[2])
