Added some debug code, refactored a little bit