#include <stdlib.h>
#include <string.h>
#include "person.h"

void free_persons(person *p, int size)
{
    int i ;
    if (p==NULL)  {
        BAD_INPUT_DATA;
    }

    for (i=0; i<size; i++) {
        if (p[i].first_name!=NULL) {
            free(p[i].first_name);
            p[i].first_name=NULL;
        }
        if (p[i].family_name!=NULL) {
            free(p[i].family_name);
            p[i].family_name=NULL;
        }
    }
    free(p);
}

int
add_one_person(person **p_in, int new_size, char *first_name, char *family_name) {
    person *p = *p_in;
    person *tmp;

    if (first_name==NULL || family_name==NULL) {
        return BAD_INPUT_DATA;
    }

    tmp = realloc(p, new_size*sizeof(person));
    if (tmp==NULL) {
        return ALLOC_FAILURE; // indicate errror to user
    }
    p = tmp;

    // Ok, we have a new person struct.
    // make room for our strings
    p[new_size-1].first_name=calloc(strlen(first_name)+1, sizeof(char));
    p[new_size-1].family_name=calloc(strlen(family_name)+1, sizeof(char));

    if (p[new_size-1].first_name==NULL || p[new_size-1].family_name==NULL) {
        if (p[new_size-1].first_name!=NULL) {
            free (p[new_size-1].first_name);
        }
        if (p[new_size-1].family_name!=NULL) {
            free (p[new_size-1].family_name);
        }
        tmp = realloc(p, (new_size-1)*sizeof(person));
        if (tmp==NULL) {
            return MEM_LOST;
        }
        p = tmp;
        return NO_DATA_ADDED ;
    }

    // Ok, we now have mem for our strings
    strcpy(p[new_size-1].first_name, first_name);
    strcpy(p[new_size-1].family_name, family_name);

    *p_in = p;
    return 0;
}
