/*
	Software License Agreement (BSD License)
	
	Copyright (c) 1997-2008, David Lindauer, (LADSoft).
	All rights reserved.
	
	Redistribution and use of this software 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 and the
	  following disclaimer.
	
	* Redistributions in binary form must reproduce the above
	  copyright notice, this list of conditions and the
	  following disclaimer in the documentation and/or other
	  materials provided with the distribution.
	
	* Neither the name of LADSoft nor the names of its
	  contributors may be used to endorse or promote products
	  derived from this software without specific prior
	  written permission of LADSoft.
	
	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.
*/
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <time.h>
#include <wchar.h>
#include <locale.h>
#include "libp.h"
#include <limits.h>
#include <wchar.h>
#include <stdlib.h>
#include <wctype.h>
#include <float.h>
#ifdef _i386_
#define USE_FLOAT
#endif

#define STP 1

wchar_t *__wstrtoone(FILE *fil, const wchar_t *format, void *arg, int *count,int *chars, int *ch)
{
    int stpdef;
    wchar_t *stplst;
    LLONG_TYPE max=INT_MAX,min= INT_MIN;
	int ignore = 0;
	int width = INT_MAX;
	int size = 0;
	int sgn = 0;
   int skip=0,didit = 0;
   int type ;
	unsigned cu;
   wchar_t *s;
   int i;
   int radix = 0 ;
   int lc = 0x20 ;
	long double fval;
   LLONG_TYPE c ;
   wchar_t fbuf[40];
   char mbbuf[40];
   mbstate_t st;
	int found = 0;
	
	if (*format == '*') {
		ignore = 1;
		format++;
	}
	if (isdigit(*format))  {
      width = 0;
      while (isdigit(*format))
			width = width *10 + *format++ -'0';
    }
   if (*format == 'h' || *format == 'l') {
		size = *format++;
      if (size == 'h') {
        max = SHRT_MAX;
        min = SHRT_MIN;
        if (*format == 'h') {
            max = CHAR_MAX;
            min = CHAR_MIN;
            size = 'c';
            format++;
        }
      } else if (*format == 'l') {
         max = LLONG_MAX;
         min = LLONG_MIN;
         size = '1' ;
         format++ ;
      }
   }
   else if (*format == 'L')
    size = *format++;
   else if (*format == 'z' || *format == 't')
    format++;
   else if (*format == 'j') {
    size = '1';
    format++;
   }

   type = *format++ ;
   if (isalpha(type) && !(type & 0x20)) {
     lc = 0;
     type |= 0x20;
   }
   switch((type)) {
		case 'c':
            if (width == INT_MAX) 
                width = 1;
            if (size != 'l') {
                memset(&st,0,sizeof(st));
                while (width > 0 && *ch) {
                    int l;
                    l = wcrtomb(mbbuf,(wchar_t)ch,&st);
                    width--;
                    if (l > 0 && !ignore) {
                        memcpy(arg,mbbuf,l);
                        (char *)arg += l;
                    }
                    (*chars)++;
                    *ch = fgetwc(fil);
                }
            }
			else {
              while (width--) {
				(*chars)++;
                if (*ch == EOF)
					return EOF;

				if (!ignore) {
                   *((wchar_t *)arg)++ = (wchar_t)*ch;
				}		
                *ch = fgetwc(fil) ;
              }
			}
         if (!ignore) {
            (*count)++;
         }     
         break ;
		case 'd':
        case 'u':
        case 'x':
        case 'o':
        case 'i':
        case 'p':
         while (*ch != EOF && isspace(*ch)) {
            *ch = fgetwc(fil) ;
            (*chars)++ ;
         }
		 if (!isdigit(*ch) && *ch != '-' && *ch != '+')
			 return NULL;
         switch(type) {
            case 'd':
                 c = __xwcstoimax(fil,width,ch,chars,10,max,0, STRT_ERR_RET_SIGNED);
                 break;
            case 'i':
                 c = __xwcstoimax(fil,width,ch,chars,0,max,0, STRT_ERR_RET_SIGNED);
                 break;
            case 'u':
                 c = __xwcstoimax(fil,width,ch,chars,10,max,0, STRT_ERR_RET_UNSIGNED);
                 break;
            case 'x':
            case 'p':
                 c = __xwcstoimax(fil,width,ch,chars,16,max,0, STRT_ERR_RET_UNSIGNED);
                 break;
            case 'o':
                 c = __xwcstoimax(fil,width,ch,chars,8,max,0, STRT_ERR_RET_UNSIGNED);
                 break;
         }
            if (!ignore) {
                (*count)++;
                if (size == '1')
                   *(LLONG_TYPE *)arg = c ;
                else if (size == 'l' || size == 'L')
                   *(long *)arg = c ;
                else if (size == 'h') 
    					*(short *)arg = (short)c;
                    else if (size == 'c')
                        *(wchar_t *)arg = (char)c;
    				else
                   *(int *)arg = (int)c;
    	    }
         break ;
		case 'e':
		case 'f':
		case 'g': 
        case 'a':
#ifndef USE_FLOAT
				fprintf(stderr,"FP not linked");
#else
         while (*ch != EOF && isspace(*ch)) {
            *ch = fgetwc(fil) ;
            (*chars)++ ;
         }
		 if (!isdigit(*ch) && *ch != '-' && *ch != '+' && *ch != '.')
			 return NULL;
				if (!ignore) {
					(*count)++;
               if (size == 'l') 
                  *(double *)arg = 
                        __xwcstod(fil,width,ch,chars, DBL_MAX, DBL_MAX_EXP, DBL_MAX_10_EXP,0);
               else 
                    *(float *)arg = 
                        __xwcstod(fil,width,ch,chars, FLT_MAX, FLT_MAX_EXP, FLT_MAX_10_EXP,0);
				}
#endif
			break;
		case 'n':
         if (!ignore) {
             if (size == '1') {
                *(LLONG_TYPE *)arg = (*chars) ;
             } else if (size == 'l' || size == 'L')
                *(long *)arg = (*chars) ;
             else if (size == 'h')
                *(short *)arg = (*chars) ;
             else if (size == 'c')
                *(wchar_t *)arg = (*chars) ;
             else
                *(int *)arg = (*chars);
         }
	     break;
      case '[': {
           int c,count=0,j=0 ;
           wchar_t *fmt = format;
           if (*format == '^') {
              format++,fmt++ ;
              stpdef = 0;
           } else
            stpdef = STP;
           while (*fmt == ']' || *fmt == '-')
                count++;
           while ((c = *fmt++) != ']' && c)  {
              if (c == '-' && *fmt != ']') {
                 if (*fmt >= *(fmt-2))
                     count += *fmt - *(fmt -2) + 1;
                 fmt++ ;
              } else
                count++;
           }
           stplst = calloc(sizeof(wchar_t),count+1);
           if (!stplst)
            return 0;
           j = 0;
           while (*format == ']' || *format == '-')
              stplst[j++] = *format++;
           while ((c = *format++) != ']' && c)  {
              if (c == '-' && *format != ']') {
                 for (i= *(format-2) ; i <= (*format); i++)
                    stplst[j++] = i;
                 format++ ;
              } else
                stplst[j++] = c;

           }
         }
         if ( c== 0)
           format-- ;
         /* fall through */
		case 's':
         if (type == 's') {
            int j;
            int count = 0;
            stpdef = 0;
            for (i=0; i <= WCHAR_MAX; i++) {
                if (iswspace(i))
                    count++;
            }
           stplst = calloc(sizeof(wchar_t),count+1);
           if (!stplst)
            return 0;
           j = 0;
            for (i=0; i <= WCHAR_MAX; i++) {
                if (iswspace(i))
                    stplst[j++] = i;
            }
            while (*ch != EOF && (stpdef && !wcschr(stplst,*ch) 
                            || !stpdef && wcschr(stplst,*ch))) {
                *ch = fgetwc(fil) ;
				found++;
                (*chars)++ ;
            }
         } 
 		 s = (wchar_t *)arg;
         skip = width == INT_MAX ? 0 : 1;
         memset(&st,0,sizeof(st));
         while (*ch != EOF && (width || !skip) && !(stpdef && !wcschr(stplst,*ch) 
                            || !stpdef && wcschr(stplst,*ch))) {
            if (size != 'l') {
                    int l ;
                    l = wcrtomb(mbbuf,(wchar_t)*ch,&st);
                    if (l > 0 && !ignore) {
                        memcpy(arg,mbbuf,l);
                        (char *)arg += l;
                    }
                    *ch = fgetwc(fil);
                    width--;
					found++;
                    (*chars)++;
            } else {
               if (!ignore)
                 *s++ = *ch;
               *ch = fgetwc(fil) ;
               width--;
			   found++;
               (*chars)++;
            }
         }

         if (!ignore) {
            if (size == 'l')
                *(wchar_t *)s = L'\0';
            else
                *(char *)arg = 0;
			if (found)
	           (*count) ++;
         }
         free(stplst);
         break;
		case '%':
            if (*ch != '%')
					return 0;
            *ch = fgetwc(fil) ;
				break;
		default:
			format++;
	}
	return format;
}

int __wscanf(FILE *fil, const wchar_t *format,void *arglist)
{
   int i = 0,j=0;
   int ch = fgetwc(fil) ;
   while (format && *format && ch != EOF) {
      while (format && *format != '%' && *format) {
        if (isspace(*format)) {
            while (ch != EOF && iswspace(ch)) {
               ch = fgetwc(fil) ;
               j++ ;
            }
            while (*format && iswspace(*format)) format++;
		}
		else  {
            if (*format++ != ch) {
                ungetwc(ch,fil);
                return i;
            }
            ch = fgetwc(fil) ;
            j++;
		}
	  }
      if (*format && ch != EOF) {
	      format++;
          format = __wstrtoone(fil,format,((void **)arglist)[i],&i,&j,&ch);
	  }
	}
    ungetwc(ch,fil);
    return(i);
}


