finally wrote THE FUNCTION