refactor a bit, fix ordering bug