# 2e23c492f1e3b95eaace7fb0b0a6773c8bc0fccc437e95af5022ee17593b7a45 Elan 2.0.0-alpha4 valid

main
  variable order set to inputIntBetween("Enter order of dragon [1..12]: ", 1, 12)
  call clearPrintedText()
  call print($"Dragon of order {order}")
  variable side set to (75/pow(sqrt(2), order))
  variable corner set to side/12.0/cos(45)
  variable turns set to left
  for i in range(1, order + 1)
    set turns to setTurns(turns)
  end for
  variable t set to new Turtle()
  call setupTurtle(t, order)
  call drawDragon(t, order, turns, side, corner)
end main

constant left set to "1"

constant right set to "0"

procedure drawDragon(t as Turtle, order as Int, turns as String, side as Float, corner as Float)
  variable p set to (200.0/order).floor()
  variable turnI set to 0
  for turn in turns
    set turnI to (if(turn.equals(left), 1, -1))
    call t.turn(-45*turnI)
    call t.move(corner)
    call t.turn(-45*turnI)
    call t.move(side)
    call sleep_ms(p)
  end for
  call t.penUp()
  call t.hide()
end procedure

procedure setupTurtle(t as Turtle, order as Int)
  call t.turnToHeading(180 + order*45)
  call t.placeAt(-40, 20)
  call t.penColour(red)
  call t.penWidth(10.0/order)
  call t.penDown()
  call t.show()
end procedure

function setTurns(turns as String) returns String
  variable turnsR set to turns + left + reflect(turns)
  # turnsR[0..turnsR.length() - 1]
  return turnsR.subString(0, turnsR.length() - 1)
end function

function reflect(s as String) returns String
  variable sR set to ""
  for i in range(1, s.length() + 1)
    set sR to if((s[i - 1]).equals(left), right, left) + sR
  end for
  return sR
end function

test test_setTurns
  assert setTurns("1") is "11"
  assert setTurns("11") is "1110"
  assert setTurns("110") is "110110"
  assert setTurns("1101100") is "11011001110010"
end test

test test_reflect
  assert reflect("110") is "100"
  assert reflect("00001") is "01111"
end test
