def gen_hivar_periodic_plots(start=0):
    """ 
    Makes glued 3-panel plots for all of the periodic hivars.
    """
    
    counter = 1
    c_max = len(hivar_periodics)

    tables_of_periodics = [autovars_true_periods, autovars_true_periods_s1]

    print 'lol'
    for t in tables_of_periodics:
        print 'lol2'
        # first, the s123 periodics (more than 95% of them)
        for s in t.SOURCEID[start:]:
            # If this is a strict autovar, we give it special stuff.
            if s not in hivar.SOURCEID: continue
            if s in autovars_strict.SOURCEID:
                flag = "s_"
            else:
                flag = ""

            # Let's make 3 plots. LC, folded, and pgram. Save em all into a place.
            plot3.graded_lc(data, s, abridged=True, color_slope=True, 
                            timecolor=True, name=flag+str(s),
                            outfile=hivar_per_path+"%s_lc.png"%str(s))


            plot3.graded_phase(data, s, timecolor='time', 
                               name=flag+str(s),
                               period=t.best_period[t.SOURCEID==s], 
                               color_slope=True, outfile=hivar_per_path+"%s_phase.png"%str(s))

            try:
                plot3.lsp_power(data, s, outfile=hivar_per_path+"%s_pgram.png"%str(s))
            except Exception, e:
                print "periodogram failed for %s" % str(s)
                print e


            # now glue em together!
            call(["montage","-mode", "concatenate", "-tile", "2x", 
                 hivar_per_path+"%s_*.png" % str(s), 
                  hivar_per_path_g+flag+"%s-glued.png" % str(s) ])


            print "Completed plot %d of %d" % (counter, c_max)
            counter += 1
def gen_lowvar_periodic_plots(start=0, stop=len(low_strict_periodics)):
    """
    Creates all the lowvar-strict plots in one shot.

    """
    
    counter = 1
    c_max = len(low_strict_periodics)

#    tables_of_periodics = [autovars_true_periods, autovars_true_periods_s1]

    print 'lol'
#    for t in tables_of_periodics:
#    print 'lol2'
        # first, the s123 periodics (more than 95% of them)
    for s in low_strict_periodics.SOURCEID[start:]:
        # If this is a strict autovar, we give it special stuff.
#        if s not in hivar.SOURCEID: continue
        # Let's make 3 plots. LC, folded, and pgram. Save em all into a place.
        plot3.graded_lc(data, s, abridged=True, color_slope=True, 
                        timecolor=True, name=str(s),
                        outfile=lowvar_per_path+"%s_lc.png"%str(s))
        
        
        plot3.graded_phase(data, s, timecolor='time', 
                           name=str(s),
                           period=low_strict_periodics.best_period[
                low_strict_periodics.SOURCEID==s], 
                           color_slope=True, 
                           outfile=lowvar_per_path+"%s_phase.png"%str(s))
        
        try:
            plot3.lsp_power(data, s, 
                            outfile=lowvar_per_path+"%s_pgram.png"%str(s))
        except Exception, e:
            print "periodogram failed for %s" % str(s)
            print e
            
            
        # now glue em together!
        call(["montage","-mode", "concatenate", "-tile", "2x", 
              lowvar_per_path+"%s_*.png" % str(s), 
              lowvar_per_path_g+"%s-glued.png" % str(s) ])
        
        
        print "Completed plot %d of %d" % (counter, c_max)
        counter += 1
def gen_periodic_plots(start=0):
    """ 
    Makes glued 3-panel plots for all of the periodic variable candidates
    """

    for s in subjective_periodics.SOURCEID[start:]:
        # Let's make 3 plots. LC, folded, and pgram. Save em all into a place.

        plot3.graded_lc(data, s, abridged=True, color_slope=True, timecolor=True, outfile=path1 + "%s_lc.png" % str(s))

        plot3.graded_phase(
            data,
            s,
            timecolor="time",
            period=subjective_periodics.best_period[subjective_periodics.SOURCEID == s][0],
            color_slope=True,
            outfile=path1 + "%s_phase.png" % str(s),
        )

        try:
            plot3.lsp_power(data, s, outfile=path1 + "%s_pgram.png" % str(s))
        except Exception, e:
            print "periodogram failed for %s" % str(s)
            print e

        # now glue em together!

        call(
            [
                "montage",
                "-mode",
                "concatenate",
                "-tile",
                "2x",
                path1 + "%s_*.png" % str(s),
                path2 + "%s-glued.png" % str(s),
            ]
        )
