cleaned code, inspired by Sebastiaan Franken