Solution to acode in c, seems to work fine here