/**************************************************************************************
 Copyright (c) 2002 The UbixOS Project
 All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions, the following disclaimer and the list of authors.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions, the following disclaimer and the list of authors
in the documentation and/or other materials provided with the distribution. Neither the name of the UbixOS Project nor the names of its
contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 $Id: file.c,v 1.19 2003/05/01 12:30:02 reddawg Exp $

**************************************************************************************/

#include <ubixos/file.h>
#include <ubixos/schedule.h>
#include <ubixos/vitals.h>
#include <lib/kmalloc.h>
#include <lib/string.h>

fileDescriptor *fdTable = 0x0;

//These Are Temporary
int sprintf(char *buf,const char *fmt, ...);
char getch();

/************************************************************************

Function: fileDescriptor *fopen(const char *file,cont char *flags)
Description: This Will Open A File And Return A File Descriptor
Notes:

08/05/02 - Just Started A Rewrite Of This Function Should Work Out Well

************************************************************************/

fileDescriptor *fopen(const char *file,const char *flags) {
  int i = 0;
  fileDescriptor *tmpFd  = 0x0;
  char *path = 0x0,*mountPoint = 0x0;
  //Allocate Memory For File Descriptor
  tmpFd = (fileDescriptor *)kmalloc(sizeof(fileDescriptor),-2);

  path = (char *)strtok((char *)file,"@");
  mountPoint = strtok(NULL,"\n");
  if (mountPoint == 0x0) {
    tmpFd->mp = _current->oInfo.container;
    }
  else {
    tmpFd->mp = findMount(mountPoint);
    }
  if (tmpFd->mp == 0x0) {
    //sysErr("Mount Point Bad");
    return(0x0);
    }
  //This Will Set Up The Descriptor Modes
  while ('\0' != flags[i]) {
    switch(flags[i]) {
      case 'w':
      case 'W':
        tmpFd->mode = 1;
        break;
      case 'r':
      case 'R':
        tmpFd->mode = 0;
        break;
      default:
        break;
      }
    i++;
    }    
  //Search For The File
  if (tmpFd->mp->fs->openFile((char *)file,tmpFd) == 1) {
    //If The File Is Found Then Set Up The Descriptor
    tmpFd->buffer = (char *)kmalloc(4096,_current->id);
    sprintf(tmpFd->fileName,"%s",file);
    //Set Its Status To Open
    tmpFd->status = fdOpen;
    //Initial File Offset Is Zero
    tmpFd->offset = 0x0;
    //Pointer To Next Descriptor Is NULL
    tmpFd->prev = 0x0;
    //If This Is The First File Descriptor Then Set It Up To Be Starting Fd
    if (fdTable == 0x0) {
      fdTable     = tmpFd;
      tmpFd->next = 0x0;
      tmpFd->prev = 0x0;
      }
    else {
      //If There Is Already A Starting FD Set This Up As The Last One
      tmpFd->next   = fdTable;
      fdTable->prev = tmpFd;
      tmpFd->prev   = 0x0;
      fdTable       = tmpFd;
      }
    systemVitals->openFiles++;
    //Return The FD
    return(fdTable);
    }
  else {
    //If The File Was Not Found Free The Memory
    kfree(tmpFd);
    }
  //Return NULL
  return(0x0);
  }

/************************************************************************

Function: int feof(fileDescriptor *fd)
Description: Check A File Descriptor For EOF And Return Result
Notes:

************************************************************************/  
int feof(fileDescriptor *fd) {
  if (fd->status == fdEof) {
    return(-1);
    }
  return(0);
  }

/************************************************************************

Function: int fclose(fileDescriptor *fd);
Description: This Will Close And Free A File Descriptor
Notes:

************************************************************************/
int fclose(fileDescriptor *fd) {
  fileDescriptor *tmpFd = 0x0;
  //Search For File Descriptor
  for (tmpFd=fdTable;tmpFd;tmpFd=tmpFd->next) {
    if (tmpFd == fd) {
      //If Fd Is The First FD Then Reset fdTable
      if (tmpFd == fdTable) {
        fdTable = tmpFd->next;
        if (fdTable != 0x0) {
          fdTable->prev = 0x0;
          }
        kfree(fd->buffer);
        kfree(fd);
        systemVitals->openFiles--;
        return(1);
        }
      else {
        tmpFd->prev->next = tmpFd->next;
        tmpFd->next->prev = tmpFd->prev;
        kfree(fd->buffer);
        kfree(fd);
        systemVitals->openFiles--;
        return(1);
        }
      }    
    }
  //Return NULL If Descriptor Was Not Found
  return(0x0);
  }

