more code from L6 lecture notes