Implementing Generators/Yield in Languages Without Support

As a follow up to my previous post, I intent to go into detail how generators are actually implemented in a language. The way I intend to do this is to actually implement the generator paradigm without using language provided tools such as keywords. The first step to this process is actually understanding what is happening when you use the yield keyword. Perhaps an simple walk through will be illustrative.

A function that wishes to use a generator will iterate over that generator. To the function using the generator, the generator acts more like a data structure that implements the enumerable (iterable) interface than a function at all. The generator function cannot be called except by iterating over it. This is the proper way to think of a generator, a data structure. If you are only using a generator, than this is all you need to know. Implementing a generator requires a little more detail. Let's examine a the most basic generator, one that counts down. This example uses, C#, but the syntax is only slightly different than other languages such as python.
public IEnumerable<int> count(int start, int end)
{
   int counter = end;
   while (counter <= end)
   {
      yield return counter;
      counter++;
   }
}
I used a while loop here intentionally so the control flow is obvious. Up until the yield statement, everything is normal. So what is happening at "yield return counter"? The function execution stops and returns the variable counter for each "call" happening indirectly through the iterator. So what happens the next time the iterator issues a call to this function? Well, the execution picks up at counter++! But what is the value of counter? The special yield return statement is saving the entire state of the generator(local variables, instruction pointer, and any other state information), allowing the generator to be resumed exactly where it left off. I'll get to that other information later. To wrap up the basic, right before yielding a value, save the state of the generator. Upon entering the generator again, restore the saved state and jump to where we left off.

Let's examine another example. This time we will be looking at a recursive implementation of our count generator. I'm going to be intentionally avoiding the use of foreach to bring out the enumerator (iterator).
public IEnumerable<int> count(int start, int end)
{
   yield return start;
   if (start != end)
   {
      // foreach (int result in count(start + 1, end))
      // {
      //    yield return result;
      // }
      IEnumerator<int> enumerator = count(start + 1, end).GetEnumerator();
      while (false != enumerator.MoveNext())
      {
         yield return enumerator.Current;
      }
   }
}
This generator does the same thing, just in a recursive fashion. The first yield is exactly as the one previously examined. Things get slightly more difficult to keep track when the recursion begins, but the same exact process is followed. The enumerator is saved as part of the state of the count generator. When returning, the iterator is restored and so the generator continues as expected.

If C# allowed us to directly recur on the generator itself instead of iterating over the results as shown below:
public IEnumerable<int> count(int start, int end)
{
   yield return start;
   if (start != end)
   {
      // Will not compile
      yield return count(start + 1, end);
   }
}
then the state would have to include the call stack of the recursion produced by the generator. By explicitly restricting yield to return the enumerated base type (int), we are prevented from this operation because count returns an enumerable type. This makes implementing generators manually easier. We don't have to worry about recursion at all.

So now we get to implementing a generator. The basic ideas have been captured above. We need to save locals upon yielding, restore state upon calling, and allow enumeration. Since we generators are essentially data structures, we are going to have our desired operation (count) be a member function of a class that extends from a Generator class. Then your program can call foreach on this data type. Let's shown the Generator class first.
class Generator<T, State, RetType>

   : IEnumerable<RetType> where T : GeneratorIterator<State, RetType>, new()
{
   public Generator(State initialState)
   {
      this.initialState = initialState;
   }

   private State initialState;

   #region IEnumerable
   public IEnumerator<RetType> GetEnumerator()
   {
      GeneratorIterator<State, RetType> yieldedFunction = new T();
      yieldedFunction.Initialize(initialState);
      return yieldedFunction;
   }

   IEnumerator IEnumerable.GetEnumerator()
   {
      return this.GetEnumerator();
   }
   #endregion
}

public abstract class GeneratorIterator<State, RetType> : IEnumerator<RetType>
{
   public void Initialize(State initialState)
   {
      this.initialState = initialState;
      this.currentState = initialState;
   }

   public RetType YieldReturn(State state, RetType result)
   {
      // Save state before returning
      this.currentState = state;
      return result;
   }

   private State initialState;

   private State currentState;

   private RetType nextResult;

   public abstract RetType function(State currentState);

   #region IEnumerator
   public RetType Current
   {
      get
      {
         return this.nextResult;
      }
   }

   object IEnumerator.Current
   {
      get
      {
         return this.Current;
      }
   }

   public void Reset()
   {
      // Set the state back and invalid nextResult
      this.Initialize(this.initialState);
      this.nextResult = default(RetType);
   }

