#!/bin/bash

IN='taylor.txt'
OUT='newton-orig.bc'
TMP="$(mktemp)"

# Uncomment lines below as needed to generate taylor.txt

# Generate taylor.txt 1 - 1000
#./taylor.py 1000 >"$IN"

# Add to existing taylor.txt
#./taylor.py 1001 1500 >>"$IN"

# Remove the leading - signs
cut -c 2- <"$IN" >"$TMP"

# Count terms to determine required scale/digits
TERMS=$[$(wc -l <"$TMP")+1]
# .624 digits/term
# terms*.624+5 = scale
S=$(echo "$TERMS*.624+6.5"|bc|cut -d. -f1)

# Header
>"$OUT"
echo "scale=$S" >>"$OUT"

echo '1/12' >>"$OUT"
#echo '# ' >>"$OUT"

# Body
C=5
while read LINE; do
  echo "last-($LINE)*(2/$C)*(1/2)^$C" >>"$OUT"
#  echo '# ' >>"$OUT"
  C=$[C+2]
done <"$TMP"

rm -f "$TMP"

# Footer
echo 'last+sqrt(3)/32' >>"$OUT"
echo 'last*24' >>"$OUT"
echo 'quit' >>"$OUT"

# Run the generated script
BC_LINE_LENGTH=0 bc "$OUT"