#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#include <string.h>
#include <assert.h>
#include <dirent.h>
#include <errno.h>
void str_replace(char *target, const char *needle, const char *replacement)
{
    char buffer[1024] = { 0 };
    char *insert_point = &buffer[0];
    const char *tmp = target;
    size_t needle_len = strlen(needle);
    size_t repl_len = strlen(replacement);

    while (1) {
        const char *p = strstr(tmp, needle);

        // walked past last occurrence of needle; copy remaining part
        if (p == NULL) {
            strcpy(insert_point, tmp);
            break;
        }

        // copy part before needle
        memcpy(insert_point, tmp, p - tmp);
        insert_point += p - tmp;

        // copy replacement string
        memcpy(insert_point, replacement, repl_len);
        insert_point += repl_len;

        // adjust pointers, move on
        tmp = p + needle_len;
    }

    // write altered string back to target
    strcpy(target, buffer);
}

void _ls(const char *dir,int op_a,int op_l)
{
        //Here we will list the directory
        struct dirent *d;
        DIR *dh = opendir(dir);
        if (!dh)
        {
                if (errno = ENOENT)
                {
                        //If the directory is not found
                        perror("Directory doesn't exist");
                }
                else
                {
                        //If the directory is not readable then throw error and exit
                        perror("Unable to read directory");
                }
                exit(EXIT_FAILURE);
        }
        //While the next entry is not readable we will print directory files
        while ((d = readdir(dh)) != NULL)
        {
                //If hidden files are found we continue
                //if (!op_a && d->d_name[0] == '.')
                 //       continue;
                //printf("%s  ", d->d_name);
                //if(op_l) printf("\n");
                if( d->d_name[0] != '.')
		{
		
		printf("%s,",dir);
		if(d->d_type == DT_REG)
		{        
			//printf("directory\n");
			printf("%s,0,16,9944,129\n",d->d_name);
		}
                else
		{
                        
			//printf("file\n");
			printf("%s,70408,32,17071,28040\n",d->d_name);
		}
		}
        }
        if(!op_l)
        printf("\n");
}


char** str_split(char* a_str, const char a_delim)
{
    char** result    = 0;
    size_t count     = 0;
    char* tmp        = a_str;
    char* last_comma = 0;
    char delim[2];
    delim[0] = a_delim;
    delim[1] = 0;

    /* Count how many elements will be extracted. */
    while (*tmp)
    {
        if (a_delim == *tmp)
        {
            count++;
            last_comma = tmp;
        }
        tmp++;
    }  /* Add space for trailing token. */
    count += last_comma < (a_str + strlen(a_str) - 1);

    /* Add space for terminating null string so caller
       knows where the list of returned strings ends. */
    count++;

    result = malloc(sizeof(char*) * count);

    if (result)
    {
        size_t idx  = 0;
        char* token = strtok(a_str, delim);

        while (token)
        {
            assert(idx < count);
            *(result + idx++) = strdup(token);
            token = strtok(0, delim);
        }
        assert(idx == count - 1);
        *(result + idx) = 0;
    }

    return result;
}


int main(void)
{

   char *env_value,*val;
   char *save_env;
   char *directory;
   int arg;
   char **args;
   time_t current_time;    

    printf("Content-Type: text/plain;charset=us-ascii\n\n"); 
   FILE *fptr = fopen("sample.txt", "a"); 
    if (fptr == NULL) 
    { 
        printf("Could not open file"); 
        return 0; 
    } 


    //printf("Content-Type: text/plain;charset=us-ascii\n\n");
  //printf("WLANSD_FILELIST\n");
  //printf("/KAL2,TAR001,0,16,9944,129\n");
  //printf("/KAL2/TAR001,TAR0001.clt,70408,32,17071,28040\n");
  //printf("/KAL2/TAR001,TAR0001.trg,70408,32,17071,28040\n");
  //printf("/KAL2,TAR002,0,16,9944,129\n");
  //printf("/KAL2/TAR002,TAR0002.clt,70408,32,17071,28040\n");
  //printf("/KAL2/TAR002,TAR0002.trg,70408,32,17071,28040\n");

    
   save_env = getenv("QUERY_STRING");   /* get environment variable */
   env_value = malloc(strlen(save_env) + 1);
   if (env_value == NULL)
   {
      printf("Major failure; please notify the webmaster\n");
      exit (2);
   }
   strcpy(env_value, save_env);    /* save environment variable */
   args=str_split(env_value,'&');
    if (args)
    {
        int i;
        for (i = 0; *(args + i); i++)
        {
            
		if(i==0) // getting opcode
		{
		 val=strtok(*(args + i),"=");	
		 val=strtok(NULL,"=");
		 sscanf(val,"%d",&arg);
		 fprintf(fptr,"roooof %d\n",arg );
		}

		if(i==1) //time to get folder name
		{
		 directory=strtok(*(args + i),"=");	
		 directory=strtok(NULL,"=");
		 str_replace(directory, "%5C", "/");
		 fprintf(fptr,"roooof %s\n",directory+1 );
		  _ls(directory+1,0,0);

		}
            free(*(args + i));
        }
        free(args);
    }

//   printf("The query is %s\n", env_value);         
   //fprintf(fptr,"%s\n", env_value);
   fclose(fptr);
  return 0;
}
