Some errors corrected, tested with real database.