More robust implementation of hex