
#include <iostream.h>
#include <stdlib.h>
#include <ctype.h>

//  C to HTML converter.
//  Adds line numbers e.g.  001:
//  Boldfaces the code, leaves comments in regular type.
//  converts < to &lt;
//           > to &gt;
//           & to &amp;

//  Bug:    Doesn't handle /* or // in quotes correctly.


void put_htmlchar(char);
void handle_comment(void);
void print_ln(void);

main()
{
    int bold;
    int current;

    cout << "<PRE>\n";
    while ((current = cin.get()) != EOF)
    {   
        bold = 0;           // begin lines wo/boldface
        print_ln();         // print line number
        cin.putback(current);       // otherwise we would miss a character
        while ((current = cin.get()) != '\n')
        {
            if (current == '/')
            {   
                if ((current = cin.get()) == '/')
                {   if (bold)
                    {   cout << "</B>";     // end boldface for comments
                        bold = 0;   }
                    cout << '/' << '/';
                    while ((current = cin.get()) != '\n')
                        put_htmlchar(current);
                    break;
                }
                else if (current == '*')    //  '/*' style comment.
                {   if (bold)
                    {   cout << "</B>"; 
                        bold = 0;   }
                    cout << '/' << '*';
                    handle_comment();
                    continue;
                }
                else 
                {   cout << '/';
                    if (current == '\n')    break;
                }
            }
            if (!bold && !isspace(current))
            {   cout << "<B>";      // begin boldface
                bold = 1;       }
            put_htmlchar(current);
        }
        if (bold)
            cout << "</B>";
        cout << '\n';
    }
    cout << "</PRE>\n";
}

void handle_comment(void)       // deal with /* style comments
{   
    char current = cin.get();
    for (;;)
    {
        put_htmlchar(current);
        if (current == '\n')
            print_ln();
        else if (current == '*')
            if ((current = cin.get()) == '/')
                break;
            else continue;
        current = cin.get();
    }
    cout << '/';
}

void put_htmlchar(char current)
{
    if (current == '<')
        cout << "&lt;";
    else if (current == '>')
        cout << "&gt;";
    else if (current == '&')
        cout << "&amp;";
    else cout << char(current);
}

void print_ln(void)         // prints line number
{
    static int linenumber;

        linenumber ++;      
        if (linenumber < 10)
            cout << "00" << linenumber << ": ";
        else if (linenumber < 100)
            cout << '0' << linenumber << ": ";
        else
            cout << linenumber << ": ";
}
