//
// testlist.cpp
//
// Test of doubly linked list implementation in list.hpp
//
// Computer Science S-111, Harvard University
//

#include <iostream.h>
#include <assert.h>
#include "list.hpp"    

//
// This class will be used for the data items in the list.
// It represents strings that have no more than 80 characters.
//
class str {
public:
    char* data;

    str();
    str(int length);
    str(const str& a);

    const str& operator =(const str& a);

    friend bool operator ==(const str& a, const str& b);
    friend bool operator <(const str& a, const str& b);
    friend ostream& operator <<(ostream& s, const str& a);
    friend istream& operator >>(istream& s, const str& a);
};

str::str()
{
    data = new char[81];
}
    
str::str(int length)
{
    assert(length > 0 && length <= 80);
    data = new char[length + 1];
}
    
str::str(const str& a)
{
    data = new char[81];
    strcpy(data, a.data);
}
    
const str&
str::operator =(const str& a)
{
    if (&a != this) {
	delete [] data;
	data = new char[81];
	strcpy(data, a.data);
    }
    return *this;
}
    
bool
operator ==(const str& a, const str& b)
{
    return (!strcmp(a.data, b.data));
}
    
bool
operator <(const str& a, const str& b)
{
    return (strcmp(a.data, b.data) < 0);
}
    
ostream&
operator <<(ostream& s, const str& a)
{
    s << a.data;
    return s;
}
    
istream&
operator >>(istream& s, const str& a)
{
    s >> a.data;
    return s;
}


//
// print_item - used by print_list to print each string in the list.
//
void
print_item(int pos, str item)
{
    cout <<  pos << " " << item.data << endl;
}


int
main()
{
    list<str> lst;
    node<str> *follow, *n;
    str item;
    char buf;
    int count, pos;

    while(true) {
	lst.print_list();

	cout << "[i pos item|o item|a item|d pos|f string|q|r|s] :";
	cin.get(buf);

	if (buf == 'q')
	    exit(1);
	else if (buf == 'i') {
	    cin >> pos;
	    cin >> item;
	    follow = lst.retrieve(pos);
	    lst.insert(follow, item);
	}
	else if (buf == 'o') {
	    cin >> item;
	    follow = lst.search_ordered(item, count);
	    lst.insert(follow, item);
	}
	else if (buf == 'a') {
	    cin >> item;
	    lst.append(item);
	}
	else if (buf == 'd') {
	    cin >> pos;
	    n = lst.retrieve(pos);
	    lst.remove(n);
	    delete n;
	}
	else if (buf == 'f') {
	    cin >> item;
	    if (lst.search(item, count) != NULL) {
		cout << "Found " << "< " << item << " > in list after ";
		cout << count << " comparisons\n";
	    }
	    else 
		cout << "Not in list\n";
	}
	else if (buf == 'r') {
	    lst.reinit();
	}
	else if (buf == 's') {
	    lst.sort();
	}
	
	cin.ignore(1);
    }
	
}