   public bool MoveNext()
   {
      this.nextResult = this.function(this.currentState);
      return this.currentState != null;
   }

   public void Dispose() { }
   #endregion
}
Let's examine what this class is doing. It is taking a class that is expected to override a member called function. This will be the function that is expected to be using the YieldReturn method provided by this class. Most of the code is setting up the enumerator. The enumerator takes care of calling the function when appropriate. The real magic that enables this class to be a generator is the currentState variable. This is where the function's state is saved. Whenever the function is needed, the function is passed the current state that was saved by YieldReturn. The function is responsible for using the state to produce the expected results.

To actually use the state, we are going to have functions that resemble finite state machines more than traditional functions. This is due to limitations of the C# compiler to allow us to jump to exactly where we need to. Below is a version of the first non recursive count and the appropriate state class representing all locals.
class Count : GeneratorIterator<CountState, int>
{
   public override int function(CountState currentState)
   {
      if (currentState.stateIndex == 0)
      {
         currentState.counter = currentState.start;
         currentState.stateIndex = 1;
         // Proceed to state 1
      }

      if (currentState.stateIndex == 1)
      {
         while (currentState.counter <= currentState.end)
         {
            // Set the next state
            currentState.stateIndex = 2;
            // yield return
            return YieldReturn(currentState, currentState.counter);
         }

         // Signal no more to yield, normally accomplished by reaching end of the function
         return YieldReturn(null, default(int));
      }

      if (currentState.stateIndex == 2)
      {
         currentState.counter = currentState.counter + 1;
         currentState.stateIndex = 1;
         // Use recursion to jump to state already passed
         return function(currentState);
      }
      
      // Can only get here if an invalid stateIndex was given
      throw new Exception("Unreachable");
   }
}

class CountState
{
   public int stateIndex;
   public int start;
   public int end;
   public int counter;
}
The stateIndex variable of the CountState class is used to determine where in the code path we left off. The function has no locals to avoid having variables no properly restored when upon reentry. To use this generator, we simply instantiate the wrapper and then the class behaves as all enumerator types do.
CountState initialState = new CountState
{
   start = 0,
   end = 5,
   stateIndex = 0
};

Generator<Count, CountState, int> generator = new Generator<Count, CountState, int>(initialState);
foreach (int result in generator)
{
   Console.WriteLine(result);
}
To illustrate that recursion is supported, I am translated the recursive count above to an appropriate finite state machine. You can try for yourself, but you can observe that there is no need to save a call stack to support recursion in your generators.
class RecursiveCount : GeneratorIterator<RecursiveCountState, int>
{
   public override int function(RecursiveCountState currentState)
   {
      if (currentState.stateIndex == 0)
      {
         currentState.stateIndex = 1;
         return YieldReturn(currentState, currentState.start);
      }

      if (currentState.stateIndex == 1)
      {
         if (currentState.start == currentState.end)
         {
            // We are done, signal no more results in this generator
            currentState.stateIndex = 3;
         }
         else
         {
            /// repeat
            currentState.recursiveCall = new Generator<RecursiveCount, RecursiveCountState, int>(
               new RecursiveCountState
                  {
                     start = currentState.start + 1,
                     end = currentState.end,
                     stateIndex = 0
                  }).GetEnumerator();
            // Go to state 2
            currentState.stateIndex = 2;
         }
      }

      if (currentState.stateIndex == 2)
      {
         while (false != currentState.recursiveCall.MoveNext())
         {
            return YieldReturn(currentState, currentState.recursiveCall.Current);
         }

         // We are done, signal no more results in this generator
         currentState.stateIndex = 3;
      }

      if (currentState.stateIndex == 3)
      {
         return YieldReturn(null, default(int));
      }

      throw new Exception("Unreachable");
   }
}

class RecursiveCountState
{
   public int stateIndex;
   public int start;
   public int end;
   public IEnumerator<int> recursiveCall;
}
I hope that this has been informative of the inner workings of generators and the yield statement. Please comment below with any questions.

Yield statement in C#

My great friend recently did on his wonderful blog covered in a recent post the basics of generators in Python. To further my own knowledge about generators, especially in the language I use most at work, I decided to port his permutation function to C#, yield statement and all.

