The solution to the revised problem description

The code here is a solution to the revised problem description. The
sample file is ugly but demonstrates the robustness of the script.