fix bitwise bug

WORKING for 1 loop
refactorig, add debug code