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 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)
{
    theJ= 2398140.2270 + 27.2752316 * thecr;

    Mdeg= 281.96 + 26.882476 * thecr
    Mrad= ( 2.0 * 3.14159265358979323846 * Mdeg ) / 360.0
    theJ= theJ + 0.1454 * sin( Mrad)
    theJ= theJ - 0.0085 * sin( 2 * Mrad)
    theJ= theJ - 0.0141 * cos( 2 * Mrad)

    return( theJ)
}

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;

    thefractionalday= theday - int( theday)
    thehour= int( thefractionalday * 24)
    theminute= int( ( thefractionalday * 24 - thehour ) * 60.0 )
    return sprintf( "%04d-%02d-%02d/%02d:%02d", theyear, themonth, theday, thehour, theminute);
}

BEGIN	{
    print "setenv DISPLAY \"\""
    print "source /home/peters/stereo/idl/stereo_source_clean"

    scname["a"]= "STEREO-A"
    scname["b"]= "STEREO-B"
}

{
    crnumber= $1
    spacecraft= $2
    plottype= $3

    print "idl -nw <<EOI"
    print ".run /home/peters/stereo/idl_test/sta_summ_plot_sep"
    print "t1='" J2date( cr2J( crnumber ) ) "'"
    print "t2='" J2date( cr2J( crnumber + 1 ) ) "'"
    print "ddir='/disks/stereo/home/www/html/sumplots/carr_rot/'"
    print "timespan, [t1, t2]"
    print "tplot_options,'xmargin',[12,12]"
    print "TIMERES=360d"
    print "st" spacecraft "_summ_plot_sep, ddir+'st" spacecraft "_cr" crnumber "_sep', TIMERES, title = '" scname[spacecraft] " SEP Summary Plot CR" crnumber "'"
    print "tplot_names,names=mytnames"
    print "store_data,delete=mytnames"
    print "EOI"
}