Updated to work directly with database. Also cleaned it up a bit