Working version with functions