Writes to database and clears temp files