Cleanup cases in apply

This changes a bunch of the code in apply to have for/or loops instead of manual let loops. It also fixes a couple cases where apply was not doing the correct thing, and adds test cases.