/************************************************************************

Function: int fputc(int ch,fileDescriptor *fd)
Description: This Will Write Character To FD
Notes:

************************************************************************/
int fputc(int ch,fileDescriptor *fd) {
  fileDescriptor *tmpFd = 0x0;
  //Search For File Descriptor
  for (tmpFd=fdTable;tmpFd;tmpFd=tmpFd->next) {
    //If Found Return Next Char
    if (tmpFd == fd) {
      ch = tmpFd->mp->fs->write(tmpFd,(char *)ch,tmpFd->offset,1);
      tmpFd->offset++;
      return(ch);
      }
    }
  //Return NULL If FD Is Not Found
  return(0x0);
  }
  
/************************************************************************

Function: int fgetc(fileDescriptor *fd)
Description: This Will Return The Next Character In A FD Stream
Notes:

************************************************************************/  
int fgetc(fileDescriptor *fd) {
  int ch = 0x0;
  fileDescriptor *tmpFd = 0x0;
  //Search For File Descriptor
  for (tmpFd=fdTable;tmpFd;tmpFd=tmpFd->next) {
    //If Found Return Next Char
    if (tmpFd == fd) {
      tmpFd->mp->fs->read(tmpFd,(char *)ch,tmpFd->offset,1);
      tmpFd->offset++;
      return(ch);
      }
    }
  //Return NULL If FD Is Not Found
  return(0x0);
  }

size_t fread(void *ptr,int size,int nmemb,fileDescriptor *fd) {
  fileDescriptor *tmpFd = 0x0;
  //Search For File Descriptor
  for (tmpFd=fdTable;tmpFd;tmpFd=tmpFd->next) {
    //If Found Return Next Char
    if (tmpFd == fd) {
      tmpFd->mp->fs->read(tmpFd,ptr,tmpFd->offset,size * nmemb);
      tmpFd->offset += size * nmemb;
      }
    }
  return(0x0);
  }

size_t fwrite(void *ptr,int size,int nmemb,fileDescriptor *fd) {
  fileDescriptor *tmpFd = 0x0;
  //Search For File Descriptor
  for (tmpFd=fdTable;tmpFd;tmpFd=tmpFd->next) {
    //If Found Return Next Char
    if (tmpFd == fd) {
      tmpFd->mp->fs->write(tmpFd,ptr,tmpFd->offset,size * nmemb);
      tmpFd->offset += size * nmemb;
      }
    }
  return(0x0);
  }

/************************************************************************

Function: void sysFopen();
Description: Opens A File Descriptor For A User Task
Notes:

************************************************************************/
void sysFopen(char *file,char *flags,userFileDescriptor *userFd) {
  asm("sti");
  userFd->fd = fopen(file,flags);
  userFd->fdSize = userFd->fd->size;
  //Return
  return;
  }

/*
size_t fread(void *ptr, int size, int nmemb,fileDescriptor *fd) {
  
  // YO! what about EOF's in the middle of reading??

  int i = 0x0;
  char *data = (char *)ptr;
    for (i=0;i<size;i++) {
      data[i] = (char) fgetc(fd);
      }
  //Return
  return(size);
  }
*/  
/************************************************************************

Function: void sysFread();
Description: Reads SIZE Bytes From The userFd Into DATA
Notes:

************************************************************************/  
void sysFread(void *data,long size,userFileDescriptor *userFd) {
  asm("sti");
  fread(data,size,1,userFd->fd);
  //Return
  return;
  }

void sysFwrite(char *ptr,int size,userFileDescriptor *userFd) {
  char data[1024];
  int i=0;
  //Temp Hack
  if (userFd->fd == 0x0) {
    for (i=0;i<size;i++) {
      data[i] = ptr[i];
      }
    kprintf("%s",data);
    }
  else {
    fwrite(ptr,size,1,userFd->fd);
    }
  }
/************************************************************************

Function: void sysFclse();
Description: Closes A File Descriptor For A User Task
Notes:

************************************************************************/
void sysFclose(userFileDescriptor *userFd,int *status) {
  *status = fclose(userFd->fd);
  //Return
  return;
  }

void sysFgetc(int *ptr,userFileDescriptor *userFd) {
  fileDescriptor *tmpFd = 0x0;
  asm("sti");
  tmpFd = userFd->fd;
  if (userFd->fd == 0) {
    ptr[0] = (int) getch();
    }
  else {
    ptr[0] = (int) fgetc(tmpFd);
    }
  }
  
void sysMkDir() {
  return;
  }

void sysRmDir() {
  return;
  }

int fseek(fileDescriptor *tmpFd,long offset,int whence) {
  tmpFd->offset = offset+whence;
  return(tmpFd->offset);
  }

void sysFseek(userFileDescriptor *userFd,long offset,int whence) {
  kprintf("Word: [0x%X][0x%X]\n",userFd,userFd->fd);
  userFd->fd->offset = offset+whence;
  }