code cleanup, added thresholds, redone flowchart