Befunge, 249249 218 bytes
v >p >&::00g\00p&::00g\`-2/:20p\2*10g\20p2*-3*:30p0\`\0\`+0\30p\20g-`:!#v_"~~>,,.<~">00g20g-*\30g*+:30g-v>:#,_@
&"~<.,^01<^+1$_v#+`\0\`\0p05,>~~"0_v#\g03+`g050`\0:-\g03\p04g02\p05:-\g02:\*2g02:<+2<-*/6+3g03p04<^
>00p&^ >50g$"<">:#,_40p>:0`40g!+\3*40g\-:22p01#|_3-`*#v_$^
!#|_0"0" >.,,"22g1>1g#<\#-:#1_$"<">:#,_22p1"40g3>3g#<\#->:#1_
2->:!#|_0"0" ,>..<,">:#,_$
#,_$1->_$>:!#@_0"#|_1-
#@_1-0" >.,.<">:#,_$>:!
I'm sure this can probably be golfed some moreThis is now based on the algorithm in the Ruby answer by Level River St, but it'swhich provided greater scope for golfing and a startsignificant reduction in size compared to my original solution.