Refactor write_imports to make it easier to read
Refactor write_imports to make it easier to read

I wasn't happy about how this method looked. I'm still not completely
satisfied, there are a few too many things going on. But I've made some
small changes so that things are better grouped and easier to follow.
I've added a few comments too.

trotzig/import-js,lencioni/import-js,lencioni/import-js,flarnie/import-js,trotzig/import-js,lencioni/import-js,flarnie/import-js,trotzig/import-js,Galooshi/import-js