Added debug option; more robust error checking