rearrange a few things, and use promises

Needs testing.
set indentation