Fixed imports and functions; also massively cleaned up code.

@Vreality please make your code more readable as you write it.