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

#include "global.h"
#include "custom.h"
#include "survey.h"

#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_survey_xml_parser.h"
#include "manhat-lib/shared_lock.h"
#include "manhat-lib/shared_survey_string.h"
#include "manhat-lib/shared_file_util.h"
#include "manhat-lib/shared_survey_submit.h"
#include "manhat-lib/shared_cs_util.h"


void
read_parameters(char *count)
{
   cs_get_required_parameter ("id", count, MAX_PATH);
}




void
write_record( const char *count)
{

    char fname[MAX_PATH +1];
    FILE *fp;
    time_t now;
    char timestring[MAX_TIMESTRING + 1];
    SURVEY_LIST *list_survey;
    NAME_VALUE_LIST *list;

    now = time (NULL);
    strftime (timestring, MAX_TIMESTRING, DOW_DATE_TIME_FORMAT,
		                   localtime (&now));

    snprintf(fname, MAX_PATH+1, "../%s/%s/%s/%s", 
		    SURVEY_DIR, SURVEY_WWW_DIR, count, SURVEY_XML_FNAME);

    list_survey = survey_data_parser(fname);
    list = build_name_value_list(list_survey); /* shared_survey_submit.c */

    snprintf(fname, MAX_PATH+1, "../%s/%s/%s/%s", 
		    SURVEY_DIR, SURVEY_WWW_DIR, count, SURVEY_RESULT_FNAME);

    fp = fopen(fname, "r+");
    if(!fp)
	 cs_critical_error( ERR_FOPEN_APPEND_FAILED, "");

    get_exclusive_lock(fileno(fp), 1);
    write_result_file(fp, timestring,"",  list);  /* shared_survey_submit.c */
    release_lock(fileno(fp));

    fclose(fp);
    free_survey_data_list(list_survey);
    free_name_value_list(list);  /* shared_survey_submit.c */
}


int
main()
{
    char count[MAX_PATH +1];

    cs_cgi_init();
    read_parameters(count);
    write_record( count);
    cs_set_int_value("close_win", -1);
    cs_set_value("success_code", SURVEY_SUBMIT_WWW_CODE);
    cs_cgi_display("survey_success", 1);
    cs_cgi_destroy();
    return 0;
}

	  
	   
