Debugged version, seems to work