#!/bin/tcsh -f
# This script should work for all years between 1901 and 2099.

if ($#argv < 1) then
  echo "usage: j2g YYYYDDD"
  exit (1)
endif

setenv JULDATE $argv[1]

set yyyy = `echo $JULDATE | cut -c1-4`
set day = `echo $JULDATE | cut -c5-7`

# leap year
if ($yyyy % 4 == 0) then

  # Determine month and day
  if ($day <= 31) then
    set mm = "01"
    @ dd = $day - 0
  else if ($day <= 60) then
    set mm = "02"
    @ dd = $day - 31
  else if ($day <= 91) then
    set mm = "03"
    @ dd = $day - 60
  else if ($day <= 121) then
    set mm = "04"
    @ dd = $day - 91
  else if ($day <= 152) then
    set mm = "05"
    @ dd = $day - 121
  else if ($day <= 182) then
    set mm = "06"
    @ dd = $day - 152
  else if ($day <= 213) then
    set mm = "07"
    @ dd = $day - 182
  else if ($day <= 244) then
    set mm = "08"
    @ dd = $day - 213
  else if ($day <= 274) then
    set mm = "09"
    @ dd = $day - 244
  else if ($day <= 305) then
    set mm = "10"
    @ dd = $day - 274
  else if ($day <= 335) then
    set mm = "11"
    @ dd = $day - 305
  else
    set mm = "12"
    @ dd = $day - 335
  endif
  
else # not leap year

  # Determine month and day
  if ($day <= 31) then
    set mm = "01"
    @ dd = $day - 0
  else if ($day <= 59) then
    set mm = "02"
    @ dd = $day - 31
  else if ($day <= 90) then
    set mm = "03"
    @ dd = $day - 59
  else if ($day <= 120) then
    set mm = "04"
    @ dd = $day - 90
  else if ($day <= 151) then
    set mm = "05"
    @ dd = $day - 120
  else if ($day <= 181) then
    set mm = "06"
    @ dd = $day - 151
  else if ($day <= 212) then
    set mm = "07"
    @ dd = $day - 181
  else if ($day <= 243) then
    set mm = "08"
    @ dd = $day - 212
  else if ($day <= 273) then
    set mm = "09"
    @ dd = $day - 243
  else if ($day <= 304) then
    set mm = "10"
    @ dd = $day - 273
  else if ($day <= 334) then
    set mm = "11"
    @ dd = $day - 304
  else
    set mm = "12"
    @ dd = $day - 334
  endif

endif

# add leading zero to day
if ($dd < 10) set dd = 0$dd

echo "$yyyy $mm $dd"
