Final version. Added debug mode