modularised, add some error checking