Rewritten based on pseudo code