working code, last commit before changing to object-oriented version