# Observation: don't need to handle cases like:
# -S-
#  |
# because S only connects to two sides
# 15/16 segments not including S (16/17 including S) -> return 8

$ 7-F7-
$ .FJ|7
$ SJLL7
$ |F--J
$ LJ.LJ
TestInput ←
$ FF7FSF7F7F7F7F7F---7
$ L|LJ||||||||||||F--J
$ FL-7LJLJ||||||LJL-77
$ F--JF--7||LJLJ7F7FJ-
$ L---JF-JLJ.||-FJLJJ7
$ |F|F-JF---7F7-L7L|7|
$ |FFJF7L7F-JF7|JL---7
$ 7-L-JL7||F7|L7F-7F7|
$ L.L7LFJ|||||FJL7||LJ
$ L7JLJL-JLJLJL--JLJ.L
TestInputII ←

DirectionMap ← ⊏⊙[¯1_0 1_0]_[0_¯1 0_1]_[0_¯1 1_0]_[0_¯1 ¯1_0]_[0_1 1_0]_[0_1 ¯1_0]_[0_0 0_0]⊗:"|-7JFL."

Parse ← ⊜∘≠@\n.

ConstructPath ← (
  ⊢⊚⌕@S.
  ▽≡/×≥0.+[¯1_0 0_¯1 1_0 0_1]¤.
  ⊢⊃(▽≡(/↥♭)⌕:|⋅¤)+∵DirectionMap⊃(⊡|≡↯2|:⊙⋅∘)⊙,
  ⍢(
    ⊃(
      ⊡⊃(⊗1¬≡≍|∘)⊓(+⊃(DirectionMap⊡|↯2)|¤⊢⇌)⊙:
    | ⊂:
    | ⋅⋅∘
    )
  )(¬≍⊙⊢)
)

# Determinant of a 2x2 matrix (useful for finding turning number - 1 ccw; `1 cw)
Determinant ← /-/×⍜⊢⇌
# given a direction and shape 2 vector, rotate it (1 ccw, `1 cw)
Rot ← ⇌⍜⊡¯±+1

PartI ← ⌊÷2⧻⋅⊙;ConstructPath

PartII ← (
  ⋅⊙;ConstructPath
  ⊃(
    ≡/-◫2⊂:⊢.
    ÷4/+≡Determinant◫2⊂:⊢..
    ≡Rot¤
  | ∘
  | ¬°⊚ # mask
  )
  ±°⊚⊂⊃(+|+↻¯1)
  ?
  ⊃×⋅∘       # apply mask
  ⊃(⊙∘|↯:0△) # set up stack structure: TOP curr mask old BOT
  ⍢(
    ⊙⊙;
    ⊃(
      ×±/+≡↻[¯1_0 0_¯1 1_0 0_1 0_0]¤
    | ⋅∘
    | ∘
    )
  )(¬≍⊙⋅∘)
  /+/+⊙⋅;
)

PartI Parse TestInput
PartII Parse TestInputII

PartI Parse &fras "day10.in"
PartII Parse &fras "day10.in"