first version with really messy, but hopefully working code