added debug, cleaned code