Rewritten after Dr. Sawada's clarification. Works correctly now