Added debug mode, various code improvements.

Debug mode: ctrl+d