#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "user.h"

user_store* new_user_store() {
  user_store *us = calloc(1, sizeof(user_store));
  us->size=0;
  us->u=NULL;
  return us;
}


user_store* add_user(user_store *store, char *fname, char *gname) {
  user *u;
  user *tmpuser;
  tmpuser = realloc(store->u,
                     (store->size+1)*sizeof(user));
  
  if (tmpuser == NULL ){
    return store;
  }
  store->u = tmpuser;
  
  u = &store->u[store->size];


  /*
   * may go bad (return NULL)
   * Add code to check 
   *
   * To force a malloc error, enable the malloc macro in user.h
   */
  u->family_name = (char*) malloc(strlen(fname)*sizeof(char)+1);
  u->given_name  = (char*) malloc(strlen(gname)*sizeof(char)+1);

  strcpy(u->family_name, fname);
  strcpy(u->given_name, gname);
  store->size++;
  return store;
}

void free_user_store(user_store *us) {
  int i ;
  for (i=0; i<us->size; i++) {
    free(us->u[i].family_name);
    free(us->u[i].given_name);
  }
  free(us->u);
  free(us);
}

void print_user_store(user_store *us) {
  int i ;
  printf("User (%d)\n", us->size);
  printf("--------------------\n" );
  for (i=0; i<us->size; i++) {
    printf ("%.4d %s, %s\n",
            i,
            us->u[i].family_name, 
            us->u[i].given_name);
  }
}
