First rewrite

Attempting a rewrite to have clearer, more readable code.