#!/bin/csh
#
#  script computes the day, month and year given the julian day from Jan. 1, 1969.
#  
# INPUTS
set outtype     = $1      # 1 = day-of-year output, 2 = month and day number output
set julian1969  = $2      # julian day from 1/1/1969


set cday0 = (0 31 59 90 120 151 181 212 243 273 304 334 365)
set cday1 = (0 31 60 91 121 152 182 213 244 274 305 335 366)

@ jday = 0
@ year = 1968
while ($jday < $julian1969)
  @ year ++
  if(($year % 4 == 0 && $year % 100 != 0) || $year % 400 == 0) then
    @ leap = 1
    @ jday = $jday + 366    # leap year
  else
    @ leap = 0
    @ jday = $jday + 365    # not leap year
  endif
end

@ yeardif  = $year - 1969
@ totdays  = $yeardif * 365
@ leapdays = $yeardif / 4
@ totdays  = $totdays + $leapdays
@ jday     = $julian1969 - $totdays

if ($outtype == 1) then
  @ month = 1
  @ day   = $jday
else
  @ imon = 2
  @ cdaytot = 0
  while ($imon <= 13)
    if($leap == 1) then 
       @ cdaytot = $cday1[$imon]
    else
       @ cdaytot = $cday0[$imon]
    endif
    if($cdaytot >= $jday) then
       @ month = $imon - 1
       if($leap == 1) then
         @ day = $jday - $cday1[$month]
       else
         @ day = $jday - $cday0[$month]
       endif
       break
    endif
    @ imon ++
  end
endif 

echo $year $month $day
