Fixes and code improvement. Added a debug mode.