Not the most efficient code, but it works