#include <stdio.h>
#include <stdlib.h>
#include "global.h"
#include "survey.h"
#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_survey_update_info.h"
#include "manhat-lib/shared_super_key.h"
#include "manhat-lib/shared_survey_path_util.h"
#include "manhat-lib/shared_cs_util.h"




void
read_parameters(int *is_admin, char *key, int *finish, char *count, int *mode, char *course,
		char *username)
{
   char tmp[10];

   cs_get_required_parameter("id", key, MAX_KEY);
   cs_get_required_parameter("count", count, MAX_PATH);
   cs_get_optional_parameter("admin", tmp, 9);
   *is_admin = !(*tmp)? 0: atoi(tmp)? 1 : 0;

   cs_get_required_parameter ("finish", tmp, 9);
   *finish = atoi(tmp);


 /* mode is a 'mystery' number somewhat cleared up in 
 ** survey.h  -  look for 
 **     #define MODE_TAKE_MYMANHATTAN   1
 **     #define MODE_TAKE_WEB_DELIVERED 2
 **    and so on.
 ** 
 ** The 'mode' value is simply passed on to a URL via
 ** a Location:http://   within this program
 */

   cs_get_required_parameter ("mode", tmp, 9);
   *mode = atoi(tmp);

   cs_get_optional_parameter ("crs", course, MAX_PATH);
   cs_get_optional_parameter ("username", username, MAX_USERNAME);
}



void
do_action(int is_admin, const char *key, int finish, 
		const char *count, int mode, SESSION *user, const char *course, const char *username)
{
     if(finish == 1)
      printf("Location: %s?admin=%d&id=%s&count=%s&mode=%d\n\n", 
		      "survey_page", is_admin, key, count, mode);
     else if(finish == 2)
      printf("Location: %s?admin=%d&id=%s&count=%s&pre_id=0\n\n",
		      "survey_new", is_admin, key, count);
     else if(finish == 3)
      printf("Location: %s?admin=%d&id=%s&count=%s\n\n", 
		      "survey_deliver_form", is_admin, key, count);
     else if(finish == 5 )
     {
	update_survey_info_state(user,  count, SURVEY_STATE_FIN, username,"");
        printf("Location: %s?admin=%d&id=%s&crs=%s&username=%s\n\n", 
			"survey_read_info", is_admin, key, course, username);

     }
     else if(finish ==4)
        printf("Location: %s?admin=%d&id=%s&crs=%s&username=%s\n\n", 
			"survey_read_info", is_admin, key, course, username);
     else
     {
	update_survey_info_state(user,  count, SURVEY_STATE_PUB, "", "");
        printf("Location: %s?admin=%d&id=%s\n\n", 
			"survey_read_info", is_admin, key);
     }
}





int 
main()
{
   int is_admin;
   char key[MAX_KEY +1];
   char count[MAX_PATH +1];
   char course[MAX_PATH +1];
   char username[MAX_USERNAME +1];
   int mode, finish;
   SESSION user;

   cs_cgi_init();
   
   read_parameters(&is_admin, key, &finish, count, &mode, course, username);
   
   verify_key_path(&user, key, is_admin);
   
   do_action(is_admin, key,  finish,  count,  mode, &user, course, username);
   
   cs_cgi_destroy();
   
   return 0;
}
