Uglier version, but should work for arbitrary input