#!/bin/sh

mkdir phases
for year in $(seq 1968 2016)
do
    wget -qO - https://www.timeanddate.com/moon/phases/france/paris?year=$year | tr \" \\n | grep -e 'New Moon on ' -e 'First Quarter on ' -e 'Full Moon on ' -e 'Third Quarter on ' | cut -d ' ' -f 1,5,7 | LC_TIME=pt_BR.UTF-8 sort -k 1,1 -k 3M | awk -v year=$year '
BEGIN {
  year -= 1968
  year *= 12 }

$3 == "Janeiro" {month = 1 }
$3 == "Fevereiro" { month = 2 }
$3 == "Março" { month = 3 }
$3 == "Abril" { month = 4 }
$3 == "Maio" { month = 5 }
$3 == "Junho" { month = 6 }
$3 == "Julho" { month = 7 }
$3 == "Agosto" { month = 8 }
$3 == "Setembro" { month = 9 }
$3 == "Outubro" { month = 10 }
$3 == "Novembro" { month = 11 }
$3 == "Dezembro" { month = 12 }

{
  if (month == prev)
    printf "," $2 >> "phases/" $1
  else {
    prev = month
    printf "\n" year + month "," $2 >> "phases/" $1 } }'
done

tr -dc 0-9,\\n < T79JNAIS.csv | tail -n +6 | head -n -1 | cut -d , -f 4- | sed 's/,*$//' > daily_births

for p in New First Full Third
do
    awk -F , -v phase=phases/$p '
BEGIN {
  getline < phase
  getline < phase
  record = $1
  for (i = 1; ++i <= NF; )
    days[$i] = "" }

{
  nb_of_days += NF
  for (i = 0; ++i <= NF; )
    nb_of_births += $i }

FNR == record {
  nb_of_days_of_phase += length(days)
  for (d in days)
    nb_of_births_on_phase += $d
  delete days
  getline < phase
  record = $1
  for (i = 1; ++i <= NF; )
    days[$i] = "" }

END {
  print nb_of_days_of_phase "," nb_of_days - nb_of_days_of_phase "," nb_of_births_on_phase / nb_of_days_of_phase "," (nb_of_births - nb_of_births_on_phase) / (nb_of_days - nb_of_days_of_phase) }
' daily_births | awk -F , -v phase=phases/$p '
BEGIN {
  getline < phase
  getline < phase
  record = $1
  for (i = 1; ++i <= NF; )
    days[$i] = "" }

FILENAME == ARGV[1] {
  n1 = $1
  n2 = $2
  mean1 = $3
  mean2 = $4 }

FILENAME == ARGV[2] {
  for (i = 0; ++i <= NF; )
    var2 += ($i - mean2) * ($i - mean2) }

FILENAME == ARGV[2] && FNR == record {
  for (d in days) {
    var2 -= ($d - mean2) * ($d - mean2)
    var1 += ($d - mean1) * ($d - mean1) }
  delete days
  getline < phase
  record = $1
  for (i = 1; ++i <= NF; )
    days[$i] = "" }

END {
  var1 /= (n1 - 1)
  var2 /= (n2 - 1)
  tmp = var1 / n1 + var2 / n2
  print phase "\n  counts: " n1 " phase days, " n2 " not\n  means: " mean1 " births on a phase day, " mean2 " not\n  variances: " var1 " among phase days, " var2 " not\n  unequal variances t-test: t = " (mean1 - mean2) / sqrt(tmp) " with " tmp * tmp / (var1 * var1 / n1 / n1 / (n1 - 1) + var2 * var2 / n2 / n2 / (n2 - 1)) " degrees of freedom" }' - daily_births
done
# https://www.wolframalpha.com/input/?i=P(X%3E1.44927)+with+t-distribution(649.374) gives 0.0738725
