/* 070209-5.c
 * 45 min
 */
#include <stdio.h>

void  DiaSis (int *dd, int *mm, int *aa);
long  DiaJul (int dd, int mm, int aa);
void  DiaGrg (long jul, int *dd, int *mm, int *aa);
int   DiaSem (long jul);
char *TxtMes (int mes);

void PrnMes (void);

void main (void)
{
  PrnMes ();
}

void PrnMes (void)
{
  int d, m, a;
  long jul;
  int  i, dem; /* Dias este mes */
  int  ds;

  DiaSis (&d, &m, &a);
  printf ("%d %s\n", a, TxtMes(m));
  printf ("   L   M   M   J   V   S   D\n");
  jul = DiaJul (1, m,   a);
  dem = DiaJul (1, m+1, a) - jul; /* Cálculo de días de este mes */
  ds = DiaSem (jul);
  for (i = 0; i < ds; i++)
    printf ("    ");
  for (i = 1; i <= dem; i++) {
    printf ("%4d", i);
    if (ds == 6) {
      printf ("\n");
      ds = 0;
    }
    else
      ds++;
  }
}

/* 10-r06-funciones.c */
#include <time.h>

void DiaSis (int *dd, int *mm, int *aa)
{
  time_t timer;
  struct tm *stm;

  timer = time (NULL);
  stm = localtime (&timer);

  *dd = stm->tm_mday;
  *mm = stm->tm_mon + 1;
  *aa = stm->tm_year + 1900;
}

void HorSis (int *hh, int *mm, int *ss)
{
  time_t timer;
  struct tm *stm;

  timer = time (NULL);
  stm = localtime (&timer);

  *hh = stm->tm_hour;
  *mm = stm->tm_min;
  *ss = stm->tm_sec;
}

long DiaJul (int dd, int mm, int aa)
{
  long jul;
  int  ja,
       jy,
       jm;

  jy = aa;

  if (jy == 0)
    return -1; /* No hay año 0 */

  if (jy < 0)
    ++jy;

  if (mm > 2) {
    jm = mm + 1;
  }
  else {
    --jy;
    jm = mm + 13;
  }

  jul =  (long) (365.25  * jy) +
         (long) (30.6001 * jm) +
                dd +
                1720995;

  if (dd + 31L * (mm + 12L * aa) >= (15 + 31L * (10 + 12L * 1582))) {
    ja = (int) (0.01 * jy);
    jul += 2 - ja + (int) (0.25 * ja);
  }

  return jul;
}

void DiaGrg (long jul, int *dd, int *mm, int *aa)
{
  long ja, jal, jb, jc, jd, je;

  if (jul >= 2299161) {
    jal = ((float) (jul - 1867216) - 0.25) / 36524.25;
    ja = jul + 1 + jal - (long) (0.25 * jal);
  }
  else if (jul < 0)
    ja = jul + 36525 *( 1 - jul / 36525);
  else
    ja = jul;
  jb = ja + 1524;
  jc = (long) (6680.0 + ((float) (jb - 2439870) - 122.1) / 365.25);
  jd = (long) (365 * jc + (0.25 * jc));
  je = (long) ((jb - jd) / 30.6001);
  *dd = jb - jd - (long) (30.6001 * je);
  *mm = je - 1;

  if (*mm > 12)
    *mm -= 12;
  *aa = jc - 4715;
  if (*mm > 2) --(*aa);
  if (*aa <= 0) --(*aa);
  if (jul < 0)
    *aa -= 100 * (1 - jul / 36525);
}

int DiaSem (long jul)
{
  return jul % 7;
}

static char *vTxtDsm [] = {
  "lunes",
  "martes",
  "miércoles",
  "jueves",
  "viernes",
  "sábado",
  "domingo"
};

char *TxtDsm (int dsm)
{
  return vTxtDsm [dsm];
}

static char *vTxtMes [] = {
  "error",
  "enero",
  "febrero",
  "marzo",
  "abril",
  "mayo",
  "junio",
  "julio",
  "agosto",
  "septiembre",
  "octubre",
  "noviembre",
  "diciembre"
};

char *TxtMes (int mes)
{
  return vTxtMes [mes];
}