/*
Sample ,yet useful c++ program written by www.softsmart.co.za on 9 January 2010
This software take a text file containing on link per line and converts it into an anchor text usuable in a website

Web: www.softsmart.co.za
email: admin@softsmart.co.za

Service: Web Hosting, Web development and software development
*/


#include <cstdio>
#include <string>
#include <sys/stat.h> 
#include <iostream>
#include <cstdlib>
#include <fstream>

using namespace std;

bool FileExists(string strFilename) 
{
    
    struct stat stFileInfo;
    int intStat;
    
    // Attempt to get the file attributes
    intStat = stat(strFilename.c_str(),&stFileInfo);
    
    if(intStat == 0) 
    {
        // We were able to get the file attributes
        // so the file obviously exists.
        return true;
    } 
    else 
    {
        // We were not able to get the file attributes.
        // This may mean that we don't have permission to
        // access the folder which contains this file. if(you
        // need to do that level of checking, lookup the
        // return values of stat which will give you
        // more details on why stat failed.
        return false;
    }
    
}

bool ValidateURL(string URL)
{
    int x;
    int DotCount = 0;
    
    for(x = 0; x < strlen(URL.c_str()); x ++)
    {
        if(URL.substr(x, 1) == ".")
        {
            DotCount++;
        }
        
        if(URL.substr(x, 1) == "#")
        {
            return false;
        }
        
        if(URL.substr(x, 1) == ")")
        {
            return false;
        }
        
        if(URL.substr(x, 1) == "(")
        {
            return false;
        }
        
        
    }
    
    if(DotCount > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
    
}

long ParseFile(string FileName, bool AddTitle, bool OpenInNewWindow, bool UseTitleAsLinkText)
{
    long ValidLink = 0;
    long InvalidLink = 0;
    long NextLine = 0;
    
    string AnchorErrorFileName;
    string AnchorFileName;

    system("CLS");
    printf("Parsing File\r\n\r\n");
    string Inputbuffer;
    char TempInputBuffer[1000] = {0};
    
    int x;
    int y;
    
    
    
    int DotPos = 0;
    int SlashPos = 0;
    
    for(x = strlen(FileName.c_str()) - 1; x >= 0; x--)
    {
        if(FileName.substr(x, 1) == ".")
        {
            DotPos = x;
        }
        
        if(FileName.substr(x, 1) == "\\")
        {
            SlashPos = x;
            break;
        }      
    }

    AnchorFileName = FileName.substr(0, SlashPos + 1) + FileName.substr(SlashPos + 1, DotPos - SlashPos - 1) + "_anchors" + FileName.substr(DotPos);
    AnchorErrorFileName = FileName.substr(0, SlashPos + 1) + FileName.substr(SlashPos + 1, DotPos - SlashPos - 1) + "_errors" + FileName.substr(DotPos);
    
    
    ofstream AnchorFile;
    AnchorFile.open (AnchorFileName.c_str());
    
    ofstream AnchorErrorFile;
    AnchorErrorFile.open (AnchorErrorFileName.c_str());
    
    ifstream URLFile (FileName.c_str());
    
    string TitleText;
    string OpenInNewWindowText;
    string LinkText;
    
    bool ErrorURL;
    bool ErrorsFound = false;
    

    while (! URLFile.eof() )
    {
 
        NextLine++;
        
        memset(TempInputBuffer, 0 , 1000);
        URLFile.getline (TempInputBuffer,1000);
  
        Inputbuffer = TempInputBuffer;
        
        
        
        if(Inputbuffer == "\r\n")
        {
            Inputbuffer = "";
        }
        
        if(Inputbuffer == "\n")
        {
            Inputbuffer = "";
        }
        
        
        if(Inputbuffer == "\r")
        {
            Inputbuffer = "";
        }
        
        if(Inputbuffer != "")
        {
            printf( "%u) %s\r\n", NextLine, Inputbuffer.c_str());
            
            ErrorURL = !ValidateURL(Inputbuffer);
            
            transform(Inputbuffer.begin(), Inputbuffer.end(),
            Inputbuffer.begin(), ::tolower);
                    
            if(Inputbuffer.substr(0,7) != "http://")
            {
                Inputbuffer = "http://" + Inputbuffer;
                //printf( "Converted to: !%s!\r\n", Inputbuffer.c_str());
            }
            
            LinkText = Inputbuffer;
            
            if(AddTitle == true)
            {
                TitleText = "";
                
                if(Inputbuffer.substr(0, 11) == "http://www.")
                {
                    y = 11;
                }
                else
                {
                    y = 7;
                }
                
                for(x = y; x < strlen(Inputbuffer.c_str()); x++)
                {
                    if(Inputbuffer[x] == '.')
                    {
                        break;
                    }
                }
                
                    
                if(UseTitleAsLinkText == true)
                {
                    LinkText = Inputbuffer.substr(y, x - y);
                }
            
                TitleText = "title=\"" + Inputbuffer.substr(y, x - y) + "\"";
            }
            
            if(OpenInNewWindow == true)
            {
                OpenInNewWindowText = " target=\"_new\"";
            }
            

            
            memset(TempInputBuffer, 0 , 1000);
            sprintf(TempInputBuffer, "<a href=\"%s\" %s %s>%s</a>", Inputbuffer.c_str(), TitleText.c_str(), OpenInNewWindowText.c_str(), LinkText.c_str());
            Inputbuffer = TempInputBuffer;
            
            if(ErrorURL == true)
            {
                ErrorsFound = true;
                InvalidLink++;
                AnchorErrorFile << Inputbuffer.c_str() << endl;
            }
            else
            {
                AnchorFile << Inputbuffer.c_str() << endl;
                ValidLink++;
    
            }
            
            ErrorURL = false;
        
            
        }
        
    }
        
    //printf( "Done with main reading loop\r\n");
    URLFile.close();
    

    AnchorFile.close();
    
    AnchorErrorFile.close();




    printf("\r\n\r\nDone creating anchor file\r\n\r\n");
    printf("Anchor file location:\r\n%s\r\n\r\n", AnchorFileName.c_str());
    
    if(ErrorsFound == true)
    {
        printf("Anchor file errors location:\r\n%s\r\n\r\n", AnchorErrorFileName.c_str());
    }
    
    return NextLine;
}

int main(int argi, char ** argc)
{
    
    string FileName;
    
    bool UseTitleTag;
    bool UseTitleTagAsLinkText;
    bool OpenInNewWindow;
    
    long FilesParsed = 0;
    
    system("CLS");
    
    printf("*****************************************************************\r\n");
    printf("Custom software written by SoftSmart.co.za (www.softsmart.co.za)\r\n");
    printf("\r\n");
    printf("Date: 09 January, 2010 (the year we host the soccer world cup!!!)\r\n");
    printf("\r\n");
    printf("HINT: Easiest use, drag the text file with urls onto this program to start\r\n");
    printf("*****************************************************************\r\n");
    
    if(argi == 2)
    {
        FileName = argc[1];
    }
    else if(argi > 2)
    {
        std::printf("\r\n\r\nPlease enter your file name, but enclose it in quotes, eg, \"C:\\Program Files\\SomeFolder\\Urls.txt\"\r\n\r\n");
        cin >> FileName;
    }
    else
    {
        std::printf("\r\n\r\nPlease type the name of the file with the urls, then press enter:\r\n\r\n");
        cin >> FileName;
    }
    
    
    char RetryOrQuit[99];
    
    do
    {
        if(FileName == "")
        {
            system("CLS"); 
            std::printf("Please type the name of the file with the urls, then press enter:\r\n\r\n");
            cin >> FileName;
        }
        
        if(FileExists(FileName) == true)
        {
            
            // get the options
                    
            cout << "\r\n\r\nPress y if you want to use a title tag, or n if not\r\n";
            cout << "(eg, www.softsmart.co.za becomes (<a href=\"http://www.softsmart.co.za\" title=\"softsmart\">...\r\n";
            
            cin >> RetryOrQuit;
            
            if(RetryOrQuit[0] == 'y')
            {
                UseTitleTag = true;
            }
            else
            {
                UseTitleTag = false;
            }
            
             
            UseTitleTagAsLinkText = false;
            
            if(UseTitleTag == true)
            {
                cout << "\r\n\r\nPress y if you want to use a title tag as the link text, or n if not\r\n";
                cout << "(eg, www.softsmart.co.za becomes <a href=\"http://www.softsmart.co.za\" title=\"softsmart\">softsmart</a>\r\n";
                
                cin >> RetryOrQuit;
                
                if(RetryOrQuit[0] == 'y')
                {
                    UseTitleTagAsLinkText = true;
                }
  
            }
            
            
            cout << "\r\n\r\nPress y if you want to have the link open in a new window, or n for not (adds target=\"_new\"\r\n";
            
            cin >> RetryOrQuit;
            
            if(RetryOrQuit[0] == 'y')
            {
                OpenInNewWindow = true;
            }
            else
            {
                OpenInNewWindow = false;
            }
            
            
            FilesParsed = ParseFile(FileName, UseTitleTag, OpenInNewWindow, UseTitleTagAsLinkText);
            return 0;
        }
        else
        {
            printf("That file does not exist (did you forget to put quotes \"\" around your file name?)...\r\n\r\nPress r to retry or any other key to quit\r\n\r\n");
            //printf(FileName.c_str());
            FileName = "";
            cin >> RetryOrQuit;
        }
        
    }while(RetryOrQuit[0] == 'r');
    
    system("CLS");
    printf("%u files parsed for you by www.softsmart.co.za ;)\r\n\r\n", FilesParsed);
    printf("Press any key to exit\r\n\r\n", FilesParsed);
      
    cin >> RetryOrQuit;
    
    return 1;
}

