<?php
// Some routines generated from Astronomical Algorithms (2nd edition) by Jean Meeus

function JulianDay( $theyear, $themonth, $theday)
{
    // See Meeus page 60
    $Y= $theyear;
    $M= $themonth;
    $D= $theday;
    if ( $M < 3 ) {
	$Y= $Y - 1;
	$M= $M +12;
    }
    $A= (int)( $Y / 100 );
    $B= 2 - $A + (int)( $A / 4);
    return( (int)(365.25*($Y+4716)) + (int)(30.6001*($M+1)) + $D + $B - 1524.5);
}

function thedate2J( $thedate)
{
    return( JulianDay( substr( $thedate, 0, 4), substr( $thedate, 4, 2), substr( $thedate, 6, 2)));
}

function CarringtonRotation( $thejulianday)
{
    // See Meeus 29.1, page 191
    // Meeus says this can be off by 0.16 days
    // there is a corrective formula (29.2) in the book, if this turns out to be a problem.
    return (int) (($thejulianday - 2398140.227 ) / 27.2752316);
}

function cr2J( $thecr)
{
    return 2398140.2270 + 27.2752316 * $thecr;
}

function J2cr( $thejul)
{
    return CarringtonRotation( $thejul);
}

function J2date( $thejul)
{
    $Z= (int) ( $thejul + 0.5 );
    $F= ( $thejul + 0.5 ) - $Z;
    if ( $Z < 2299161 ) 
	$A= $Z;
    else {
	$alpha= (int) ( ( $Z - 1867216.25 ) / 36524.25 );
	$A= $Z + 1 + $alpha - (int) ( $alpha / 4);
    }
    $B= $A + 1524;
    $C= (int) ( ( $B - 122.1 ) / 365.25 );
    $D= (int) ( 365.25 * $C );
    $E= (int) ( ( $B - $D ) / 30.6001 );
    $theday= $B - $D - (int) (30.6001 * $E ) + $F;
    if ( $E < 14 )
	$themonth= $E - 1;
    else
	$themonth= $E - 13;
    if ( $themonth > 2 )
	$theyear= $C - 4716;
    else
	$theyear= $C - 4715;

    return sprintf( "%04d%02d%02d", $theyear, $themonth, $theday);
}

function CRstartdate( $thecr)
{
    return( J2date( cr2J( $thecr)));
}

function CRenddate( $thecr)
{
    return( J2date( cr2J( $thecr+1)-1));
}

?>