Take a look at making this a separate function; it's doing too much magic now