generalised code, fixed bugs