#define SPACE 32
#define LETTER_O 111
#define DSYSBUFSIZE 4096

#include <Dtype/Dtype.h>
#include <dsys/dsys.h>
#include <string.h>

Dtype *dt_match_photo (char *, char *, int);

Dtype *get_photo_caption (char *photo_string, char *server, int port) {
     short int multiple, ind, photo_len;
     char photo_id[10], photo_id_match[14];
     char *rdbuf, *wrbuf;
     Dtype *dtlist, retdt;
     DsysBuf dsb;

     /*  More than one photo?
      *  Strings are of format: "AP Photo..."  so the 9th char is either
      *  an 's' or a space */

     if((photo_len = strlen(photo_string)) < 10) {
	  return (Dtype *) NULL;
     }

     if(photo_string[8] == SPACE) {
	  /*  A single Photo, easy */

	  if(photo_string[9] == LETTER_O){
	       /* Oops no actual photo id given */
	       return (Dtype *) NULL;
	  }
	  else {
	       strncpy(photo_id, (photo_string+9), 
		       (ind = index(photo_string+9, SPACE)) ? ind:photo_len-9);
	  }

	  return((Dtype *) dt_match_photo(photo_id, server, port));
     }
     else {
	  /* Multiple photos, what a pain */

	  fprintf(stderr, "Please I can't deal with multiple photos yet\n");

     }

}


Dtype *dt_match_photo (char *photo_id, char *server, int port) {
     char photo_id_match[14];
     char *rdbuf, *wrbuf;
     Dtype *dtlist, retdt;
     DsysClient *dsc;
     DsysBuf dsb;

     sprintf(photo_id_match, ".*%s.*", *photo_id);
     dtlist = DtypeListCreate(DTYPE_STRING, "=", DTYPE_STRING, "slugword",
			      DTYPE_STRING, photo_id_match);
     
     /* Connect to the Dtype server at the specified hostname/port */
     if((dsc = DsysClientCreate(server, port)) == NULL) {
	  fprintf(stderr, "ERROR - Unable to connect to server\n");
	  exit(-1);
     }
     /* Set up the DsysBuf for passing Dtypes */
     rdbuf = (char *) malloc(DSYSBUFSIZE);
     wrbuf = (char *) malloc(DSYSBUFSIZE);
     DsysBufClientInit(&dsb, dsc, rdbuf, DSYSBUFSIZE, wrbuf, DSYSBUFSIZE);
     
     if(DtypeSend(&dsb, dtlist) < 0){
	  fprintf(stderr, "ERROR -- Failed to send lookup\n");
     }
     DtypeFree(dtlist);
     free(dtlist);
     
     if(DtypeRecv(&dsb, &retdt) < 0){
	  fprintf(stderr, "ERROR -- receiving dtype\n");
     }
     return &retdt;

}

main () {
     char input_string[50];
     Dtype *dt;

     scanf("%s", &input_string);
     dt = get_photo_caption(input_string, "fishwrap.mit.edu", 11111);
     DtypePrint(dt);
}
