working code (needs cleaning)