//
//  PointerList.h
//  Wbl3001
//
//  Created by david van brink on 3/17/13.
//
//

#ifndef __Wbl3001__PointerList__
#define __Wbl3001__PointerList__

#include <stdlib.h>


class Util
{
public:
    
    static void clear(void *p, size_t size)
    {
    if(p)
        for(size_t i = 0; i < size; i++)
            ((char *)p)[i] = 0;
    }

    static void *mallocClear(size_t size)
    {
        void *result = malloc(size);
        clear(result,size);
        return result;
    }
};

template <int S,class T>
class List
{
public:
    unsigned char empty[sizeof(T)];
    int maxSize;
    int size;
    T list[S];

    List()
    {
        Util::clear(&this->empty,sizeof(T));
        this->maxSize = S;
        this->size = 0;
    }

    ~List()
    {
    }
    
    T getAt(int ix)
    {
        if(ix < 0 || ix > this->size)
            return *(T *)(&this->empty);
        return this->list[ix];
    }
    
    int find(T element)
    {
        for(int i = 0; i < this->size; i++)
        {
            if(element == this->list[i])
                return i;
        }
        return -1;
    }

    void add(T element)
    {
        int ix = find(element);
        if(ix >= 0)
            return;
        if(this->size >= this->maxSize)
        {
            throw "TOO FULL";
        }
        this->list[this->size++] = element;
    }
    
    void clear()
    {
        this->size = 0;
    }
    
    void removeAt(int ix)
    {
        if(ix < 0 || ix >= this->size)
            return;

        this->size--;
        while(ix < this->size)
        {
            this->list[ix] = this->list[ix + 1];
            ix++;
        }
    }
    
    void remove(T element)
    {
        int ix;
        for(ix = 0; ix < this->size; ix++)
        {
            if(this->list[ix] == element)
            {
                this->removeAt(ix);
                ix--;
            }
        }
    }
    
    int getSize()
    {
        return this->size;
    }
};

#endif /* defined(__Wbl3001__PointerList__) */
