Final working version, before refactoring.