reworked some functions, added `state` variable, optimized code