updated algorithm and cleaned some codes