To basically reiterate what my friend stated, the yield statement allows a function's state to be saved. For functions that are designed to generate a set of data to be iterated over this is great. Instead of computing the entire list and storing the results in memory, the function is able to pick up where it left off and generate the next element of the set when requested. Here is an example with a function that generates permutations.


   private static IEnumerable<string> Permutations(string input)
   {
      List<string> result = new List<string>();
      if (string.IsNullOrEmpty(input))
      {
         yield return string.Empty;
      }
      else
      {
         for (int i = 0; i < input.Count(); i++)
         {
            foreach (string permutation in Permutations(input.Substring(0, i) + input.Substring(i + 1)))
            {   
               yield return input[i] + permutation;
            }
         }
      }
   }
If you iterate over this function, you will notice that the entire list is never generated entirely in memory. The syntax would be something along the lines of:
   foreach (string permutation in Permutations("vegetable"))
      {
         System.Console.WriteLine(permutation);
      }
Thanks to my friend for helping me understand this topic and bring attention to features of a language I use every day.

Time Lapse

Recently, I set up my server with a copy of Yawcam on my home server. The initial plan was to experiment with using a webcam for security purposes, but found myself a little creeped out. I decided to turn the camera away from the door and out to the window. I set the software to take a picture every 10 seconds for a full day. You can see the results on Vimeo.

Formatting Lilypond Sheet Music for the Kindle

Tired of fumbling around with my collection of sheet music looking for a certain piece, I thought it would be great to have some sheet music on my third generation kindle (now called the Kindle Keyboard). I have always been a fan of the open source program Lilypond. Lilypond is a TeX-like system where sheet music is written to a text file and then compiled into the desired output.
Since Lilypond is similar to Tex, Lilypond files have incredible control of the output. No exception is adjusting paper dimensions, only a simple command is required:
\paper {
   paper-height = H\mm
   paper-width = W\mm
}
where H is the desired height in millimeters and W is the desired width in millimeters of the output paper. Since the kindle was a "fit-to-width" option for PDFs, the first step is to figure out the aspect ratio of the display. Once we have the aspect ratio, then we can configure the scaling to make the actual output legible from a reasonable distance. At first I thought that this would be easy. The Kindle has a resolution of 600x800, or an aspect ratio of 3:4 (the screen is taller than it is wide). However, when creating sheet music of this ratio and the display mode of the Kindle set to "fit-to-width", the pages spanned multiple virtual pages. This meant that the music was cut off between virtual pages. This makes playing the music impossible. From here I decided to figure out the ratio by creating a bunch of files of varying ratios and testing the output.

It turns out that the Kindle is doing a little fudging on the display and allows a range of display ratios that will appear as one virtual page. From what I observe, any ratio between .57-.61. I tried many variations and it also seems there is some other logic going on in the "fit-to-width" option and determining when to page, but this is a decent rule of thumb to work with. Now that we have a few aspect ratios to work with, I wanted to figure out some nice paper size in absolute terms such that Lilypond will output notes about the same size as normal sheet music.

At first I tried 100mm x 59mm. As you can see, the notes were extremely large and didn't allow many notes to displayed at once. This would making paging an annoying operation while trying to play the music.
Next I doubled everything. I found 200mm x 122mm appears nice.

Compared to actual sheet music, the font is a little small, but completely usable. If you want a bigger font and don't mind paging frequently, I tried the in the between, 150mm x 80mm.

This is the closest to actual size, but fine tuning could be done.

It is worth noting that while doing this, the "fudge" factor I mentioned earlier, or variability in determining the aspect ratio of the virtual page the Kindle will chose to display, is frustrating. These values I found through trial and error by generating many sheet music files, and looking at all of them.

Custom HTML "Widgets" for ASP.NET MVC3

