Carlos's code, with slight modifications