added pseudocode which might help