def gen_ukvar_all(start=0, stop=len(ukvar)):
    """ 
    Creates all the UKvar plots in one shot.

    Uses the UKvar ID as the primary identifier; lists info
    in the filename distinguishing auto/strict/subj, plus per/nonper
    I'm thinking: 'a' for autovar, 't' for strict, 'j' for subj,
    'p' for periodic, 'n' for nonperiodic. Each dude gets two letters.

    if periodic:
        do the gluedvars stuff
    else:
        just a normal lightcurve!

    """

    for s, id, i in zip(ukvar.SOURCEID, ukvar.UKvar_ID, 
                        range(len(ukvar)))[start:stop]:

        # Each plot gets a suffix: ('a'|'t'|'j')+('p'|'n')
        
        suffix = suffix_generator(ukvar, i)

        # Periodics first

        if ukvar.periodic[i] == 1:
            
            # Dig up the best period for this dude! 3 main cases.

            if ukvar.autovar[i] == 1:
                if s in autovars_true_periods.SOURCEID:
                    t = autovars_true_periods
                elif s in autovars_true_periods_s1.SOURCEID:
                    t = autovars_true_periods_s1
                else:
                    raise Exception("Something weird happened!")
            else:
                t = conf_subj_periodics
                
            best_period = t.best_period[t.SOURCEID == s][0]

            # Let's make 3 plots. LC, folded, and pgram. Save em all into a place.
            # print out the names as ID_fs_lc.png
            plot3.graded_lc(data, s, abridged=True, color_slope=True, 
                            timecolor=True,
                            name = "%s:  UKvar %s (%s)" %
                            (str(s), str(id), suffix),
                            outfile=ukvar_path_ng+"%s_%s_lc.png" %
                            (str(id), suffix))

            # ID_fs_phase.png
            plot3.graded_phase(data, s, timecolor='time', color_slope=True,
                               period=best_period, 
                               name = "%s:  UKvar %s (%s)" %
                               (str(s), str(id), suffix),
                               outfile=ukvar_path_ng+"%s_%s_phase.png" % 
                               (str(id), suffix))
            # ID_fs_pgram.png
            try:
                plot3.lsp_power(data, s, 
                                name = "%s:  UKvar %s (%s)" %
                                (str(s), str(id), suffix),
                                outfile=ukvar_path_ng+"%s_%s_pgram.png" %
                                (str(id), suffix))
            except Exception, e:
                print "periodogram failed for %s" % str(s)
                print e


# now glue em together!
                
            try:
                call(["montage","-mode", "concatenate", "-tile", "2x", 
                      ukvar_path_ng+"%s_%s*.png" % (str(id), suffix), 
                      ukvar_path+"%s_%s.png" % (str(id), suffix) ])
            except Exception, e:
                print "Why did montage fail?"
                raise e
middle_phase_end = 0.55

v1916ori_phase = ((v1916ori_data.MEANMJDOBS-54034) % v1916ori_period) / v1916ori_period

v1916ori_out_of_eclipse = v1916ori_data.where((v1916ori_phase > min_phase) &
	                                          (v1916ori_phase < max_phase) & 
	                                          ((v1916ori_phase < middle_phase_start) |
	                                           (v1916ori_phase > middle_phase_end)) )

print len(v1916ori_out_of_eclipse)
print "Datapoints removed: {0}".format(len(v1916ori_data) - len(v1916ori_out_of_eclipse))

print "Stetson of V1916 Ori, full data: {0}".format(Stetson_machine(v1916ori_data, flags=256))
print "Stetson of V1916 Ori out of eclipse: {0}".format(Stetson_machine(v1916ori_out_of_eclipse, flags=256))

plot3.graded_phase(v1916ori_out_of_eclipse, v1916ori_sid, period=v1916ori_period, timecolor=True,
	               name="V1916 Ori, eclipse data removed")

plot3.graded_phase(v1916ori_data, v1916ori_sid, period=v1916ori_period, timecolor=True,
	               name="V1916 Ori, with eclipses")


# V2716 Ori has SOURCEID: 44199508497099
v2716ori_sid = 44199508497099
v2716ori_data = source_photometry.where(source_photometry.SOURCEID == v2716ori_sid)

# I looked at the lightcurve and concluded that all eclipses can be removed by excluding data where H is fainter than 13.7928 

v2716ori_Hmag = v2716ori_data.HAPERMAG3

