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

#define LEN 90

struct basket {
  char name[LEN];
  struct item *item;
};

struct item {
  struct item *next;
  char name[LEN];
};

void init_basket( struct basket *b ) {
  strncpy( b->name, "Basket", LEN );
  b->item = NULL;
}

void init_basket_item( struct item *i ) {
  strncpy( i->name, "", LEN );
  i->next = NULL;
}

struct item *last_item( struct basket *b ) {
  struct item *ptr = NULL;
  struct item *p = NULL;
  ptr = b->item;
  if( ptr == NULL ) {
    printf( "Returning null\n" );
    return( ptr );
  }
  
  while( ptr != NULL ) {
    p = ptr;
    ptr = ptr->next;
    
  }
  return( p );
}

struct item *add_item( struct basket *b ) {
  struct item *ptr,*p;
  ptr = last_item( b );
  p = malloc( sizeof( struct item ) );
  init_basket_item( p );
  strncpy( p->name, "Created", LEN );

  /* is this the first item */
  if( ptr == NULL ) {
    printf( "Setting b->item\n" );
    b->item = p;
  }
  else {
    ptr->next = p;
  }
  return( p );
}

int main( int argc, char *argv[] ) {
  struct basket *b = malloc( sizeof( struct basket ) );
  struct item *ii;// = malloc( sizeof( struct item ) );
  struct item *iii;// = malloc( sizeof( struct item ) );
  init_basket( b );
  
  ii = add_item( b );
  iii = add_item( b );
  strncpy( ii->name, "C", LEN );
  
  printf( "Basket name: %s\n", b->name );
  printf( "Item name: %s\n", b->item->name );
  printf( "Item name: %s\n", b->item->next->name );
  
  free( b );
  return(0);
}