I was experimenting with ASP.NET MVC3 and found myself in need of some HTML outputted by the Razor engine that would need to be used many times. I wanted to follow the DRY (Don't Repeat Yourself) principle by having the HTML appear in one spot and allow me to use it many times. Ideally I wanted something like the builtin HTML "widgets".

   @Html.DropDownList("DropDownID", Model.Items)

The way I accomplished this was extension methods. Extension methods are an interesting way to add functionality to a class without inheritence. There are drawbacks, such as not being able to access protected members of the base class, but for some cases this is ok.

I decided to use extension methods to add a method to the class that corresponded to the @Html object in the Razor engine. I found out that this class was the HtmlHelper class in the System.Web.Mvc namespace. By extending the HtmlHelper class via extension methods, I was able to achieve my goal of adding a custom widget.

namespace MvcHtml
{
   using System.Web.Mvc;

   public static class ExtensionHtml
   {
      public static MvcHtmlString CustomWidget(this HtmlHelper htmlHelper, string property)
      {
         TagBuilder tagBuilder = new TagBuilder("div");
         tagBuilder.SetInnerText(property);
         return new MvcHtmlString(tagBuilder.ToString());
      }
   }
}

After this little bit of work, we are ready to use the custom widget in our view template just as traditional widgets provided for us.

   @Html.CustomWidget("SampleProperty")

I hope this helps people understand how Razor is producing HTML from these view files!

Combining the Decorator Pattern with the Template Method Pattern

Design patterns are exactly that, patterns of design. These patterns have been determined to appear frequently throughout software development. These patterns appear so often that they have become well documented and given names. I cannot recommend more highly the book Design Patterns by the "Gang of Four" as a resource on the topic of patterns. Recently I came across the need to combine to of the most common patterns, the decorator pattern and the template method pattern. I needed multiple implementation of a class to simultaneously coexist, the template method pattern, and I also needed to be able to decorate these classes, the decorator pattern. I noticed that while combining these two patterns, the decorator class behaves just as another class that implements the template method.
/* The template method */
interface AbstractClass
{
   void Method();
}

/* One implementation */
class ConcreteClass1 : AbstractClass
{
   public void Method()
   {
      System.Console.WriteLine("   ConcreteClass1");
   }
}

/* Second implementation */
class ConcreteClass2 : AbstractClass
{
   public void Method()
   {
      System.Console.WriteLine("   ConcreteClass2");
   }
}

/* Now comes the decorator, which feels just like any other implementation */
abstract class AbstractClassDecorator : AbstractClass
{
   public AbstractClassDecorator(AbstractClass abstractClass)
   {
      this.abstractClass = abstractClass;
   }

   public virtual void Method()
   {
      this.abstractClass.Method();
   }

   protected AbstractClass abstractClass;
}
Now it becomes time to implement the decorators. The nice thing about the decorator pattern is that it allows you to add decorators simply by extending a class. Here I have two decorators.
class ConcreteDecoratedAbstractClass1 : AbstractClassDecorator
{
   public ConcreteDecoratedAbstractClass1(AbstractClass abstractClass)
      : base(abstractClass)
   {
   }

   public override void Method()
   {
      this.abstractClass.Method();
      System.Console.WriteLine("   Decorator1");
   }
}

class ConcreteDecoratedAbstractClass2 : AbstractClassDecorator
{
   public ConcreteDecoratedAbstractClass2(AbstractClass abstractClass)
      : base(abstractClass)
   {
   }

   public override void Method()
   {
      this.abstractClass.Method();
      System.Console.WriteLine("   Decorator2");
   }
}
And now that the patterns are in place, all we have to do is simply use them. Because of the decoration and template pattern, we are able to create many possibilities to execute the "same" method. We can decorate or not decorate with any of the decorators, and we have multiple implementations of each method.
class Program
{
   static void Main(string[] args)
   {
      AbstractClass concrete1 = new ConcreteClass1();
      AbstractClass concrete2 = new ConcreteClass2();
      ConcreteDecoratedAbstractClass1 decorated1Concrete1 = new ConcreteDecoratedAbstractClass1(concrete1);
      ConcreteDecoratedAbstractClass1 decorated1Concrete2 = new ConcreteDecoratedAbstractClass1(concrete2);
      ConcreteDecoratedAbstractClass2 decorated2Concrete1 = new ConcreteDecoratedAbstractClass2(concrete1);
      ConcreteDecoratedAbstractClass2 decorated2Concrete2 = new ConcreteDecoratedAbstractClass2(concrete2);
      ConcreteDecoratedAbstractClass2 decorated21Concrete1 = new ConcreteDecoratedAbstractClass2(decorated1Concrete1);
      /* Et cetra */

      System.Console.WriteLine("Implementaiton 1");
      concrete1.Method();

      System.Console.WriteLine("Implementation 2");
      concrete2.Method();

      System.Console.WriteLine("Implementation 1 decorated by decorator 1");
      decorated1Concrete1.Method();

      System.Console.WriteLine("Implementation 2 decorated by decorator 1");
      decorated1Concrete2.Method();

      System.Console.WriteLine("Implementation 1 decorated by decorator 2");
      decorated2Concrete1.Method();

      System.Console.WriteLine("Implementation 2 decorated by decorator 2");
      decorated2Concrete2.Method();

      System.Console.WriteLine("Implementation 1 decorated by decorator 1 and decorator 2");
      decorated21Concrete1.Method();
}
This program outputs
Implementaiton 1
   ConcreteClass1
Implementation 2
   ConcreteClass2
Implementation 1 decorated by decorator 1
   ConcreteClass1
   Decorator1
Implementation 2 decorated by decorator 1
   ConcreteClass2
   Decorator1
Implementation 1 decorated by decorator 2
   ConcreteClass1
   Decorator2
Implementation 2 decorated by decorator 2
   ConcreteClass2
   Decorator2
Implementation 1 decorated by decorator 1 and decorator 2
   ConcreteClass1
   Decorator1
   Decorator2
I hope that this was informative in demonstrating the power of patterns and how they can be combined for even greater utility. Please feel free to comment below.

Scrobbler support in DAAP

A popular feature request for DAAP has been Last.fm's Scrobbler support. Scrobbling is a mechanism that allows Last.fm to know what songs you listen to on your personal devices, such as iPods, computer, or your Android device. This allows Last.fm to personalize which songs to suggest more quickly than normal. Big thanks to my brother Michael for implementing this.

The feature is pretty straight forward. First, a Scrobbling application must be installed on your device. For this version, Scrobbling has been tested with scrobbledroid and A Simple Last.fm Scrobbler. Next, navigating to the preferences via Menu -> Preferences from the Servers screen presents an option to enable this feature. From now on, your music listening will be relayed to your Scrobbling application which in turn relays that to your Last.fm account! No interaction required.

You can download DAAP via the android market by
  1. The Android Market Application
  2. Scanning the tag

Don't forget about DAAP

I recently updated some of the Android applications my brother and I have on the market. I left out by far the most popular application that we have. I have now fixed that. The DAAP application last night received a small but very useful bug fix. I expect more features to come out for the application in due time.

The bug fixed was a user experience (UX) design bug. Take the following scenario for instance: Select a song to play. Upon selection, the notification appears and you are free to continue using your phone for other purposes. Suppose that then you decided to return to the home screen or another application via repeatedly pressing the back button on the phone. You can use your phone, but if you returned to the DAAP application, you would have to re-login. If you clicked the notification, there was no way to return to the song selection screen. Essentially there was no way to return to pick a new song without re-logging in, a time consuming process.

The fix was easy. I added a new menu option on the media player (the screen viewed after clicking the notification) that allows you to return to the playlists. To prevent overloading of the menu options, I moved the shuffle and repeat buttons onto the screen. They are viewable at all times now. A screenshot below is included for demonstration purposes.


You can download DAAP via the android market by
  1. The Android Market Application
  2. Scanning the tag

Updates to mOTP and Utlimate Search Widget

I have finally found some free time to fix things that have been bothering me in my Android applications. That means updates!

First, I have fixed a minor bug in the mOTP application affecting some users. The bug was a simple oversight when originally implementing profile editing. When editing TOTP profiles with a non-default time interval, the time interval would  be listed as default. The fix was simple: pre-populate the spinner similar to how the other fields operate.

The second update was much more demanding. The Ultimate Search Widget application had no support for custom search providers. For instance, if I wanted to search my blog using the widget, I could not. I was restricted to a predefined list of search providers. Also, if I constantly switched between providers, I would have to scroll through the huge list of providers to find the search provider I wanted.

I solved the first problem by adding support for custom search providers. Simply fill in the name of the provider, the URL portion that appears before the query, the URL portion that appears after the query, and you are set.


Now this newly created search provider will appear in the list of providers when clicking the icon on the left hand side of the widget!

To fix the second problem, I added a preference type screen where you may click which providers are to appear in the list. This allows you to remove unused providers and make the widget more useful when frequently switching between search providers.


You can find both of the newly updated applications in The Android Market:
 
 

Integrating Doxygen with Autotools

For my thesis source code, I desired to have Doxygen documentation automatically generated by make. However, after searching the Internet, I was unable to find a decent tutorial. Luckily after reading the great book that I cannot recommend enough, A Practitioner's Guide to GNU Autoconf, Automake, and Libtool by John Calcote, I learned a great solution. I intend to outline that solution based off his book.

The first step is to decide how the process will work. In my case, I wrote documentation for a library that I plan for other developers to use. I want the documentation to be able to be viewed using the man utility. The documentation should be generated when the user runs 'make' and should be installed when the user runs 'make install'. If doxygen is not installed, output a warning message during configuration and do not generate any documentation.

The first step is to determine if the user has Doxygen installed. We can do this by searching for the Doxygen program using the Autoconf macro AC_CHECK_PROGS. If Doxygen is not found, output a warning message. We can put all of this logic in an m4 script or in-line in the configure.ac file. For this example, I will just put this in configure.ac:
AC_CHECK_PROGS([DOXYGEN], [doxygen])
if test -z "$DOXYGEN";
   then AC_MSG_WARN([Doxygen not found - continuing without Doxygen support])
fi


Now in configure.ac, we can check to see if we have Doxygen and if so, add some files to later be processed.
AM_CONDITIONAL([HAVE_DOXYGEN],
[test -n "$DOXYGEN"])AM_COND_IF([HAVE_DOXYGEN], [AC_CONFIG_FILES([docs/Doxyfile])])


We see a mention to 'docs/Doxyfile' above. To any Autotools users, this should outline the next step, to write the 'Doxyfile.in' file. This is a file that will be transformed into 'Doxyfile', which will control how Doxygen generates the documentation. The reason we describe the configuration file in a way that configure modifies it is in case that we want certain properties of the documentation to be configurable. For example, we could add a configure option to optionally generate html documentation, --enable-html-doc for example.

In the subdirectory docs of the project, we can start by running:
doxygen -g Doxyfile.in
This generates a template configuration file for Doxygen that we can modify to get our final configuration file. We need to supply the project name, project version, and any other options determined by configure. Change the following properties as below:
PROJECT_NAME = @PACKAGE_NAME@
PROJECT_NUMBER = @PACKAGE_VERSION@
INPUT = @top_srcdir@
Be sure to change other options that you desire, such as HTML output, man output, etc.


Now that we have a configuration file ready to be parsed by configuration script, we need to tell Automake to generate makefiles that have rules to generate the actual documentation. In the docs subdirectory, we can create the 'Makefile.am' file that will be transformed by automake into 'Makefile'. Here is a what it looks like:
if HAVE_DOXYGEN
directory = $(top_srcdir)/docs/man/man3/

dist_man_MANS = $(directory)/man_page_1.3 $(directory)/man_page_2.3
$(directory)/man_page_1.3: doxyfile.stamp
$(directory)/man_page_2.3: doxyfile.stamp

doxyfile.stamp:
   $(DOXYGEN) Doxyfile
   echo Timestamp > doxyfile.stamp

CLEANFILES = doxyfile.stamp

all-local: doxyfile.stamp
clean-local:
   rm -rf $(top_srcdir)/docs/man
endif

Now let's look at this carefully. The first thing that you should notice is that all the rules are only generated if configure set HAVE_DOXYGEN. We can see in the m4 code above that this is set is Doxygen is found.

Next we set up a convenience variable directory to save typing later on. Then we set the man pages that we wish to install when 'make install' is called. We set up a "Product List Variable" dist_man_MANS. This is a normal product list variable with a dist modifier. This means that we want to install these files when we run 'make install'. The man_ portion is the prefix, meaning we want to install these files in the $(mandir) directory. This is set by configure. The MANS portion of this product list is one of the primaries telling Autoconf which types of files are in this list.

We need make rules to build these man pages during the make stage. To do this, we make a rule for each man page to be installed, each one depending on a file called doxyfile.stamp. The reason we use one file is because of the one to many relationship between the one doxygen command and the many files generated. We need to be able to determine when we need to generate documentation, but which file do we check for. It doesn't make sense to pick one documentation file at random and check for its existence, so we use this solution.

The doxyfile.stamp target will generate the documentation by using the $DOXYGEN file determined by configure and the 'Doxyfile' generated from 'Doxyfile.in'. This target must also generate the doxyfile.stamp file also so future documentation file dependency checks are satisfied.

Now we need to tell Automake we want these built not at 'make install' time, but at 'make' time. To do this, we use a hook to the normal all target. By making the target all-local, we are making a target that will get executed before the normal all target. Now we are set. Make will install the man pages with the 'make install' command as we use the product list man_MANS with the dist prefix. We just need to handle cleaning up files on make clean. To do this, we add the 'doxyfile.stamp' file to the CLEANFILES list. This list is automatically cleaned when 'make clean' is run. To remove the directory of man pages is slightly different though. We can't easily remove a directory using the CLEANFILES variable. We simply hook into clean as we did with all and manually remove the directory.

Now we are set and ready to go. Please comment on improvements or errors in my guide.