Ton of tidy up - I think this is approaching idiomatic Lua!