/* library to enable getting and setting subjective responses
   Copyright (C) 1992-2000 Michigan State University

   The CAPA system is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   The CAPA system is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public
   License along with the CAPA system; see the file COPYING.  If not,
   write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.

   As a special exception, you have permission to link this program
   with the TtH/TtM library and distribute executables, as long as you
   follow the requirements of the GNU GPL in regard to all of the
   software in the executable aside from TtH/TtM.
*/


#include "capaCommon.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <ctype.h>

char* strtoupper(char* source)
{
  char* result;
  int i,len=strlen(source);
  result=capa_malloc(len+2,1);
  for(i=0;i<len;i++) result[i]=toupper(source[i]);
  result[i]='\0';
  return result;
}

int capa_set_subjective (int set,int problem,char *student_num,char* response)
{
  char buf[FILE_NAME_LENGTH],*upperstunum;
  FILE *responsefile;

  sprintf(buf,"records/set%d",set);
  if( capa_access(buf, F_OK) == -1 ) { 
    if ( mkdir(buf, S_IREAD | S_IWRITE | S_IEXEC ) == -1 ) { return -1; }
  }

  sprintf(buf,"records/set%d/problem%d",set,problem);
  if( capa_access(buf, F_OK) == -1 ) { 
    if ( mkdir(buf, S_IREAD | S_IWRITE | S_IEXEC ) == -1 ) { return -2; }
  }

  upperstunum=strtoupper(student_num);
  sprintf(buf,"records/set%d/problem%d/%s",set,problem,upperstunum);
  if ((responsefile=fopen(buf,"w"))==NULL)  { return -3; }
  
  fwrite(response,strlen(response),1,responsefile);
  fclose(responsefile);
  return 0;
}

char* capa_get_subjective (int set,int problem,char *student_num)
{
  char buf[FILE_NAME_LENGTH],*upperstunum,*response;
  FILE *responsefile;
  long length;

  upperstunum=strtoupper(student_num);
  sprintf(buf,"records/set%d/problem%d/%s",set,problem,upperstunum);
  if ((responsefile=fopen(buf,"r"))==NULL)  { return NULL; }
  fseek(responsefile,0,SEEK_END);
  length=ftell(responsefile);
  rewind(responsefile);
  response=capa_malloc(length+1,1);
  fread(response,length,1,responsefile);
  response[length]='\0';
  return response;
}
