# Variable calculations should be done in this file.
# It is read and interpreted by wims for all valid calls to the module.

n=!trim $n
!bound type within prime,base default prime
!bound list between integer 1 and 20 default 10
prime_limit=40000

histcnt=!itemcnt $hist
!if $start=back and $histcnt>=2
 start=!item -2 of $hist
 !if $histcnt>2
  hist=!items 1 to -3 of $hist
 !else
  hist=
 !endif
!endif 
!if $start!=$empty
 start=$[abs(floor($start))]
 !if NaN isin $start or Inf isin $start or $start>$prime_limit-1000
  start=
 !endif
!endif
!default start=0
!if $start<=0
 hist=
!endif

# how to detect the need to compute?
!if $cmd!=resume and $n!=$empty
 error=
 compute=yes
 n=!rawmath $n
 test=$[abs($n)]
 !if NaN isin $test
  error=bad_formula
  !exit
 !endif
 !if Inf isin $test or inf isin $test or $test>10^200
  error=too_big
  !exit
 !endif
 !if $test<4
  error=too_small
  !exit
 !endif
 log=$[log($test)]
 !if $log>60
  list=$[min($list,10)]
 !endif
 !if $log>100
  list=$[min($list,5)]
 !endif

 search_prime=for(t=1+$start,$prime_limit,p=prime(t);r=n-p;if(isprime(r),if(2*p>n,break);print(n," ",p," ",r," ",t,",");k++;if(k>=$list,break)))
 search_base=for(add=$start,$list+$start-1,nn=n+2*add;for(t=1,$prime_limit,p=prime(t);r=nn-p;if(isprime(r),if(2*p<=nn,print(nn," ",p," ",r","));break)))
 pariout=!exec pari k=0;n=abs(2*floor($n/2));print(n);\
  $(search_$type)
  print("end")
 !distribute lines $pariout into parin,splits,mark
 splits=!char 1 to -2 of $splits
 count=!itemcnt $splits
 !if $type=base
  next=$[$start+$count]
 !else
  tt=!item $count of $splits
  tt=!word 4 of $tt
  !if $tt!=$empty
   next=$[$tt]
  !else
   next=$start
  !endif
 !endif
 hist=!append item $start to $hist
!endif

histcnt=!itemcnt $hist

