/*
    This file is part of BOP.
    Copyright (C) 2004  Patrick Davalan

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    The GNU General Public License text is also available at
    http://www.gnu.org/
    or on the Copyright holder web site :
    http://patrick.davalan.free.fr/gnu-gpl.html
*/
#define DEBUG 0
// change the include to #include <bop.2/bop.h>
# include "bop.h"

//    
//    Filter : read stdin and write stdout
//    Reverse lines of stdin using a extended stack
//    don't replicate identical lines, print only the
//    first which appears in input
//    
//    May be used to understand the Bop API, and test it
//    especially extended stack functions
//
//    Lines which have a length > BOP_BUFSIZE are silently truncated.
//    

# define BOP_BUFSIZE 4096
int 
main()
{
    BopsHandle * stack ;
    BopsEntry * entry ;
    char buffer[ BOP_BUFSIZE ] ;

    bopmTrace( ) ;

    // create a stack
    stack = bopsNew( NULL, "extended stack", 4, 3 ) ; // the sizes are just for test
    // make it an extended stack
    bopsXSet( stack ) ;

    // for each line of the input file, push it on the stack
    for ( ; fgets( buffer, BOP_BUFSIZE, stdin ) != NULL ; )
    { 
        size_t len = 0 ;
        char * line ;
        
        len = strlen(buffer) ;
        *( buffer + len - 1 ) = 0 ; // erase \n
        // alloc and fill the line
        line =bopmMalloc( len ) ;
        memcpy( line, buffer, len ) ;
        
        // bopdTrace("line :%s\n", line ) ;
        // push the line onto the stack
        entry = bopsXPush( stack, line, len ) ;
        if ( entry != NULL )
        {
            bopmFree( line ) ;
        }
        
    }
    bopdTrace("End of file\n" ) ;
    
    // pop the stack and write popped entries to stdout
    for ( ; ( entry = bopsPop( stack ) ) != NULL ; )
    {
        void * data ;
        data = bopsGetData( entry ) ; 
        puts( data ) ;
        bopmFree( data ) ;
    }
        

    bopsDelete( NULL, stack ) ;

    bopmMem( ) ;

    return( EXIT_SUCCESS ) ;
}