Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).

Example of an expected output:

./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29


Related tasks
 Day of the week
 Five weekends
 Last Friday of each month


 
rem - return p mod q
function mod(p, q = integer) = integer
end = p - q * (p/q)
 
comment
    return day of week (Sun = 0, Mon = 1, etc.) for a
    given Gregorian calendar date using Zeller's congruence
end
function dayofweek (mo, da, yr = integer) = integer
    var y, c, z = integer
    if mo < 3 then
       begin
          mo = mo + 10
          yr = yr - 1
       end
    else mo = mo - 2
    y = mod(yr,100)
    c = int(yr / 100)
    z = int((26 * mo - 2) / 10)
    z = z + da + y + int(y/4) + int(c/4) - 2 * c + 777
    z = mod(z,7)
end = z
 
rem - return true if y is a leap year
function isleap(y = integer) = integer
end = mod(y,4)=0 and mod(y,100)<>0 or mod(y,400)=0
 
rem - return number of days in specified month
function monthdays(m, y = integer) = integer
    var n = integer
    if m = 2 then
        if isleap(y) then
            n = 29
        else
            n = 28
    else if (m = 4) or (m = 6) or (m = 9) or (m = 11) then
        n = 30
    else
        n = 31
end = n
 
comment
   return the day of the month corresponding to the last
   occurrence of weekday k (Sun=0, Mon=1, etc.) in the given
   month and year
end
function lastkday(k, m, y = integer) = integer
   var d, w = integer
   rem - determine weekday for last day of the month
   d = monthdays(m, y)
   w = dayofweek(m, d, y)
   rem - back up as needed to desired weekday
   if w >= k then
      d = d - (w - k)
   else
      d = d - (7 - (k - w))
end = d
 
rem - return abbreviated month name
function shortmonth (m = integer) = string
end = mid("JanFebMarAprMayJunJulAugSepOctNovDec", m*3-2, 3)
 
rem - main program starts here
 
$constant SUNDAY = 0
var m, y = integer
input "Display last Sundays in what year"; y
for m = 1 to 12
   print shortmonth(m);" ";lastkday(SUNDAY, m, y)
next m
end