#include <stdio.h>
#include <stdlib.h>
#include "global.h"
#include "survey.h"

#include "manhat-lib/shared_survey_util.h"
#include "manhat-lib/shared_survey_string.h"
#include "manhat-lib/shared_survey_log.h"
#include "manhat-lib/shared_survey_modify.h"
#include "manhat-lib/shared_survey_info_list_parser.h"
#include "manhat-lib/shared_survey_path_util.h"
#include "manhat-lib/shared_survey_read_param.h"
#include "manhat-lib/shared_cs_util.h"

SURVEY_DATA *
read_parameters(int  *is_admin, char *key, char *count)
{
   int id =0;
   SURVEY_DATA *data =0;

   read_com_parameters(is_admin, key, count, &id); 
   data = read_title_parameters(id);  /* shared_survey_read_param.c */
   return data;
}

void
update_title_info(const char *count, const char *title, SESSION *user)
{
   char filename[MAX_PATH +1];
   char base[MAX_PATH +1];
   SURVEY_INFO_LIST *list;
   FILE *fp;
   char *str =0;

   get_survey_base(user, base);   /*shared_survey_path_util.c */
   snprintf(filename, MAX_PATH+1, "%s/%s", base, SURVEY_INFO_FNAME);

   list = survey_info_parser(filename);
   write_to_log(filename);
   if(list)
    {
       fp = fopen(filename, "w");
       if(!fp)
          cs_critical_error(ERR_FOPEN_WRITE_FAILED, "");
       fprintf(fp, "<?xml version=\"1.0\" encoding=\"iso-8859-1\" ?>\n");
       fprintf(fp, "<%s>\n", SURVEY_LIST_TAG);

       list->current = list->head;
       while(list->current)
       {
	  if(!strcmp(list->current->id, count))
	  {
	    if(list->current->title)
	    {
	      free(list->current->title);
	      list->current->title = malloc_str(title);
	    }
	  }
	  else
	  {
	     if(list->current->title)
	     {
	       str = replace_sp(list->current->title);
	       free(list->current->title);
	       list->current->title = malloc_str(str);
	       free(str);
	     }
	  }
	     
	  write_one_survey_info(list->current, fp);
	  list->current = list->current->next;
       }
       fprintf(fp, "%s", SURVEY_INFO_END_TAG);
       fclose(fp);
       free_survey_info_list(list);
    }
}


int 
main()
{
   int  is_admin;
   char key[MAX_KEY +1];
   char count[MAX_PATH +1];
   SURVEY_DATA *data;
   SESSION user;
   
   cs_cgi_init();    /* shared_cs_util.c */
   data = read_parameters(&is_admin, key, count);
   verify_key_path(&user, key, is_admin);  /* shared_survey_path_util.c */
   modify_action( &user, count, data); /*shared_survey_modify.c */
   update_title_info( count, data->left_cols, &user);
   printf("Location: %s?admin=%d&id=%s&count=%s&target=%d#%d\n\n", 
                     "survey_new", is_admin, key, count, data->id, data->id);
   free_survey_data(data);
   cs_cgi_destroy();   /* sahred_cs_util.c */

   return 0;
}
