moved a lot of high-level C code to lua, closes #1