make more robust and add debug capability