v2716ori_out_of_eclipse = v2716ori_data.where(v2716ori_Hmag < 13.7928)
def do_it_all( table, sid_list, name_list, path='', 
               option=['lc','tables','phase'] ):
    """ 
    Does some stuff. Not sure exactly what yet, but I'll 
    want it to make tons of plots and tables for a list of 
    SOURCEIDs and their corresponding data.
    
    Parameters
    ----------
    table : atpy.Table 
        The WFCAM time-series data to be extracted
    sid_list : (list or array) of int
        SOURCEIDs of stars to be analyzed
    name_list : list of str
        Names that correspond to each SOURCEID: will be used in
        the filename and title section of each plot, and in the tables
    path : str
        The parent file path to save the output to. 
        Please make sure it has a "/" at the end of it.
    option : list of str, optional
        Which sub-components of this function you'd like to actually
        call. Default is all (lc, tables, phase).

    Returns
    -------
    I don't know yet. Probably nothing.
    Produces a bunch of files, though!

    
    Notes:
    The input data must already be cleaned via some other method.
    
    """

    # until we figure out orion seasons...
    season = 0

    if path=='' or type(path) is not str:
        print "`path` must be a string. Exiting without action."
        return
    
    # Force `path` to have a trailing forward slash
    path = path.rstrip('/')+'/'
    
    ## First, make directories for everything (or try, at least).

    # Structure of directories:
    #  path/lc
    #  path/phase
    #  path/tables
    # within each of those (now it's a *),
    #  path/*/(s1 | s2 | s3 | s123)
    # Within lc/s*, we put the files directly in.
    # Within phase/s*, we do
    #  path/phase/s*/(h_fx2 | h_lsp | j_fx2 | j_lsp | k_fx2 | k_lsp | lsp_power)
    # Within tables/s*, we put the files directly in.

    mkdir_p(path+"lc/")
    mkdir_p(path+"phase/")
    mkdir_p(path+"tables/")

#    ss = ['s1', 's2', 's3', 's123']
    types = ['h_fx2', 'h_lsp', 'j_fx2', 'j_lsp', 'k_fx2', 'k_lsp', 'lsp_power']

#    for s in ss:
    mkdir_p(path+"lc/")
    mkdir_p(path+"tables/")
    for t in types:
        mkdir_p("%sphase/%s"%(path,t))
            
    # We should now be done making directories. Let's test this.
    # Tested! Woo.

    ## Second, let's make tables.

    tables = path+"tables/"

    if 'tables' in option:

        tables = path+"tables/"

        # Make a lookup table. It should have a column with the `name_list`
        # parameter we fed into this function, as well as a column with the 
        # SOURCEIDs.
        # They should be named "SOURCEID" and "Designation", respectively.
    
        lookup = atpy.Table()
        lookup.add_column("SOURCEID", sid_list)
        lookup.add_column("Designation", name_list)
        
#        for season, s in zip([1,2,3,123], ss):
            
        # Write the spreadsheet and save it to the relevant directory.
        spread3.spreadsheet_write(table, lookup, season, 
                                  tables+s+'/spreadsheet.fits', 
                                  flags=256, per=True)
            

    # What command do we want to make plots?
    # Probably plot3.lc and plot3.phase, which are going to be almost 
    # identical to plot2 equivalents except that they can handle missing data 
    # and flags and stuff.

    ## Third, make lightcurves.
    # And put the gorram Stetson index in the title!

        
#    for season, s in zip([1,2,3,123], ss):

    s_stats = atpy.Table(tables+'/spreadsheet.fits')

    for name, sid in zip(name_list, sid_list):
        # The specific plot command we use here depends a lot
        # on what functions are available.
        if 'lc' in option:
            tplot.graded_lc(table, sid, season=0, name=name, #flags=16,
                            outfile=path+"lc/"+name, png_too=True,
                            abridged=True, color_slope=True) 
#png, eps, pdf




        # A bunch of the following code will be substantially rewritten
        # once "spread3" is functional.

        # Well... spread3 is now functional!
        if 'phase' in option:
            for t in types:
                if t == 'lsp_power':
                    tplot.lsp_power(table, sid, season=0, name=name,
                                    outfile=path+"phase/lsp_power/"+name, 
                                    png_too=True) 
                    
                else:
                    per = s_stats.data[t+"_per"][s_stats.SOURCEID == sid]
                    tplot.graded_phase(table, sid, period=per, season=0, 
                                       name=name, color_slope=True,
                                       outfile=path+"phase/"+t+"/"+name, 
                                       png_too=True) 
                
                # elif t == 'k_fx2':
                #     tplot.phase(table, sid, season=season, name=name,
                #                 outfile=path+"phase/"+s+"/k_fx2/"+name, 
                #                 png_too=True) 
                # elif t == 'k_lsp':
                #     tplot.phase(table, sid, season=season, name=name,
                #                 period='lsp',
                #                 outfile=path+"phase/"+s+"/k_lsp/"+name, 
                #                 png_too=True) 

                # else:
                #     pass


    return