def book_maker(data_table, lookup_table, savepath, sort_column, max_i=-1, reverse=True):
    """ A function to make lightcurve-and-period books.
    
    Inputs:
      data_table -- an ATpy table with time-series photometry.
      lookup_table -- an ATpy table with star names, IDs, and other parameters
      savepath -- Where to save output files to
      sort_column -- (str) a column in lookup_table to sort the book by.

    Optional inputs:
      max_i -- how many stars to go through before stopping
               (defaults to all of them)
      reverse -- whether to iterate over the sorted column backwards
                 (defaults to True)
    """

    # First, let's sort our lookup table by the sort column
    lookup_table.sort("%s" % sort_column)

    # This is SO HACKISH
    if reverse:
        look_table = reversed(lookup_table)
    else:
        look_table = lookup_table

    # For each star
    for row, i in zip(look_table, np.arange(len(lookup_table))):

        desig = row["Designation"]
        name = "p%d.%d" % (desig, round(row["fraction"] * 100, 0))
        sid = row["SOURCEID"]
        # For each season

        for season in [0, 1, 2, 3]:
            outname_a = savepath + ("%.3d_%.3d" % (i, desig)) + "." + str(season) + "a"

            outname_b = savepath + ("%.3d_%.3d" % (i, desig)) + "." + str(season) + "b"

            tr.plot_5(data_table, sid, outfile=outname_a, name=name, season=season, png_too=True)
            tr.plot_page_periods(data_table, sid, outfile=outname_b, name=name, season=season, png_too=True)

        print name + " is done"

        if i == max_i:
            break
import atpy
import numpy as np
import matplotlib.pyplot as plt
import tr

datapath = '/home/tom/reu/DATA/Merged_Catalogs/'
savepath = '/home/tom/reu/logs/feb_15_2011/huge/'

# Let's load up our data...

wc = atpy.Table(datapath + 'wserv_errbits_combined.fits')

goods = atpy.Table(datapath + '5_sigma_disks_good1.fits')

for row in goods:
    desig = row['Designation']
    name = "p%d.%d" % ( row[4], round(row[3]*100, 0) )
    sid = row[0]
    
    for season in [1,2,3]:
        outname = savepath+ ("%.3d" % desig) + "." + str(season) + ".pdf"
        outname_png = ( savepath+"png/"+ ("%.3d" % desig) + 
                        "." + str(season) + ".png" )
        tr.plot_5(wc, sid, season=season, name=name, outfile=outname)
        tr.plot_5(wc, sid, season=season, name=name, outfile=outname_png)

    print name + " is done"