Made variables local where appropriate
Populate tables if not supplied