file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/50136994.c | int print_char(char c);
void print_alphabet(void);
int main(void)
{
print_alphabet();
return (0);
}
|
the_stack_data/583265.c | /*
* Program to remove trailing blanks and tabs from each line of input
* Also deletes entirely blank lines
* created by Anvesh G. Jhuboo
* on Feb/5/21
*/
#include <stdio.h>
#define MAXLINE 1000 /* max input line length */
char line[MAXLINE + 1];
int getline2(void);
int main()
{
int len; /* current line length */
int head, tail, inn; /* states */
extern char line[]; /* current input line */
while ((len = getline2()) > 0) {
for (head = 0; line[head] == ' ' ||
line[head] == '\t'; head++);
for (tail = len; line[tail] == ' ' ||
line[tail] == '\t' ||
line[tail] == '\n' ||
line[tail] == '\0'; tail--);
if (tail - head >= 0) {
for (inn = head; inn <= tail; inn++)
putchar(line[inn]);
putchar('\n');
putchar('\0');
}
}
}
int getline2(void)
{
extern char line[];
int c, i;
for (i = 0; i < MAXLINE-1 && (c = getchar()) != EOF && c != '\n'; i++)
line[i] = c;
if (c == '\n') {
line[i] = c;
++i;
}
line[i] = '\0';
return i;
}
|
the_stack_data/63932.c | int main() {
int a = 0;
for (int i = 0; i < 3; i = i + 1)
a = a + 1;
return a;
} |
the_stack_data/90762711.c | /*Exercise 3 - Repetition
Write a C program to calculate the sum of the numbers from 1 to n.
Where n is a keyboard input.
e.g.
n -> 100
sum = 1+2+3+....+ 99+100 = 5050
n -> 1-
sum = 1+2+3+...+10 = 55 */
#include <stdio.h>
int main()
{
//creating variables
int num, i, sum=0;
//getting keyboard input
printf ("The sum of the numbers from 1 to ");
scanf ("%d",&num);
for ( i=1 ; i<=num ;i++ )
{
sum += i;
}
//getting the sum of numbers
printf ("Sum of the %d numbers = %d", num, sum);
return 0;
}
|
the_stack_data/102549.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
int a, b, c, diskriminant;
printf("ax^2 + bx + c seklinde verilmis olan 2. dereceden denklem icin a, b, c degerlerini giriniz: \n");
printf("a degerini giriniz:");
scanf("%d", &a);
printf("b degerini giriniz:");
scanf("%d", &b);
printf("c degerini giriniz:");
scanf("%d", &c);
diskriminant = b * b - 4 * a * c;
if (diskriminant > 0)
{
printf("Denklemin iki farkli reel koku vardir");
}
else if (diskriminant == 0)
{
printf("Denklemin bir tane reel koku vardir");
}
else if (diskriminant < 0)
{
printf("Denklemin reel koku bulunmamaktadir.");
}
return 0;
}
|
the_stack_data/384693.c | /*
Copyright (C) 1991-2018 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it andor
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http:www.gnu.org/licenses/>.
*/
/*
This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it.
*/
/*
glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default.
*/
/*
wchar_t uses Unicode 10.0.0. Version 10.0 of the Unicode Standard is
synchronized with ISOIEC 10646:2017, fifth edition, plus
the following additions from Amendment 1 to the fifth edition:
- 56 emoji characters
- 285 hentaigana
- 3 additional Zanabazar Square characters
*/
/*
Copyright (c) 2017, Lawrence Livermore National Security, LLC.
Produced at the Lawrence Livermore National Laboratory
Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund,
Markus Schordan, and Ian Karlin
(email: [email protected], [email protected], [email protected],
[email protected], [email protected])
LLNL-CODE-732144
All rights reserved.
This file is part of DataRaceBench. For details, see
https:github.comLLNL/dataracebench. Please also see the LICENSE file
for our additional BSD notice.
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 and the disclaimer below.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the disclaimer (as noted below)
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL
SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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>
/*
use of omp target + teams + distribute + parallel for
*/
int main(int argc, char * argv[])
{
int i, i2;
int len = 2560;
double sum = 0.0, sum2 = 0.0;
double a[len], b[len];
/* Initialize with some values */
int _ret_val_0;
#pragma cetus private(i)
#pragma loop name main#0
#pragma cetus parallel
#pragma omp parallel for private(i)
for (i=0; i<len; i ++ )
{
a[i]=(((double)i)/2.0);
b[i]=(((double)i)/3.0);
}
#pragma cetus private(i, i2)
#pragma loop name main#1
#pragma cetus reduction(+: sum)
#pragma cetus parallel
#pragma omp parallel for private(i, i2) reduction(+: sum)
for (i2=0; i2<len; i2+=256)
{
#pragma cetus private(i)
#pragma loop name main#1#0
#pragma cetus reduction(+: sum)
#pragma cetus parallel
#pragma omp parallel for private(i) reduction(+: sum)
for (i=i2; i<(((i2+256)<len) ? (i2+256) : len); i ++ )
{
sum+=(a[i]*b[i]);
}
}
/* CPU reference computation */
#pragma cetus private(i)
#pragma loop name main#2
#pragma cetus reduction(+: sum2)
#pragma cetus parallel
#pragma omp parallel for private(i) reduction(+: sum2)
for (i=0; i<len; i ++ )
{
sum2+=(a[i]*b[i]);
}
printf("sum=%f sum2=%f\n", sum, sum2);
_ret_val_0=0;
return _ret_val_0;
}
|
the_stack_data/723571.c | /*
* Copyright 2021 Patrick Paul
* SPDX-License-Identifier: MIT-0
*/
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdarg.h>
extern void PSP_Console_Write(char *buffer);
char bsp_ff_buffer[100];
void BSP_FF_PRINTF(char *format, ...){
va_list va;
va_start(va, format);
vsprintf(bsp_ff_buffer, format, va);
va_end(va);
PSP_Console_Write(bsp_ff_buffer);
} |
the_stack_data/817595.c | /* A Bison parser, made by GNU Bison 2.3. */
/* Skeleton implementation for Bison's Yacc-like parsers in C
Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
Free Software Foundation, Inc.
This program 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, or (at your option)
any later version.
This program 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 this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* C LALR(1) parser skeleton written by Richard Stallman, by
simplifying the original so-called "semantic" parser. */
/* All symbols defined below should begin with yy or YY, to avoid
infringing on user name space. This should be done even for local
variables, as they might otherwise be expanded by user macros.
There are some unavoidable exceptions within include files to
define necessary library symbols; they are noted "INFRINGES ON
USER NAME SPACE" below. */
/* Identify Bison output. */
#define YYBISON 1
/* Bison version. */
#define YYBISON_VERSION "2.3"
/* Skeleton name. */
#define YYSKELETON_NAME "yacc.c"
/* Pure parsers. */
#define YYPURE 0
/* Using locations. */
#define YYLSP_NEEDED 0
/* Tokens. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
/* Put the tokens into the symbol table, so that GDB and other debuggers
know about them. */
enum yytokentype {
COND = 258,
REPEAT = 259,
TYPE = 260,
NAME = 261,
NUMBER = 262,
UNIT = 263
};
#endif
/* Tokens. */
#define COND 258
#define REPEAT 259
#define TYPE 260
#define NAME 261
#define NUMBER 262
#define UNIT 263
/* Copy the first part of user declarations. */
#line 21 "sysinfo.y"
#include <stdio.h>
#include <stdlib.h>
static char writecode;
static char *it;
static int code;
static char * repeat;
static char *oldrepeat;
static char *name;
static int rdepth;
static char *names[] = {" ","[n]","[n][m]"};
static char *pnames[]= {"","*","**"};
static int yyerror (char *s);
extern int yylex (void);
/* Enabling traces. */
#ifndef YYDEBUG
# define YYDEBUG 0
#endif
/* Enabling verbose error messages. */
#ifdef YYERROR_VERBOSE
# undef YYERROR_VERBOSE
# define YYERROR_VERBOSE 1
#else
# define YYERROR_VERBOSE 0
#endif
/* Enabling the token table. */
#ifndef YYTOKEN_TABLE
# define YYTOKEN_TABLE 0
#endif
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef union YYSTYPE
#line 40 "sysinfo.y"
{
int i;
char *s;
}
/* Line 193 of yacc.c. */
#line 135 "sysinfo.c"
YYSTYPE;
# define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1
# define YYSTYPE_IS_TRIVIAL 1
#endif
/* Copy the second part of user declarations. */
/* Line 216 of yacc.c. */
#line 148 "sysinfo.c"
#ifdef short
# undef short
#endif
#ifdef YYTYPE_UINT8
typedef YYTYPE_UINT8 yytype_uint8;
#else
typedef unsigned char yytype_uint8;
#endif
#ifdef YYTYPE_INT8
typedef YYTYPE_INT8 yytype_int8;
#elif (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
typedef signed char yytype_int8;
#else
typedef short int yytype_int8;
#endif
#ifdef YYTYPE_UINT16
typedef YYTYPE_UINT16 yytype_uint16;
#else
typedef unsigned short int yytype_uint16;
#endif
#ifdef YYTYPE_INT16
typedef YYTYPE_INT16 yytype_int16;
#else
typedef short int yytype_int16;
#endif
#ifndef YYSIZE_T
# ifdef __SIZE_TYPE__
# define YYSIZE_T __SIZE_TYPE__
# elif defined size_t
# define YYSIZE_T size_t
# elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
# define YYSIZE_T size_t
# else
# define YYSIZE_T unsigned int
# endif
#endif
#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
#ifndef YY_
# if defined YYENABLE_NLS && YYENABLE_NLS
# if ENABLE_NLS
# include <libintl.h> /* INFRINGES ON USER NAME SPACE */
# define YY_(msgid) dgettext ("bison-runtime", msgid)
# endif
# endif
# ifndef YY_
# define YY_(msgid) msgid
# endif
#endif
/* Suppress unused-variable warnings by "using" E. */
#if ! defined lint || defined __GNUC__
# define YYUSE(e) ((void) (e))
#else
# define YYUSE(e) /* empty */
#endif
/* Identity function, used to suppress warnings about constant conditions. */
#ifndef lint
# define YYID(n) (n)
#else
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static int
YYID (int i)
#else
static int
YYID (i)
int i;
#endif
{
return i;
}
#endif
#if ! defined yyoverflow || YYERROR_VERBOSE
/* The parser invokes alloca or malloc; define the necessary symbols. */
# ifdef YYSTACK_USE_ALLOCA
# if YYSTACK_USE_ALLOCA
# ifdef __GNUC__
# define YYSTACK_ALLOC __builtin_alloca
# elif defined __BUILTIN_VA_ARG_INCR
# include <alloca.h> /* INFRINGES ON USER NAME SPACE */
# elif defined _AIX
# define YYSTACK_ALLOC __alloca
# elif defined _MSC_VER
# include <malloc.h> /* INFRINGES ON USER NAME SPACE */
# define alloca _alloca
# else
# define YYSTACK_ALLOC alloca
# if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
# ifndef _STDLIB_H
# define _STDLIB_H 1
# endif
# endif
# endif
# endif
# endif
# ifdef YYSTACK_ALLOC
/* Pacify GCC's `empty if-body' warning. */
# define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0))
# ifndef YYSTACK_ALLOC_MAXIMUM
/* The OS might guarantee only one guard page at the bottom of the stack,
and a page size can be as small as 4096 bytes. So we cannot safely
invoke alloca (N) if N exceeds 4096. Use a slightly smaller number
to allow for a few compiler-allocated temporary stack slots. */
# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
# endif
# else
# define YYSTACK_ALLOC YYMALLOC
# define YYSTACK_FREE YYFREE
# ifndef YYSTACK_ALLOC_MAXIMUM
# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
# endif
# if (defined __cplusplus && ! defined _STDLIB_H \
&& ! ((defined YYMALLOC || defined malloc) \
&& (defined YYFREE || defined free)))
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
# ifndef _STDLIB_H
# define _STDLIB_H 1
# endif
# endif
# ifndef YYMALLOC
# define YYMALLOC malloc
# if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# ifndef YYFREE
# define YYFREE free
# if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
void free (void *); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# endif
#endif /* ! defined yyoverflow || YYERROR_VERBOSE */
#if (! defined yyoverflow \
&& (! defined __cplusplus \
|| (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
/* A type that is properly aligned for any stack member. */
union yyalloc
{
yytype_int16 yyss;
YYSTYPE yyvs;
};
/* The size of the maximum gap between one aligned stack and the next. */
# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
/* The size of an array large to enough to hold all stacks, each with
N elements. */
# define YYSTACK_BYTES(N) \
((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \
+ YYSTACK_GAP_MAXIMUM)
/* Copy COUNT objects from FROM to TO. The source and destination do
not overlap. */
# ifndef YYCOPY
# if defined __GNUC__ && 1 < __GNUC__
# define YYCOPY(To, From, Count) \
__builtin_memcpy (To, From, (Count) * sizeof (*(From)))
# else
# define YYCOPY(To, From, Count) \
do \
{ \
YYSIZE_T yyi; \
for (yyi = 0; yyi < (Count); yyi++) \
(To)[yyi] = (From)[yyi]; \
} \
while (YYID (0))
# endif
# endif
/* Relocate STACK from its old location to the new one. The
local variables YYSIZE and YYSTACKSIZE give the old and new number of
elements in the stack, and YYPTR gives the new location of the
stack. Advance YYPTR to a properly aligned location for the next
stack. */
# define YYSTACK_RELOCATE(Stack) \
do \
{ \
YYSIZE_T yynewbytes; \
YYCOPY (&yyptr->Stack, Stack, yysize); \
Stack = &yyptr->Stack; \
yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
yyptr += yynewbytes / sizeof (*yyptr); \
} \
while (YYID (0))
#endif
/* YYFINAL -- State number of the termination state. */
#define YYFINAL 3
/* YYLAST -- Last index in YYTABLE. */
#define YYLAST 38
/* YYNTOKENS -- Number of terminals. */
#define YYNTOKENS 11
/* YYNNTS -- Number of nonterminals. */
#define YYNNTS 19
/* YYNRULES -- Number of rules. */
#define YYNRULES 27
/* YYNRULES -- Number of states. */
#define YYNSTATES 55
/* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */
#define YYUNDEFTOK 2
#define YYMAXUTOK 263
#define YYTRANSLATE(YYX) \
((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
/* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */
static const yytype_uint8 yytranslate[] =
{
0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
5, 6, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 1, 2, 3, 4,
7, 8, 9, 10
};
#if YYDEBUG
/* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in
YYRHS. */
static const yytype_uint8 yyprhs[] =
{
0, 0, 3, 4, 7, 10, 11, 12, 19, 22,
25, 28, 29, 30, 37, 38, 45, 46, 57, 59,
60, 64, 67, 71, 72, 73, 77, 78
};
/* YYRHS -- A `-1'-separated list of the rules' RHS. */
static const yytype_int8 yyrhs[] =
{
12, 0, -1, -1, 13, 14, -1, 15, 14, -1,
-1, -1, 5, 8, 9, 16, 17, 6, -1, 22,
17, -1, 20, 17, -1, 18, 17, -1, -1, -1,
5, 4, 8, 19, 17, 6, -1, -1, 5, 3,
8, 21, 17, 6, -1, -1, 5, 25, 5, 24,
26, 6, 27, 23, 28, 6, -1, 7, -1, -1,
5, 8, 6, -1, 9, 10, -1, 5, 8, 6,
-1, -1, -1, 5, 29, 6, -1, -1, 29, 5,
8, 8, 6, -1
};
/* YYRLINE[YYN] -- source line where rule number YYN was defined. */
static const yytype_uint16 yyrline[] =
{
0, 54, 54, 54, 92, 93, 98, 97, 169, 170,
171, 172, 176, 175, 223, 222, 250, 249, 357, 358,
362, 367, 373, 374, 377, 378, 380, 382
};
#endif
#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE
/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
First, the terminals, then, starting at YYNTOKENS, nonterminals. */
static const char *const yytname[] =
{
"$end", "error", "$undefined", "COND", "REPEAT", "'('", "')'", "TYPE",
"NAME", "NUMBER", "UNIT", "$accept", "top", "@1", "it_list", "it", "@2",
"it_field_list", "repeat_it_field", "@3", "cond_it_field", "@4",
"it_field", "@5", "attr_type", "attr_desc", "attr_size", "attr_id",
"enums", "enum_list", 0
};
#endif
# ifdef YYPRINT
/* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to
token YYLEX-NUM. */
static const yytype_uint16 yytoknum[] =
{
0, 256, 257, 258, 259, 40, 41, 260, 261, 262,
263
};
# endif
/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
static const yytype_uint8 yyr1[] =
{
0, 11, 13, 12, 14, 14, 16, 15, 17, 17,
17, 17, 19, 18, 21, 20, 23, 22, 24, 24,
25, 26, 27, 27, 28, 28, 29, 29
};
/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */
static const yytype_uint8 yyr2[] =
{
0, 2, 0, 2, 2, 0, 0, 6, 2, 2,
2, 0, 0, 6, 0, 6, 0, 10, 1, 0,
3, 2, 3, 0, 0, 3, 0, 5
};
/* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state
STATE-NUM when YYTABLE doesn't specify something else to do. Zero
means the default is an error. */
static const yytype_uint8 yydefact[] =
{
2, 0, 5, 1, 0, 3, 5, 0, 4, 6,
11, 0, 0, 11, 11, 11, 0, 0, 0, 0,
7, 10, 9, 8, 14, 12, 0, 19, 11, 11,
20, 18, 0, 0, 0, 0, 0, 15, 13, 21,
23, 0, 16, 0, 24, 22, 26, 0, 0, 17,
0, 25, 0, 0, 27
};
/* YYDEFGOTO[NTERM-NUM]. */
static const yytype_int8 yydefgoto[] =
{
-1, 1, 2, 5, 6, 10, 12, 13, 29, 14,
28, 15, 44, 32, 19, 36, 42, 47, 48
};
/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
STATE-NUM. */
#define YYPACT_NINF -14
static const yytype_int8 yypact[] =
{
-14, 8, 4, -14, 2, -14, 4, 3, -14, -14,
6, 0, 7, 6, 6, 6, 9, 10, 11, 15,
-14, -14, -14, -14, -14, -14, 16, 14, 6, 6,
-14, -14, 5, 17, 18, 19, 20, -14, -14, -14,
22, 23, -14, 24, 27, -14, -14, 28, 1, -14,
25, -14, 29, 30, -14
};
/* YYPGOTO[NTERM-NUM]. */
static const yytype_int8 yypgoto[] =
{
-14, -14, -14, 32, -14, -14, -13, -14, -14, -14,
-14, -14, -14, -14, -14, -14, -14, -14, -14
};
/* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If
positive, shift that token. If negative, reduce the rule which
number is the opposite. If zero, do what YYDEFACT says.
If YYTABLE_NINF, syntax error. */
#define YYTABLE_NINF -1
static const yytype_uint8 yytable[] =
{
21, 22, 23, 16, 17, 18, 50, 51, 3, 4,
7, 11, 9, 20, 35, 33, 34, 24, 25, 26,
27, 31, 30, 37, 38, 0, 40, 41, 0, 39,
45, 43, 46, 52, 49, 0, 54, 53, 8
};
static const yytype_int8 yycheck[] =
{
13, 14, 15, 3, 4, 5, 5, 6, 0, 5,
8, 5, 9, 6, 9, 28, 29, 8, 8, 8,
5, 7, 6, 6, 6, -1, 6, 5, -1, 10,
6, 8, 5, 8, 6, -1, 6, 8, 6
};
/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
symbol of state STATE-NUM. */
static const yytype_uint8 yystos[] =
{
0, 12, 13, 0, 5, 14, 15, 8, 14, 9,
16, 5, 17, 18, 20, 22, 3, 4, 5, 25,
6, 17, 17, 17, 8, 8, 8, 5, 21, 19,
6, 7, 24, 17, 17, 9, 26, 6, 6, 10,
6, 5, 27, 8, 23, 6, 5, 28, 29, 6,
5, 6, 8, 8, 6
};
#define yyerrok (yyerrstatus = 0)
#define yyclearin (yychar = YYEMPTY)
#define YYEMPTY (-2)
#define YYEOF 0
#define YYACCEPT goto yyacceptlab
#define YYABORT goto yyabortlab
#define YYERROR goto yyerrorlab
/* Like YYERROR except do call yyerror. This remains here temporarily
to ease the transition to the new meaning of YYERROR, for GCC.
Once GCC version 2 has supplanted version 1, this can go. */
#define YYFAIL goto yyerrlab
#define YYRECOVERING() (!!yyerrstatus)
#define YYBACKUP(Token, Value) \
do \
if (yychar == YYEMPTY && yylen == 1) \
{ \
yychar = (Token); \
yylval = (Value); \
yytoken = YYTRANSLATE (yychar); \
YYPOPSTACK (1); \
goto yybackup; \
} \
else \
{ \
yyerror (YY_("syntax error: cannot back up")); \
YYERROR; \
} \
while (YYID (0))
#define YYTERROR 1
#define YYERRCODE 256
/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
If N is 0, then set CURRENT to the empty location which ends
the previous symbol: RHS[0] (always defined). */
#define YYRHSLOC(Rhs, K) ((Rhs)[K])
#ifndef YYLLOC_DEFAULT
# define YYLLOC_DEFAULT(Current, Rhs, N) \
do \
if (YYID (N)) \
{ \
(Current).first_line = YYRHSLOC (Rhs, 1).first_line; \
(Current).first_column = YYRHSLOC (Rhs, 1).first_column; \
(Current).last_line = YYRHSLOC (Rhs, N).last_line; \
(Current).last_column = YYRHSLOC (Rhs, N).last_column; \
} \
else \
{ \
(Current).first_line = (Current).last_line = \
YYRHSLOC (Rhs, 0).last_line; \
(Current).first_column = (Current).last_column = \
YYRHSLOC (Rhs, 0).last_column; \
} \
while (YYID (0))
#endif
/* YY_LOCATION_PRINT -- Print the location on the stream.
This macro was not mandated originally: define only if we know
we won't break user code: when these are the locations we know. */
#ifndef YY_LOCATION_PRINT
# if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL
# define YY_LOCATION_PRINT(File, Loc) \
fprintf (File, "%d.%d-%d.%d", \
(Loc).first_line, (Loc).first_column, \
(Loc).last_line, (Loc).last_column)
# else
# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
# endif
#endif
/* YYLEX -- calling `yylex' with the right arguments. */
#ifdef YYLEX_PARAM
# define YYLEX yylex (YYLEX_PARAM)
#else
# define YYLEX yylex ()
#endif
/* Enable debugging if requested. */
#if YYDEBUG
# ifndef YYFPRINTF
# include <stdio.h> /* INFRINGES ON USER NAME SPACE */
# define YYFPRINTF fprintf
# endif
# define YYDPRINTF(Args) \
do { \
if (yydebug) \
YYFPRINTF Args; \
} while (YYID (0))
# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
do { \
if (yydebug) \
{ \
YYFPRINTF (stderr, "%s ", Title); \
yy_symbol_print (stderr, \
Type, Value); \
YYFPRINTF (stderr, "\n"); \
} \
} while (YYID (0))
/*--------------------------------.
| Print this symbol on YYOUTPUT. |
`--------------------------------*/
/*ARGSUSED*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
#else
static void
yy_symbol_value_print (yyoutput, yytype, yyvaluep)
FILE *yyoutput;
int yytype;
YYSTYPE const * const yyvaluep;
#endif
{
if (!yyvaluep)
return;
# ifdef YYPRINT
if (yytype < YYNTOKENS)
YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
# else
YYUSE (yyoutput);
# endif
switch (yytype)
{
default:
break;
}
}
/*--------------------------------.
| Print this symbol on YYOUTPUT. |
`--------------------------------*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
#else
static void
yy_symbol_print (yyoutput, yytype, yyvaluep)
FILE *yyoutput;
int yytype;
YYSTYPE const * const yyvaluep;
#endif
{
if (yytype < YYNTOKENS)
YYFPRINTF (yyoutput, "token %s (", yytname[yytype]);
else
YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]);
yy_symbol_value_print (yyoutput, yytype, yyvaluep);
YYFPRINTF (yyoutput, ")");
}
/*------------------------------------------------------------------.
| yy_stack_print -- Print the state stack from its BOTTOM up to its |
| TOP (included). |
`------------------------------------------------------------------*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yy_stack_print (yytype_int16 *bottom, yytype_int16 *top)
#else
static void
yy_stack_print (bottom, top)
yytype_int16 *bottom;
yytype_int16 *top;
#endif
{
YYFPRINTF (stderr, "Stack now");
for (; bottom <= top; ++bottom)
YYFPRINTF (stderr, " %d", *bottom);
YYFPRINTF (stderr, "\n");
}
# define YY_STACK_PRINT(Bottom, Top) \
do { \
if (yydebug) \
yy_stack_print ((Bottom), (Top)); \
} while (YYID (0))
/*------------------------------------------------.
| Report that the YYRULE is going to be reduced. |
`------------------------------------------------*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yy_reduce_print (YYSTYPE *yyvsp, int yyrule)
#else
static void
yy_reduce_print (yyvsp, yyrule)
YYSTYPE *yyvsp;
int yyrule;
#endif
{
int yynrhs = yyr2[yyrule];
int yyi;
unsigned long int yylno = yyrline[yyrule];
YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
yyrule - 1, yylno);
/* The symbols being reduced. */
for (yyi = 0; yyi < yynrhs; yyi++)
{
fprintf (stderr, " $%d = ", yyi + 1);
yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi],
&(yyvsp[(yyi + 1) - (yynrhs)])
);
fprintf (stderr, "\n");
}
}
# define YY_REDUCE_PRINT(Rule) \
do { \
if (yydebug) \
yy_reduce_print (yyvsp, Rule); \
} while (YYID (0))
/* Nonzero means print parse trace. It is left uninitialized so that
multiple parsers can coexist. */
int yydebug;
#else /* !YYDEBUG */
# define YYDPRINTF(Args)
# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
# define YY_STACK_PRINT(Bottom, Top)
# define YY_REDUCE_PRINT(Rule)
#endif /* !YYDEBUG */
/* YYINITDEPTH -- initial size of the parser's stacks. */
#ifndef YYINITDEPTH
# define YYINITDEPTH 200
#endif
/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
if the built-in stack extension method is used).
Do not make this value too large; the results are undefined if
YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
evaluated with infinite-precision integer arithmetic. */
#ifndef YYMAXDEPTH
# define YYMAXDEPTH 10000
#endif
#if YYERROR_VERBOSE
# ifndef yystrlen
# if defined __GLIBC__ && defined _STRING_H
# define yystrlen strlen
# else
/* Return the length of YYSTR. */
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static YYSIZE_T
yystrlen (const char *yystr)
#else
static YYSIZE_T
yystrlen (yystr)
const char *yystr;
#endif
{
YYSIZE_T yylen;
for (yylen = 0; yystr[yylen]; yylen++)
continue;
return yylen;
}
# endif
# endif
# ifndef yystpcpy
# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
# define yystpcpy stpcpy
# else
/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
YYDEST. */
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static char *
yystpcpy (char *yydest, const char *yysrc)
#else
static char *
yystpcpy (yydest, yysrc)
char *yydest;
const char *yysrc;
#endif
{
char *yyd = yydest;
const char *yys = yysrc;
while ((*yyd++ = *yys++) != '\0')
continue;
return yyd - 1;
}
# endif
# endif
# ifndef yytnamerr
/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
quotes and backslashes, so that it's suitable for yyerror. The
heuristic is that double-quoting is unnecessary unless the string
contains an apostrophe, a comma, or backslash (other than
backslash-backslash). YYSTR is taken from yytname. If YYRES is
null, do not copy; instead, return the length of what the result
would have been. */
static YYSIZE_T
yytnamerr (char *yyres, const char *yystr)
{
if (*yystr == '"')
{
YYSIZE_T yyn = 0;
char const *yyp = yystr;
for (;;)
switch (*++yyp)
{
case '\'':
case ',':
goto do_not_strip_quotes;
case '\\':
if (*++yyp != '\\')
goto do_not_strip_quotes;
/* Fall through. */
default:
if (yyres)
yyres[yyn] = *yyp;
yyn++;
break;
case '"':
if (yyres)
yyres[yyn] = '\0';
return yyn;
}
do_not_strip_quotes: ;
}
if (! yyres)
return yystrlen (yystr);
return yystpcpy (yyres, yystr) - yyres;
}
# endif
/* Copy into YYRESULT an error message about the unexpected token
YYCHAR while in state YYSTATE. Return the number of bytes copied,
including the terminating null byte. If YYRESULT is null, do not
copy anything; just return the number of bytes that would be
copied. As a special case, return 0 if an ordinary "syntax error"
message will do. Return YYSIZE_MAXIMUM if overflow occurs during
size calculation. */
static YYSIZE_T
yysyntax_error (char *yyresult, int yystate, int yychar)
{
int yyn = yypact[yystate];
if (! (YYPACT_NINF < yyn && yyn <= YYLAST))
return 0;
else
{
int yytype = YYTRANSLATE (yychar);
YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]);
YYSIZE_T yysize = yysize0;
YYSIZE_T yysize1;
int yysize_overflow = 0;
enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
int yyx;
# if 0
/* This is so xgettext sees the translatable formats that are
constructed on the fly. */
YY_("syntax error, unexpected %s");
YY_("syntax error, unexpected %s, expecting %s");
YY_("syntax error, unexpected %s, expecting %s or %s");
YY_("syntax error, unexpected %s, expecting %s or %s or %s");
YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s");
# endif
char *yyfmt;
char const *yyf;
static char const yyunexpected[] = "syntax error, unexpected %s";
static char const yyexpecting[] = ", expecting %s";
static char const yyor[] = " or %s";
char yyformat[sizeof yyunexpected
+ sizeof yyexpecting - 1
+ ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2)
* (sizeof yyor - 1))];
char const *yyprefix = yyexpecting;
/* Start YYX at -YYN if negative to avoid negative indexes in
YYCHECK. */
int yyxbegin = yyn < 0 ? -yyn : 0;
/* Stay within bounds of both yycheck and yytname. */
int yychecklim = YYLAST - yyn + 1;
int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
int yycount = 1;
yyarg[0] = yytname[yytype];
yyfmt = yystpcpy (yyformat, yyunexpected);
for (yyx = yyxbegin; yyx < yyxend; ++yyx)
if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR)
{
if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
{
yycount = 1;
yysize = yysize0;
yyformat[sizeof yyunexpected - 1] = '\0';
break;
}
yyarg[yycount++] = yytname[yyx];
yysize1 = yysize + yytnamerr (0, yytname[yyx]);
yysize_overflow |= (yysize1 < yysize);
yysize = yysize1;
yyfmt = yystpcpy (yyfmt, yyprefix);
yyprefix = yyor;
}
yyf = YY_(yyformat);
yysize1 = yysize + yystrlen (yyf);
yysize_overflow |= (yysize1 < yysize);
yysize = yysize1;
if (yysize_overflow)
return YYSIZE_MAXIMUM;
if (yyresult)
{
/* Avoid sprintf, as that infringes on the user's name space.
Don't have undefined behavior even if the translation
produced a string with the wrong number of "%s"s. */
char *yyp = yyresult;
int yyi = 0;
while ((*yyp = *yyf) != '\0')
{
if (*yyp == '%' && yyf[1] == 's' && yyi < yycount)
{
yyp += yytnamerr (yyp, yyarg[yyi++]);
yyf += 2;
}
else
{
yyp++;
yyf++;
}
}
}
return yysize;
}
}
#endif /* YYERROR_VERBOSE */
/*-----------------------------------------------.
| Release the memory associated to this symbol. |
`-----------------------------------------------*/
/*ARGSUSED*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep)
#else
static void
yydestruct (yymsg, yytype, yyvaluep)
const char *yymsg;
int yytype;
YYSTYPE *yyvaluep;
#endif
{
YYUSE (yyvaluep);
if (!yymsg)
yymsg = "Deleting";
YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
switch (yytype)
{
default:
break;
}
}
/* Prevent warnings from -Wmissing-prototypes. */
#ifdef YYPARSE_PARAM
#if defined __STDC__ || defined __cplusplus
int yyparse (void *YYPARSE_PARAM);
#else
int yyparse ();
#endif
#else /* ! YYPARSE_PARAM */
#if defined __STDC__ || defined __cplusplus
int yyparse (void);
#else
int yyparse ();
#endif
#endif /* ! YYPARSE_PARAM */
/* The look-ahead symbol. */
int yychar;
/* The semantic value of the look-ahead symbol. */
YYSTYPE yylval;
/* Number of syntax errors so far. */
int yynerrs;
/*----------.
| yyparse. |
`----------*/
#ifdef YYPARSE_PARAM
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
int
yyparse (void *YYPARSE_PARAM)
#else
int
yyparse (YYPARSE_PARAM)
void *YYPARSE_PARAM;
#endif
#else /* ! YYPARSE_PARAM */
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
int
yyparse (void)
#else
int
yyparse ()
#endif
#endif
{
int yystate;
int yyn;
int yyresult;
/* Number of tokens to shift before error messages enabled. */
int yyerrstatus;
/* Look-ahead token as an internal (translated) token number. */
int yytoken = 0;
#if YYERROR_VERBOSE
/* Buffer for error messages, and its allocated size. */
char yymsgbuf[128];
char *yymsg = yymsgbuf;
YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
#endif
/* Three stacks and their tools:
`yyss': related to states,
`yyvs': related to semantic values,
`yyls': related to locations.
Refer to the stacks thru separate pointers, to allow yyoverflow
to reallocate them elsewhere. */
/* The state stack. */
yytype_int16 yyssa[YYINITDEPTH];
yytype_int16 *yyss = yyssa;
yytype_int16 *yyssp;
/* The semantic value stack. */
YYSTYPE yyvsa[YYINITDEPTH];
YYSTYPE *yyvs = yyvsa;
YYSTYPE *yyvsp;
#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N))
YYSIZE_T yystacksize = YYINITDEPTH;
/* The variables used to return semantic value and location from the
action routines. */
YYSTYPE yyval;
/* The number of symbols on the RHS of the reduced rule.
Keep to zero when no symbol should be popped. */
int yylen = 0;
YYDPRINTF ((stderr, "Starting parse\n"));
yystate = 0;
yyerrstatus = 0;
yynerrs = 0;
yychar = YYEMPTY; /* Cause a token to be read. */
/* Initialize stack pointers.
Waste one element of value and location stack
so that they stay on the same level as the state stack.
The wasted elements are never initialized. */
yyssp = yyss;
yyvsp = yyvs;
goto yysetstate;
/*------------------------------------------------------------.
| yynewstate -- Push a new state, which is found in yystate. |
`------------------------------------------------------------*/
yynewstate:
/* In all cases, when you get here, the value and location stacks
have just been pushed. So pushing a state here evens the stacks. */
yyssp++;
yysetstate:
*yyssp = yystate;
if (yyss + yystacksize - 1 <= yyssp)
{
/* Get the current used size of the three stacks, in elements. */
YYSIZE_T yysize = yyssp - yyss + 1;
#ifdef yyoverflow
{
/* Give user a chance to reallocate the stack. Use copies of
these so that the &'s don't force the real ones into
memory. */
YYSTYPE *yyvs1 = yyvs;
yytype_int16 *yyss1 = yyss;
/* Each stack pointer address is followed by the size of the
data in use in that stack, in bytes. This used to be a
conditional around just the two extra args, but that might
be undefined if yyoverflow is a macro. */
yyoverflow (YY_("memory exhausted"),
&yyss1, yysize * sizeof (*yyssp),
&yyvs1, yysize * sizeof (*yyvsp),
&yystacksize);
yyss = yyss1;
yyvs = yyvs1;
}
#else /* no yyoverflow */
# ifndef YYSTACK_RELOCATE
goto yyexhaustedlab;
# else
/* Extend the stack our own way. */
if (YYMAXDEPTH <= yystacksize)
goto yyexhaustedlab;
yystacksize *= 2;
if (YYMAXDEPTH < yystacksize)
yystacksize = YYMAXDEPTH;
{
yytype_int16 *yyss1 = yyss;
union yyalloc *yyptr =
(union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
if (! yyptr)
goto yyexhaustedlab;
YYSTACK_RELOCATE (yyss);
YYSTACK_RELOCATE (yyvs);
# undef YYSTACK_RELOCATE
if (yyss1 != yyssa)
YYSTACK_FREE (yyss1);
}
# endif
#endif /* no yyoverflow */
yyssp = yyss + yysize - 1;
yyvsp = yyvs + yysize - 1;
YYDPRINTF ((stderr, "Stack size increased to %lu\n",
(unsigned long int) yystacksize));
if (yyss + yystacksize - 1 <= yyssp)
YYABORT;
}
YYDPRINTF ((stderr, "Entering state %d\n", yystate));
goto yybackup;
/*-----------.
| yybackup. |
`-----------*/
yybackup:
/* Do appropriate processing given the current state. Read a
look-ahead token if we need one and don't already have one. */
/* First try to decide what to do without reference to look-ahead token. */
yyn = yypact[yystate];
if (yyn == YYPACT_NINF)
goto yydefault;
/* Not known => get a look-ahead token if don't already have one. */
/* YYCHAR is either YYEMPTY or YYEOF or a valid look-ahead symbol. */
if (yychar == YYEMPTY)
{
YYDPRINTF ((stderr, "Reading a token: "));
yychar = YYLEX;
}
if (yychar <= YYEOF)
{
yychar = yytoken = YYEOF;
YYDPRINTF ((stderr, "Now at end of input.\n"));
}
else
{
yytoken = YYTRANSLATE (yychar);
YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
}
/* If the proper action on seeing token YYTOKEN is to reduce or to
detect an error, take that action. */
yyn += yytoken;
if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
goto yydefault;
yyn = yytable[yyn];
if (yyn <= 0)
{
if (yyn == 0 || yyn == YYTABLE_NINF)
goto yyerrlab;
yyn = -yyn;
goto yyreduce;
}
if (yyn == YYFINAL)
YYACCEPT;
/* Count tokens shifted since error; after three, turn off error
status. */
if (yyerrstatus)
yyerrstatus--;
/* Shift the look-ahead token. */
YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
/* Discard the shifted token unless it is eof. */
if (yychar != YYEOF)
yychar = YYEMPTY;
yystate = yyn;
*++yyvsp = yylval;
goto yynewstate;
/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state. |
`-----------------------------------------------------------*/
yydefault:
yyn = yydefact[yystate];
if (yyn == 0)
goto yyerrlab;
goto yyreduce;
/*-----------------------------.
| yyreduce -- Do a reduction. |
`-----------------------------*/
yyreduce:
/* yyn is the number of a rule to reduce with. */
yylen = yyr2[yyn];
/* If YYLEN is nonzero, implement the default value of the action:
`$$ = $1'.
Otherwise, the following line sets YYVAL to garbage.
This behavior is undocumented and Bison
users should not rely upon it. Assigning to YYVAL
unconditionally makes the parser a bit smaller, and it avoids a
GCC warning that YYVAL may be used uninitialized. */
yyval = yyvsp[1-yylen];
YY_REDUCE_PRINT (yyn);
switch (yyn)
{
case 2:
#line 54 "sysinfo.y"
{
switch (writecode)
{
case 'i':
printf("#ifdef SYSROFF_SWAP_IN\n");
break;
case 'p':
printf("#ifdef SYSROFF_p\n");
break;
case 'd':
break;
case 'g':
printf("#ifdef SYSROFF_SWAP_OUT\n");
break;
case 'c':
printf("#ifdef SYSROFF_PRINT\n");
printf("#include <stdio.h>\n");
printf("#include <stdlib.h>\n");
printf("#include <ansidecl.h>\n");
break;
}
}
break;
case 3:
#line 76 "sysinfo.y"
{
switch (writecode) {
case 'i':
case 'p':
case 'g':
case 'c':
printf("#endif\n");
break;
case 'd':
break;
}
}
break;
case 6:
#line 98 "sysinfo.y"
{
it = (yyvsp[(2) - (3)].s); code = (yyvsp[(3) - (3)].i);
switch (writecode)
{
case 'd':
printf("\n\n\n#define IT_%s_CODE 0x%x\n", it,code);
printf("struct IT_%s;\n", it);
printf("extern void sysroff_swap_%s_in (struct IT_%s *);\n",
(yyvsp[(2) - (3)].s), it);
printf("extern void sysroff_swap_%s_out (FILE *, struct IT_%s *);\n",
(yyvsp[(2) - (3)].s), it);
printf("extern void sysroff_print_%s_out (struct IT_%s *);\n",
(yyvsp[(2) - (3)].s), it);
printf("struct IT_%s { \n", it);
break;
case 'i':
printf("void sysroff_swap_%s_in (struct IT_%s * ptr)\n",(yyvsp[(2) - (3)].s),it);
printf("{\n");
printf("\tunsigned char raw[255];\n");
printf("\tint idx = 0;\n");
printf("\tint size;\n");
printf("\tmemset(raw,0,255);\n");
printf("\tmemset(ptr,0,sizeof(*ptr));\n");
printf("\tsize = fillup(raw);\n");
break;
case 'g':
printf("void sysroff_swap_%s_out (FILE * ffile, struct IT_%s * ptr)\n",(yyvsp[(2) - (3)].s),it);
printf("{\n");
printf("\tunsigned char raw[255];\n");
printf("\tint idx = 16;\n");
printf("\tmemset (raw, 0, 255);\n");
printf("\tcode = IT_%s_CODE;\n", it);
break;
case 'o':
printf("void sysroff_swap_%s_out (bfd * abfd, struct IT_%s * ptr)\n",(yyvsp[(2) - (3)].s), it);
printf("{\n");
printf("\tint idx = 0;\n");
break;
case 'c':
printf("void sysroff_print_%s_out (struct IT_%s *ptr)\n",(yyvsp[(2) - (3)].s),it);
printf("{\n");
printf("itheader(\"%s\", IT_%s_CODE);\n",(yyvsp[(2) - (3)].s),(yyvsp[(2) - (3)].s));
break;
case 't':
break;
}
}
break;
case 7:
#line 149 "sysinfo.y"
{
switch (writecode) {
case 'd':
printf("};\n");
break;
case 'g':
printf("\tchecksum(ffile,raw, idx, IT_%s_CODE);\n", it);
case 'i':
case 'o':
case 'c':
printf("}\n");
}
}
break;
case 12:
#line 176 "sysinfo.y"
{
rdepth++;
switch (writecode)
{
case 'c':
if (rdepth==1)
printf("\tprintf(\"repeat %%d\\n\", %s);\n",(yyvsp[(3) - (3)].s));
if (rdepth==2)
printf("\tprintf(\"repeat %%d\\n\", %s[n]);\n",(yyvsp[(3) - (3)].s));
case 'i':
case 'g':
case 'o':
if (rdepth==1)
{
printf("\t{ int n; for (n = 0; n < %s; n++) {\n", (yyvsp[(3) - (3)].s));
}
if (rdepth == 2) {
printf("\t{ int m; for (m = 0; m < %s[n]; m++) {\n", (yyvsp[(3) - (3)].s));
}
break;
}
oldrepeat = repeat;
repeat = (yyvsp[(3) - (3)].s);
}
break;
case 13:
#line 206 "sysinfo.y"
{
repeat = oldrepeat;
oldrepeat =0;
rdepth--;
switch (writecode)
{
case 'i':
case 'g':
case 'o':
case 'c':
printf("\t}}\n");
}
}
break;
case 14:
#line 223 "sysinfo.y"
{
switch (writecode)
{
case 'i':
case 'g':
case 'o':
case 'c':
printf("\tif (%s) {\n", (yyvsp[(3) - (3)].s));
break;
}
}
break;
case 15:
#line 236 "sysinfo.y"
{
switch (writecode)
{
case 'i':
case 'g':
case 'o':
case 'c':
printf("\t}\n");
}
}
break;
case 16:
#line 250 "sysinfo.y"
{name = (yyvsp[(7) - (7)].s); }
break;
case 17:
#line 252 "sysinfo.y"
{
char *desc = (yyvsp[(2) - (10)].s);
char *type = (yyvsp[(4) - (10)].s);
int size = (yyvsp[(5) - (10)].i);
char *id = (yyvsp[(7) - (10)].s);
char *p = names[rdepth];
char *ptr = pnames[rdepth];
switch (writecode)
{
case 'g':
if (size % 8)
{
printf("\twriteBITS(ptr->%s%s,raw,&idx,%d);\n",
id,
names[rdepth], size);
}
else {
printf("\twrite%s(ptr->%s%s,raw,&idx,%d,ffile);\n",
type,
id,
names[rdepth],size/8);
}
break;
case 'i':
{
if (rdepth >= 1)
{
printf("if (!ptr->%s) ptr->%s = (%s*)xcalloc(%s, sizeof(ptr->%s[0]));\n",
id,
id,
type,
repeat,
id);
}
if (rdepth == 2)
{
printf("if (!ptr->%s[n]) ptr->%s[n] = (%s**)xcalloc(%s[n], sizeof(ptr->%s[n][0]));\n",
id,
id,
type,
repeat,
id);
}
}
if (size % 8)
{
printf("\tptr->%s%s = getBITS(raw,&idx, %d,size);\n",
id,
names[rdepth],
size);
}
else {
printf("\tptr->%s%s = get%s(raw,&idx, %d,size);\n",
id,
names[rdepth],
type,
size/8);
}
break;
case 'o':
printf("\tput%s(raw,%d,%d,&idx,ptr->%s%s);\n", type,size/8,size%8,id,names[rdepth]);
break;
case 'd':
if (repeat)
printf("\t/* repeat %s */\n", repeat);
if (type[0] == 'I') {
printf("\tint %s%s; \t/* %s */\n",ptr,id, desc);
}
else if (type[0] =='C') {
printf("\tchar %s*%s;\t /* %s */\n",ptr,id, desc);
}
else {
printf("\tbarray %s%s;\t /* %s */\n",ptr,id, desc);
}
break;
case 'c':
printf("tabout();\n");
printf("\tprintf(\"/*%-30s*/ ptr->%s = \");\n", desc, id);
if (type[0] == 'I')
printf("\tprintf(\"%%d\\n\",ptr->%s%s);\n", id,p);
else if (type[0] == 'C')
printf("\tprintf(\"%%s\\n\",ptr->%s%s);\n", id,p);
else if (type[0] == 'B')
{
printf("\tpbarray(&ptr->%s%s);\n", id,p);
}
else abort();
break;
}
}
break;
case 18:
#line 357 "sysinfo.y"
{ (yyval.s) = (yyvsp[(1) - (1)].s); }
break;
case 19:
#line 358 "sysinfo.y"
{ (yyval.s) = "INT";}
break;
case 20:
#line 363 "sysinfo.y"
{ (yyval.s) = (yyvsp[(2) - (3)].s); }
break;
case 21:
#line 368 "sysinfo.y"
{ (yyval.i) = (yyvsp[(1) - (2)].i) * (yyvsp[(2) - (2)].i); }
break;
case 22:
#line 373 "sysinfo.y"
{ (yyval.s) = (yyvsp[(2) - (3)].s); }
break;
case 23:
#line 374 "sysinfo.y"
{ (yyval.s) = "dummy";}
break;
case 27:
#line 382 "sysinfo.y"
{
switch (writecode)
{
case 'd':
printf("#define %s %s\n", (yyvsp[(3) - (5)].s),(yyvsp[(4) - (5)].s));
break;
case 'c':
printf("if (ptr->%s%s == %s) { tabout(); printf(\"%s\\n\");}\n", name, names[rdepth],(yyvsp[(4) - (5)].s),(yyvsp[(3) - (5)].s));
}
}
break;
/* Line 1267 of yacc.c. */
#line 1715 "sysinfo.c"
default: break;
}
YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
*++yyvsp = yyval;
/* Now `shift' the result of the reduction. Determine what state
that goes to, based on the state we popped back to and the rule
number reduced by. */
yyn = yyr1[yyn];
yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
yystate = yytable[yystate];
else
yystate = yydefgoto[yyn - YYNTOKENS];
goto yynewstate;
/*------------------------------------.
| yyerrlab -- here on detecting error |
`------------------------------------*/
yyerrlab:
/* If not already recovering from an error, report this error. */
if (!yyerrstatus)
{
++yynerrs;
#if ! YYERROR_VERBOSE
yyerror (YY_("syntax error"));
#else
{
YYSIZE_T yysize = yysyntax_error (0, yystate, yychar);
if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM)
{
YYSIZE_T yyalloc = 2 * yysize;
if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM))
yyalloc = YYSTACK_ALLOC_MAXIMUM;
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
yymsg = (char *) YYSTACK_ALLOC (yyalloc);
if (yymsg)
yymsg_alloc = yyalloc;
else
{
yymsg = yymsgbuf;
yymsg_alloc = sizeof yymsgbuf;
}
}
if (0 < yysize && yysize <= yymsg_alloc)
{
(void) yysyntax_error (yymsg, yystate, yychar);
yyerror (yymsg);
}
else
{
yyerror (YY_("syntax error"));
if (yysize != 0)
goto yyexhaustedlab;
}
}
#endif
}
if (yyerrstatus == 3)
{
/* If just tried and failed to reuse look-ahead token after an
error, discard it. */
if (yychar <= YYEOF)
{
/* Return failure if at end of input. */
if (yychar == YYEOF)
YYABORT;
}
else
{
yydestruct ("Error: discarding",
yytoken, &yylval);
yychar = YYEMPTY;
}
}
/* Else will try to reuse look-ahead token after shifting the error
token. */
goto yyerrlab1;
/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR. |
`---------------------------------------------------*/
yyerrorlab:
/* Pacify compilers like GCC when the user code never invokes
YYERROR and the label yyerrorlab therefore never appears in user
code. */
if (/*CONSTCOND*/ 0)
goto yyerrorlab;
/* Do not reclaim the symbols of the rule which action triggered
this YYERROR. */
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
yystate = *yyssp;
goto yyerrlab1;
/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR. |
`-------------------------------------------------------------*/
yyerrlab1:
yyerrstatus = 3; /* Each real token shifted decrements this. */
for (;;)
{
yyn = yypact[yystate];
if (yyn != YYPACT_NINF)
{
yyn += YYTERROR;
if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
{
yyn = yytable[yyn];
if (0 < yyn)
break;
}
}
/* Pop the current state because it cannot handle the error token. */
if (yyssp == yyss)
YYABORT;
yydestruct ("Error: popping",
yystos[yystate], yyvsp);
YYPOPSTACK (1);
yystate = *yyssp;
YY_STACK_PRINT (yyss, yyssp);
}
if (yyn == YYFINAL)
YYACCEPT;
*++yyvsp = yylval;
/* Shift the error token. */
YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
yystate = yyn;
goto yynewstate;
/*-------------------------------------.
| yyacceptlab -- YYACCEPT comes here. |
`-------------------------------------*/
yyacceptlab:
yyresult = 0;
goto yyreturn;
/*-----------------------------------.
| yyabortlab -- YYABORT comes here. |
`-----------------------------------*/
yyabortlab:
yyresult = 1;
goto yyreturn;
#ifndef yyoverflow
/*-------------------------------------------------.
| yyexhaustedlab -- memory exhaustion comes here. |
`-------------------------------------------------*/
yyexhaustedlab:
yyerror (YY_("memory exhausted"));
yyresult = 2;
/* Fall through. */
#endif
yyreturn:
if (yychar != YYEOF && yychar != YYEMPTY)
yydestruct ("Cleanup: discarding lookahead",
yytoken, &yylval);
/* Do not reclaim the symbols of the rule which action triggered
this YYABORT or YYACCEPT. */
YYPOPSTACK (yylen);
YY_STACK_PRINT (yyss, yyssp);
while (yyssp != yyss)
{
yydestruct ("Cleanup: popping",
yystos[*yyssp], yyvsp);
YYPOPSTACK (1);
}
#ifndef yyoverflow
if (yyss != yyssa)
YYSTACK_FREE (yyss);
#endif
#if YYERROR_VERBOSE
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
#endif
/* Make sure YYID is used. */
return YYID (yyresult);
}
#line 397 "sysinfo.y"
/* four modes
-d write structure definitions for sysroff in host format
-i write functions to swap into sysroff format in
-o write functions to swap into sysroff format out
-c write code to print info in human form */
int yydebug;
int
main (int ac, char **av)
{
yydebug=0;
if (ac > 1)
writecode = av[1][1];
if (writecode == 'd')
{
printf("typedef struct { unsigned char *data; int len; } barray; \n");
printf("typedef int INT;\n");
printf("typedef char * CHARS;\n");
}
yyparse();
return 0;
}
static int
yyerror (char *s)
{
fprintf(stderr, "%s\n" , s);
return 0;
}
|
the_stack_data/211080671.c | /***
* This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License.
* When used, please cite the following article(s): V. Mrazek, L. Sekanina, Z. Vasicek "Libraries of Approximate Circuits: Automated Design and Application in CNN Accelerators" IEEE Journal on Emerging and Selected Topics in Circuits and Systems, Vol 10, No 4, 2020
* This file contains a circuit from a sub-set of pareto optimal circuits with respect to the pwr and ep parameters
***/
// MAE% = 0.015 %
// MAE = 20
// WCE% = 0.049 %
// WCE = 64
// WCRE% = 66.67 %
// EP% = 49.22 %
// MRE% = 0.041 %
// MSE = 876
// PDK45_PWR = 0.062 mW
// PDK45_AREA = 136.1 um2
// PDK45_DELAY = 0.79 ns
#include <stdint.h>
#include <stdlib.h>
uint64_t add16u_1MB(uint64_t a, uint64_t b) {
int wa[16];
int wb[16];
uint64_t y = 0;
wa[0] = (a >> 0) & 0x01;
wb[0] = (b >> 0) & 0x01;
wa[1] = (a >> 1) & 0x01;
wb[1] = (b >> 1) & 0x01;
wa[2] = (a >> 2) & 0x01;
wb[2] = (b >> 2) & 0x01;
wa[3] = (a >> 3) & 0x01;
wb[3] = (b >> 3) & 0x01;
wa[4] = (a >> 4) & 0x01;
wb[4] = (b >> 4) & 0x01;
wa[5] = (a >> 5) & 0x01;
wb[5] = (b >> 5) & 0x01;
wa[6] = (a >> 6) & 0x01;
wb[6] = (b >> 6) & 0x01;
wa[7] = (a >> 7) & 0x01;
wb[7] = (b >> 7) & 0x01;
wa[8] = (a >> 8) & 0x01;
wb[8] = (b >> 8) & 0x01;
wa[9] = (a >> 9) & 0x01;
wb[9] = (b >> 9) & 0x01;
wa[10] = (a >> 10) & 0x01;
wb[10] = (b >> 10) & 0x01;
wa[11] = (a >> 11) & 0x01;
wb[11] = (b >> 11) & 0x01;
wa[12] = (a >> 12) & 0x01;
wb[12] = (b >> 12) & 0x01;
wa[13] = (a >> 13) & 0x01;
wb[13] = (b >> 13) & 0x01;
wa[14] = (a >> 14) & 0x01;
wb[14] = (b >> 14) & 0x01;
wa[15] = (a >> 15) & 0x01;
wb[15] = (b >> 15) & 0x01;
int sig_32 = wa[0] ^ wb[0];
int sig_33 = wa[0] & wb[0];
int sig_34 = wa[1] ^ wb[1];
int sig_35 = wa[1] & wb[1];
int sig_36 = sig_34 & sig_33;
int sig_37 = sig_34 ^ sig_33;
int sig_38 = sig_35 | sig_36;
int sig_39 = wa[2] ^ wb[2];
int sig_40 = wa[2] & wb[2];
int sig_41 = sig_39 & sig_38;
int sig_42 = sig_39 ^ sig_38;
int sig_43 = sig_40 | sig_41;
int sig_44 = wa[3] ^ wb[3];
int sig_45 = wa[3] & wb[3];
int sig_46 = sig_44 & sig_43;
int sig_47 = sig_44 ^ sig_43;
int sig_48 = sig_45 | sig_46;
int sig_49 = wa[4] ^ wb[4];
int sig_50 = wa[4] & wb[4];
int sig_51 = sig_49 & sig_48;
int sig_52 = sig_49 ^ sig_48;
int sig_53 = sig_50 | sig_51;
int sig_54 = wa[5] | wb[5];
int sig_57 = sig_54 | sig_53;
int sig_59 = wa[6] ^ wb[6];
int sig_60 = wa[6] & wb[6];
int sig_63 = sig_60;
int sig_64 = wa[7] ^ wb[7];
int sig_65 = wa[7] & wb[7];
int sig_66 = sig_64 & sig_63;
int sig_67 = sig_64 ^ sig_63;
int sig_68 = sig_65 | sig_66;
int sig_69 = wa[8] ^ wb[8];
int sig_70 = wa[8] & wb[8];
int sig_71 = sig_69 & sig_68;
int sig_72 = sig_69 ^ sig_68;
int sig_73 = sig_70 | sig_71;
int sig_74 = wa[9] ^ wb[9];
int sig_75 = wa[9] & wb[9];
int sig_76 = sig_74 & sig_73;
int sig_77 = sig_74 ^ sig_73;
int sig_78 = sig_75 | sig_76;
int sig_79 = wa[10] ^ wb[10];
int sig_80 = wa[10] & wb[10];
int sig_81 = sig_79 & sig_78;
int sig_82 = sig_79 ^ sig_78;
int sig_83 = sig_80 | sig_81;
int sig_84 = wa[11] ^ wb[11];
int sig_85 = wa[11] & wb[11];
int sig_86 = sig_84 & sig_83;
int sig_87 = sig_84 ^ sig_83;
int sig_88 = sig_85 | sig_86;
int sig_89 = wa[12] ^ wb[12];
int sig_90 = wa[12] & wb[12];
int sig_91 = sig_89 & sig_88;
int sig_92 = sig_89 ^ sig_88;
int sig_93 = sig_90 | sig_91;
int sig_94 = wa[13] ^ wb[13];
int sig_95 = wa[13] & wb[13];
int sig_96 = sig_94 & sig_93;
int sig_97 = sig_94 ^ sig_93;
int sig_98 = sig_95 | sig_96;
int sig_99 = wa[14] ^ wb[14];
int sig_100 = wa[14] & wb[14];
int sig_101 = sig_99 & sig_98;
int sig_102 = sig_99 ^ sig_98;
int sig_103 = sig_100 | sig_101;
int sig_104 = wa[15] ^ wb[15];
int sig_105 = wa[15] & wb[15];
int sig_106 = sig_104 & sig_103;
int sig_107 = sig_104 ^ sig_103;
int sig_108 = sig_105 | sig_106;
y |= (sig_32 & 0x01) << 0; // default output
y |= (sig_37 & 0x01) << 1; // default output
y |= (sig_42 & 0x01) << 2; // default output
y |= (sig_47 & 0x01) << 3; // default output
y |= (sig_52 & 0x01) << 4; // default output
y |= (sig_57 & 0x01) << 5; // default output
y |= (sig_59 & 0x01) << 6; // default output
y |= (sig_67 & 0x01) << 7; // default output
y |= (sig_72 & 0x01) << 8; // default output
y |= (sig_77 & 0x01) << 9; // default output
y |= (sig_82 & 0x01) << 10; // default output
y |= (sig_87 & 0x01) << 11; // default output
y |= (sig_92 & 0x01) << 12; // default output
y |= (sig_97 & 0x01) << 13; // default output
y |= (sig_102 & 0x01) << 14; // default output
y |= (sig_107 & 0x01) << 15; // default output
y |= (sig_108 & 0x01) << 16; // default output
return y;
}
|
the_stack_data/122015125.c | /******************************************************************************
* Copyright (c) 2019 - 2020 Xilinx, Inc. All rights reserved.
* SPDX-License-Identifier: MIT
******************************************************************************/
#ifndef __linux__
#include "xstatus.h"
#include "xparameters.h"
#include "xmpegtsmux.h"
extern XMpegtsmux_Config XMpegtsmux_ConfigTable[];
XMpegtsmux_Config *XMpegtsmux_LookupConfig(u16 DeviceId) {
XMpegtsmux_Config *ConfigPtr = NULL;
int Index;
for (Index = 0; Index < XPAR_XMPEGTSMUX_NUM_INSTANCES; Index++) {
if (XMpegtsmux_ConfigTable[Index].DeviceId == DeviceId) {
ConfigPtr = &XMpegtsmux_ConfigTable[Index];
break;
}
}
return ConfigPtr;
}
int XMpegtsmux_Initialize(XMpegtsmux *InstancePtr, u16 DeviceId) {
XMpegtsmux_Config *ConfigPtr;
Xil_AssertNonvoid(InstancePtr != NULL);
ConfigPtr = XMpegtsmux_LookupConfig(DeviceId);
if (ConfigPtr == NULL) {
InstancePtr->IsReady = 0;
return (XST_DEVICE_NOT_FOUND);
}
return XMpegtsmux_CfgInitialize(InstancePtr, ConfigPtr);
}
#endif
|
the_stack_data/509032.c | int irbit1(unsigned long *iseed)
{
unsigned long newbit;
newbit = (*iseed >> 17) & 1
^ (*iseed >> 4) & 1
^ (*iseed >> 1) & 1
^ (*iseed & 1);
*iseed=(*iseed << 1) | newbit;
return (int) newbit;
}
|
the_stack_data/115766507.c | #include <stdio.h>
int isArmstrongNumber(int n);
void main()
{
// Variable declaration
int n;
// Read data from user
printf("Enter any number: ");
scanf("%d", &n);
// Print the result
if (isArmstrongNumber(n))
printf("%d is ARMSTRONG Number", n);
else
printf("%d is Not ARMSTRONG Number", n);
}
int isArmstrongNumber(int n)
{
int rem, m, result = 0;
m = n;
while (m > 10) {
rem = m % 10;
m = m / 10;
result = result + rem*rem*rem;
}
if (result == n)
return 1;
else
return 0;
}
|
the_stack_data/640215.c | #include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>
void part_one ()
{
int limit;
scanf ( "%d", &limit );
int previous = -1, next = -1;
int ans = 0;
scanf ( "%d", &previous );
for ( int i = 1 ; i < limit ; ++i ) {
scanf ( "%d", &next );
if ( next > previous )
++ans;
previous = next;
}
printf ( "Part One Ans is : %d\n", ans );
}
void part_two ()
{
int limit;
scanf ( "%d", &limit );
int prev_a, prev_b, prev_c, next;
int ans = 0;
scanf ( "%d%d%d", &prev_a, &prev_b, &prev_c );
for ( int i = 3 ; i < limit ; ++i ) {
scanf ( "%d", &next );
int up = prev_a + prev_b + prev_c;
int down = prev_b + prev_c + next;
if ( down > up ) ++ans;
prev_a = prev_b;
prev_b = prev_c;
prev_c = next;
}
printf ( "Part Two Ans is : %d\n", ans );
}
int main ()
{
part_one ();
part_two ();
return 0;
}
|
the_stack_data/168258.c | /* Taxonomy Classification: 0000000000001500000000 */
/*
* WRITE/READ 0 write
* WHICH BOUND 0 upper
* DATA TYPE 0 char
* MEMORY LOCATION 0 stack
* SCOPE 0 same
* CONTAINER 0 no
* POINTER 0 no
* INDEX COMPLEXITY 0 constant
* ADDRESS COMPLEXITY 0 constant
* LENGTH COMPLEXITY 0 N/A
* ADDRESS ALIAS 0 none
* INDEX ALIAS 0 none
* LOCAL CONTROL FLOW 1 if
* SECONDARY CONTROL FLOW 5 longjmp
* LOOP STRUCTURE 0 no
* LOOP COMPLEXITY 0 N/A
* ASYNCHRONY 0 no
* TAINT 0 no
* RUNTIME ENV. DEPENDENCE 0 no
* MAGNITUDE 0 no overflow
* CONTINUOUS/DISCRETE 0 discrete
* SIGNEDNESS 0 no
*/
/*
Copyright 2005 Massachusetts Institute of Technology
All rights reserved.
Redistribution and use of 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 set of conditions and the disclaimer below.
- Redistributions in binary form must reproduce the copyright notice, this
set of conditions, and the disclaimer below in the documentation and/or
other materials provided with the distribution.
- Neither the name of the Massachusetts Institute of Technology 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".
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 <setjmp.h>
int main(int argc, char *argv[])
{
jmp_buf env;
int flag;
char buf[10];
if (setjmp(env) != 0)
{
return 0;
}
flag = 1;
if (flag)
{
/* OK */
buf[9] = 'A';
}
longjmp(env, 1);
return 0;
}
|
the_stack_data/187642588.c | #include <stdio.h>
#include <stdlib.h>
struct node //ok
{
int value;
struct node *parent;
struct node *left;
struct node *right;
};
struct nodelist //ok
{
struct node* adress;
struct nodelist *next;
};
struct list //ok
{
struct nodelist *head;
struct nodelist *tail;
};
void initlist(struct list* l) //ok
{
l->head=NULL;
l->tail=NULL;
}
void clearlist(struct list* l) //ok
{
struct nodelist* tmp_1;
struct nodelist* tmp_2;
tmp_1=l->head;
while (tmp_1->next!=NULL)
{
tmp_2=tmp_1;
tmp_1=tmp_1->next;
free(tmp_2);
}
free(tmp_1);
initlist(l);
}
int isEmpty(struct list* l) //ok
{
if (l->head==NULL) return 0;
else return 1;
}
int push_back(struct list* l, struct node* val) //ok
{
struct nodelist* new_node;
new_node=(struct nodelist*)malloc(sizeof(struct nodelist));
new_node->adress = val;
new_node->next = NULL;
if (l->head==NULL) l->head=new_node;
else if (l->head->next==NULL) l->head->next = new_node;
else l->tail->next = new_node;
l->tail=new_node;
return 0;
}
void printlist(struct list* l) //ok
{
if (isEmpty(l)==1)
{
struct nodelist* tmp;
tmp=l->head;
while (tmp->next!=NULL)
{
if (tmp->adress == NULL) printf("_ ");
else printf("%d ", tmp->adress->value);
tmp = tmp->next;
}
if (tmp->adress == NULL) printf("_\n");
else
printf("%d\n", l->tail->adress->value);
}
}
int noempty(struct list* l) //?ok
{
int tmp=0;
if (isEmpty(l)==0) return 0;
struct nodelist* n;
n=l->head;
while (n!=NULL)
{
if (n->adress!=NULL) tmp=1;
n=n->next;
}
return tmp;
}
//start treeeeeeeeee
struct tree
{
struct node *root;
int number;
};
void init(struct tree* t)
{
t->number=0;
t->root=NULL;
}
void clear(struct tree *t) //ok?or?not
{
struct list tmp1, tmp2;
struct nodelist *node_tmp;
initlist(&tmp1);
initlist(&tmp2);
push_back(&tmp1, t->root);
while(noempty(&tmp1)|| noempty(&tmp2))
{
if (isEmpty(&tmp2)==0)
{
node_tmp=tmp1.head;
while(node_tmp!=NULL)
{
if (node_tmp->adress==NULL)
{
push_back(&tmp2, NULL);
push_back(&tmp2, NULL);
}
else
{
push_back(&tmp2, node_tmp->adress->left);
push_back(&tmp2, node_tmp->adress->right);
}
free(node_tmp->adress);
node_tmp=node_tmp->next;
}
clearlist(&tmp1);
}
else
{
node_tmp=tmp2.head;
while(node_tmp!=NULL)
{
if (node_tmp->adress==NULL)
{
push_back(&tmp1, NULL);
push_back(&tmp1, NULL);
}
else
{
push_back(&tmp1, node_tmp->adress->left);
push_back(&tmp1, node_tmp->adress->right);
}
free(node_tmp->adress);
node_tmp=node_tmp->next;
}
clearlist(&tmp2);
}
}
init(t);
}
int find(struct tree* t, int val, struct node** n) //ok
{
struct node* node_tmp;
node_tmp=t->root;
if (node_tmp==NULL) return 1;
while((node_tmp!=NULL))
{
if (node_tmp->value==val)
{
(*n)=node_tmp;
return 0;
}
if (node_tmp->value>val)
{
if (node_tmp->left==NULL) return 1;
else node_tmp=node_tmp->left;
}
else
{
if (node_tmp->right==NULL) return 1;
else node_tmp=node_tmp->right;
}
}
return 1;
}
int insert(struct tree* t, int val) //ooooook
{
struct node* new_node;
if (find(t, val, &new_node)==0) return 1;
new_node=(struct node*)malloc(sizeof(struct node));
if (new_node==NULL) return 2;
t->number++;
new_node->left=NULL;
new_node->right=NULL;
new_node->value=val;
if (NULL==t->root)
{
new_node->parent=NULL;
t->root=new_node;
}
else
{
struct node* tmp;
int InsertOK=0;
tmp=t->root;
while (0==InsertOK)
{
if (val<tmp->value)
{
if (tmp->left!=NULL) tmp=tmp->left;
else
{
new_node->parent=tmp;
tmp->left=new_node;
InsertOK=1;
}
}
else
{
if (tmp->right!=NULL) tmp=tmp->right;
else
{
new_node->parent=tmp;
tmp->right=new_node;
InsertOK=1;
}
}
}
}
return 0;
}
int removeNode(struct tree* t, int val)
{
struct node* tmp;
if (find(t, val, &tmp)==1) return 1;
if ((tmp->left==NULL)&&(tmp->right==NULL))
{
if (tmp->parent==NULL)
{
clear(t);
return 0;
}
if (tmp->parent->left==tmp) tmp->parent->left=NULL;
else tmp->parent->right=NULL;
free(tmp);
t->number--;
return 0;
}
if ((tmp->left==NULL) && (tmp->right!=NULL))
{
if (tmp->parent==NULL)
{
t->root=tmp->right;
t->root->parent=NULL;
free(tmp);
t->number--;
return 0;
}
if (tmp->parent->left==tmp) tmp->parent->left=tmp->right;
else tmp->parent->right=tmp->right;
t->number--;
free(tmp);
return 0;
}
if ((tmp->right==NULL) && (tmp->left!=NULL))
{
if (tmp->parent==NULL)
{
t->root=tmp->left;
t->root->parent=NULL;
t->number--;
free(tmp);
return 0;
}
if (tmp->parent->left==tmp) tmp->parent->left=tmp->left;
else tmp->parent->right=tmp->left;
t->number--;
free(tmp);
return 0;
}
if ((tmp->left!=NULL) && (tmp->right!=NULL))
{
struct node* min;
min=tmp->right;
while(min->left!=NULL)
min=min->left;
tmp->value=min->value;
if (min->right!=NULL)
{
if (min->parent->left==min) min->parent->left=min->right;
else min->parent->right=min->right;
min->right->parent=min->parent;
}
else
{
if (min->parent->left==min) min->parent->left=NULL;
else min->parent->right=NULL;
}
t->number--;
free(min);
return 0;
}
}
int removeMin(struct node* n, struct tree* t)
{
int MinV;
while (n->left!=NULL)
n=n->left;
MinV=n->value;
n->parent->left=NULL;
if (n->right!=NULL)
{
n->parent->left=n->right;
n->right->parent=n->parent;
}
t->number--;
free(n);
return MinV;
}
int rotateRight(struct node *n, struct tree *t)
{
struct node *tmp;
if (n->left==NULL) return 1;
if (n->parent==NULL)
{
t->root=n->left;
n->left->parent=NULL;
}
else
{
if (n->parent->left==n) n->parent->left=n->left;
else n->parent->right=n->left;
n->left->parent=n->parent;
}
n->parent=n->left;
tmp=n->parent->right;
n->parent->right=n;
n->left=tmp;
return 0;
}
int rotateLeft(struct node *n, struct tree *t)
{
struct node *tmp;
if (n->right==NULL) return 1;
if (n->parent==NULL)
{
t->root=n->right;
n->right->parent=NULL;
}
else
{
if (n->parent->left==n) n->parent->left=n->right;
else n->parent->right=n->right;
n->right->parent=n->parent;
}
n->parent=n->right;
tmp=n->parent->left;
n->parent->left=n;
n->right=tmp;
return 0;
}
void print(struct node* n)
{
if (n==NULL)
{
printf("-\n");
return;
}
struct list tmp1, tmp2;
struct nodelist *node_tmp;
initlist(&tmp1);
initlist(&tmp2);
push_back(&tmp1, n);
while(noempty(&tmp1)|| noempty(&tmp2))
{
if (isEmpty(&tmp2)==0)
{
printlist(&tmp1);
node_tmp=tmp1.head;
while(node_tmp!=NULL)
{
if (node_tmp->adress==NULL)
{
push_back(&tmp2, NULL);
push_back(&tmp2, NULL);
}
else
{
push_back(&tmp2, node_tmp->adress->left);
push_back(&tmp2, node_tmp->adress->right);
}
node_tmp=node_tmp->next;
}
clearlist(&tmp1);
}
else
{
printlist(&tmp2);
node_tmp=tmp2.head;
while(node_tmp!=NULL)
{
if (node_tmp->adress==NULL)
{
push_back(&tmp1, NULL);
push_back(&tmp1, NULL);
}
else
{
push_back(&tmp1, node_tmp->adress->left);
push_back(&tmp1, node_tmp->adress->right);
}
node_tmp=node_tmp->next;
}
clearlist(&tmp2);
}
}
}
void printTree(struct tree *t)
{
print(t->root);
}
int main()
{
struct tree ApplesTree;
struct node* b;
int a1, a2, a3, a4;
init(&ApplesTree);
scanf("%d %d %d %d", &a1, &a2, &a3, &a4);
insert(&ApplesTree, a1);
insert(&ApplesTree, a2);
insert(&ApplesTree, a3);
insert(&ApplesTree, a4);
printTree(&ApplesTree);
scanf("%d %d %d", &a1, &a2, &a3);
insert(&ApplesTree, a1);
insert(&ApplesTree, a2);
insert(&ApplesTree, a3);
printTree(&ApplesTree);
scanf("%d", &a1);
a2=find(&ApplesTree, a1, &b);
if (a2==1) printf("_\n");
else
{
if (b->parent!=NULL) printf("%d ", b->parent->value);
else printf("_ ");
if (b->left!=NULL) printf("%d ", b->left->value);
else printf("_ ");
if (b->right!=NULL) printf("%d\n", b->right->value);
else printf("_\n");
}
scanf("%d", &a1);
a2=find(&ApplesTree, a1, &b);
if (a2==1) printf("-\n");
else
{
if (b->parent!=NULL) printf("%d ", b->parent->value);
else printf("_ ");
if (b->left!=NULL) printf("%d ", b->left->value);
else printf("_ ");
if (b->right!=NULL) printf("%d\n", b->right->value);
else printf("_\n");
}
scanf("%d", &a1);
removeNode(&ApplesTree, a1);
printTree(&ApplesTree);
while (rotateLeft(ApplesTree.root, &ApplesTree)==0)
a2=0;
printTree(&ApplesTree);
while (rotateRight(ApplesTree.root, &ApplesTree)==0)
a2=0;
printTree(&ApplesTree);
printf("%d\n", ApplesTree.number);
clear(&ApplesTree);
printTree(&ApplesTree);
return 0;
}
|
the_stack_data/1130547.c | #include <stdio.h>
#include <stdlib.h>
void troca(int i,int j,int *V)
{
int aux;
aux = *(V+i);
*(V+i) = *(V+j);
*(V+j) = aux;
}
int separa(int p, int r, int *V)
{
int *x,i,j;
x = (V+p);
i = p;
j = r;
while (1)
{
while(*(V+j) > *x)
j--;
while(*(V+i) < *x)
i--;
if (i < j){
troca(i, j, V);
}
else
return j;
j--;
i++;
}
}
void quicksort(int p, int r, int *V)
{
int q;
if (p < r){
q = separa(p,r,V);
quicksort(p,q,V);
quicksort(q+1,r,V);
}
}
int soma_balanceada(int n, int *V)
{
int i=0,somacerta=0,correto=1,soma=0;
somacerta = *(V+i) + *(V+(n-1)-i);
for(i=1; i < (n/2); i++){
soma = *(V+i) + *(V+n-1-i);
if (soma == somacerta)
correto++;
}
if (correto == (n/2))
return 1;
else
return -1;
}
int main()
{
int *V,n,i=0,p=0;
scanf("%d",&n);
V = (int *) malloc(n * sizeof(int));
if (V != NULL){
for (i=0; i < n; i++)
scanf("%d",(V+i));
quicksort(p,n-1,V);
if (soma_balanceada(n,V) == 1)
printf("A sequencia eh balanceada\n");
else
printf("A sequencia nao eh balanceada\n");
}
else
printf("Num vai dar nao\n");
return 0;
}
|
the_stack_data/81127.c | #include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode *addTwoNumbers(struct ListNode *l1, struct ListNode *l2)
{
struct ListNode *head;
struct ListNode **pp = &head;
struct ListNode *p1, *p2;
int c = 0;
while (l1 && l2) {
p1 = l1;
l1 = l1->next;
p2 = l2;
l2 = l2->next;
int t = p1->val + p2->val + c;
c = 0;
if (t > 9) {
c = 1;
t -= 10;
}
*pp = malloc(sizeof(**pp));
(*pp)->val = t;
pp = &(*pp)->next;
}
while (l1) {
p1 = l1;
l1 = l1->next;
int t = p1->val + c;
c = 0;
if (t > 9) {
c = 1;
t -= 10;
}
*pp = malloc(sizeof(**pp));
(*pp)->val = t;
pp = &(*pp)->next;
}
while (l2) {
p1 = l2;
l2 = l2->next;
int t = p1->val + c;
c = 0;
if (t > 9) {
c = 1;
t -= 10;
}
*pp = malloc(sizeof(**pp));
(*pp)->val = t;
pp = &(*pp)->next;
}
if (c) {
*pp = malloc(sizeof(**pp));
(*pp)->val = c;
pp = &(*pp)->next;
}
*pp = NULL;
return(head);
}
main(void){}
|
the_stack_data/148578803.c | /*
Array typed firstprivate variables:
element-by-element copy.
Contributed by Pranav Tendulkar
[email protected]
4/12/2010
*/
int array[100];
int main()
{
array[10] = 10;
#pragma omp parallel firstprivate(array)
{
int i;
for(i=0;i<100;i++)
array[i] += i;
}
return 0;
}
|
the_stack_data/93886469.c | /* Generated by CIL v. 1.7.0 */
/* print_CIL_Input is false */
struct _IO_FILE;
struct timeval;
extern float strtof(char const *str , char const *endptr ) ;
extern void signal(int sig , void *func ) ;
typedef struct _IO_FILE FILE;
extern int atoi(char const *s ) ;
extern double strtod(char const *str , char const *endptr ) ;
extern int fclose(void *stream ) ;
extern void *fopen(char const *filename , char const *mode ) ;
extern void abort() ;
extern void exit(int status ) ;
extern int raise(int sig ) ;
extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ;
extern int strcmp(char const *a , char const *b ) ;
extern int rand() ;
extern unsigned long strtoul(char const *str , char const *endptr , int base ) ;
void RandomFunc(unsigned int input[1] , unsigned int output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
void megaInit(void)
{
{
}
}
int main(int argc , char *argv[] )
{
unsigned int input[1] ;
unsigned int output[1] ;
int randomFuns_i5 ;
unsigned int randomFuns_value6 ;
int randomFuns_main_i7 ;
{
megaInit();
if (argc != 2) {
printf("Call this program with %i arguments\n", 1);
exit(-1);
} else {
}
randomFuns_i5 = 0;
while (randomFuns_i5 < 1) {
randomFuns_value6 = (unsigned int )strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == 1041810857U) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%u\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
void RandomFunc(unsigned int input[1] , unsigned int output[1] )
{
unsigned int state[1] ;
char copy11 ;
unsigned short copy13 ;
unsigned short copy14 ;
char copy15 ;
{
state[0UL] = (input[0UL] + 914778474UL) - 981234615U;
if (state[0UL] & 1U) {
if (state[0UL] & 1U) {
if (state[0UL] & 1U) {
state[0UL] += state[0UL];
copy11 = *((char *)(& state[0UL]) + 3);
*((char *)(& state[0UL]) + 3) = *((char *)(& state[0UL]) + 1);
*((char *)(& state[0UL]) + 1) = copy11;
} else {
state[0UL] += state[0UL];
}
} else
if ((state[0UL] >> 1U) & 1U) {
state[0UL] += state[0UL];
copy13 = *((unsigned short *)(& state[0UL]) + 0);
*((unsigned short *)(& state[0UL]) + 0) = *((unsigned short *)(& state[0UL]) + 1);
*((unsigned short *)(& state[0UL]) + 1) = copy13;
} else {
copy14 = *((unsigned short *)(& state[0UL]) + 0);
*((unsigned short *)(& state[0UL]) + 0) = *((unsigned short *)(& state[0UL]) + 1);
*((unsigned short *)(& state[0UL]) + 1) = copy14;
copy14 = *((unsigned short *)(& state[0UL]) + 1);
*((unsigned short *)(& state[0UL]) + 1) = *((unsigned short *)(& state[0UL]) + 0);
*((unsigned short *)(& state[0UL]) + 0) = copy14;
state[0UL] += state[0UL];
}
} else
if ((state[0UL] >> 4U) & 1U) {
state[0UL] += state[0UL];
copy15 = *((char *)(& state[0UL]) + 3);
*((char *)(& state[0UL]) + 3) = *((char *)(& state[0UL]) + 0);
*((char *)(& state[0UL]) + 0) = copy15;
copy15 = *((char *)(& state[0UL]) + 0);
*((char *)(& state[0UL]) + 0) = *((char *)(& state[0UL]) + 1);
*((char *)(& state[0UL]) + 1) = copy15;
}
output[0UL] = (state[0UL] + 572847304UL) + 535407349U;
}
}
|
the_stack_data/168894561.c | //
// Created by Cosmin Alex on 12/10/2018.
//
#include<stdlib.h>
#include <stdio.h>
#include<string.h>
#include <ctype.h>
typedef struct {
char *sir;
int nr_aparitii;
} Cuvant;
/**
*
* @param cuvinte
* @param lungimeVector
*/
void afisare(Cuvant *cuvinte, int *lungimeVector){
if (cuvinte != NULL)
for (int i = 0; i < (*lungimeVector); i++) {
printf("Cuvantul %s apare de %d ori\n", cuvinte[i].sir, cuvinte[i].nr_aparitii);
}
}
/**
*
* @param lungimeVector
* @return
*/
Cuvant *procesareText(int *lungimeVector) {
FILE *in = fopen("..//cuvinte.txt", "r");
if (in == NULL) {
printf("Fisierul nu poate fi deschis");
exit(0);
}
char linie[100];
*lungimeVector = 0;
Cuvant *cuvinte = NULL;
while (fgets(linie, 100, in) != NULL) {
strtok(linie, "\n");
char *cuvant;
cuvant = strtok(linie, " ,.-");
while (cuvant != NULL) {
cuvant[0] = (char) tolower(cuvant[0]);
if (cuvinte == NULL) {
cuvinte = (Cuvant *) malloc(sizeof(Cuvant));
cuvinte[0].sir = (char *) malloc(strlen(cuvant) + 1);
strcpy(cuvinte[0].sir, cuvant);
cuvinte[0].nr_aparitii = 1;
(*lungimeVector)++;
} else {
int gasit = 0;
for (int i = 0; i < (*lungimeVector); i++)
if (strcmp(cuvinte[i].sir, cuvant) == 0) {
cuvinte[i].nr_aparitii++;
gasit = 1;
break;
}
if (!gasit) {
Cuvant *aux = realloc(cuvinte, (*lungimeVector + 1) * sizeof(Cuvant));
if (aux != NULL) {
cuvinte = aux;
cuvinte[(*lungimeVector)].sir = (char *) malloc(strlen(cuvant) + 1);
strcpy(cuvinte[(*lungimeVector)].sir, cuvant);
cuvinte[(*lungimeVector)].nr_aparitii = 1;
(*lungimeVector)++;
} else {
printf("Nu se poate realoca memoria!");
}
}
}
cuvant = strtok(NULL, " ,.-");
}
}
fclose(in);
afisare(cuvinte, lungimeVector);
return cuvinte;
}
/**
*
* @param p
* @param q
* @return
*/
int cmp(const void *p, const void *q) {
Cuvant firstWord = *(Cuvant *) p;
Cuvant secondWord = *(Cuvant *) q;
if (firstWord.nr_aparitii > secondWord.nr_aparitii)
return -1;
else if (firstWord.nr_aparitii < secondWord.nr_aparitii)
return 1;
else return strcmp(firstWord.sir, secondWord.sir);
}
//int main() {
// int lungimeVector;
// Cuvant *cuvinte = procesareText(&lungimeVector);
// printf("Vectorul sortat este -------------------------------------\n");
// qsort(cuvinte, lungimeVector, sizeof(Cuvant), cmp);
// afisare(cuvinte, &lungimeVector);
// free(cuvinte);
//} |
the_stack_data/628857.c | #include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int l, int m, int r)
{
//This function takes an array, and takes the left most(l), middle(m) and right(r) most indices of the array.
//Then this function copies two halves of the given array into two separate arrays.
// Then it does something called two finger algorithm.
// It then compares starting elements of both the sub arrays and then copies the smallest into the original array until the completion of the comparing all the elements of both the sub arrays.
//First sub array is from index l to m, second sub array is from index m+1 to r.
int i, j, k;
int s1 = m - l + 1;
int s2 = r - m;
int L[s1], R[s2];
for (i = 0; i < s1; i++)
L[i] = arr[l + i];
for (j = 0; j < s2; j++)
R[j] = arr[m + 1 + j];
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < s1 && j < s2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
//Here we copy the remaining elements of both sub arrays if left.
while (i < s1) {
arr[k] = L[i];
i++;
k++;
}
while (j < s2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergesort(int arr[], int left, int right)
{
//This function sorts 2 halves separately and gives our final sorted array using two finger algorithm.
if (left < right) {
//left and right are indices of the array from and to the places where the array has to be sorted.
int middle = left + (right - left) / 2;
//middle stores the middle index of the array
// Sorting both the halves of the array separately and then joining them using the merge function which joins 2 different sorted arrays by comparing their first elements and then so on.
mergesort(arr, left, middle);
mergesort(arr, middle + 1, right);
merge(arr, left, middle, right);
}
}
int main(int argc, char *argv[])
{
// Here in this file i used the term array at some places where i have allocated the memory dynamically, which is similar to an array for using in this file.
//opening the input file for taking the input
FILE *fp = fopen(argv[1],"r");
if(fp == NULL)
{
printf("Could not read input from input file\n");
}
else
{
//allocating memory for storing the data from file
int *p = (int*)malloc(sizeof(int));
int input=0;
int count=0;
//count stores the number of elements in the file
while(fscanf(fp,"%d",&input)!=EOF)
{
//storing all elements in the file dynamically
p =(int*)realloc(p,(count+1)*sizeof(int));
p[count]=input;
//arr[count]=input;
count++;
}
//calling the merge sort function on the array(space) which has stored our elements upto the number of elements(count)
mergesort(p, 0, count - 1);
//printing array(space) into a new file after sorting in separate lines
FILE *fp2 = fopen("mergesort.txt","w");
if(fp2==NULL)
{
printf("Could not write to the output file\n");
}
else
{
for(int j=0;j<count-1;j++)
{
fprintf(fp2,"%d\n",p[j]);
}
fprintf(fp2,"%d",p[count-1]);
}
//closing the opened files
fclose(fp);
fclose(fp2);
}
return 0;
}
|
the_stack_data/329382.c | /*-
* Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*-
* Example of using EVP_MD_fetch and EVP_Digest* methods to calculate
* a digest of static buffers
* You can find SHA3 test vectors from NIST here:
* https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/sha3/sha-3bytetestvectors.zip
* For example, contains these lines:
Len = 80
Msg = 1ca984dcc913344370cf
MD = 6915ea0eeffb99b9b246a0e34daf3947852684c3d618260119a22835659e4f23d4eb66a15d0affb8e93771578f5e8f25b7a5f2a55f511fb8b96325ba2cd14816
* use xxd convert the hex message string to binary input for BIO_f_md:
* echo "1ca984dcc913344370cf" | xxd -r -p | ./BIO_f_md
* and then verify the output matches MD above.
*/
#include <string.h>
#include <stdio.h>
#include <openssl/err.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
/*-
* This demonstration will show how to digest data using
* a BIO configured with a message digest
* A message digest name may be passed as an argument.
* The default digest is SHA3-512
*/
int main(int argc, char * argv[])
{
int result = 1;
OSSL_LIB_CTX *library_context = NULL;
BIO *input = NULL;
BIO *bio_digest = NULL;
EVP_MD *md = NULL;
unsigned char buffer[512];
size_t readct, writect;
size_t digest_size;
char *digest_value=NULL;
int j;
input = BIO_new_fd( fileno(stdin), 1 );
if (input == NULL) {
fprintf(stderr, "BIO_new_fd() for stdin returned NULL\n");
goto cleanup;
}
library_context = OSSL_LIB_CTX_new();
if (library_context == NULL) {
fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n");
goto cleanup;
}
/*
* Fetch a message digest by name
* The algorithm name is case insensitive.
* See providers(7) for details about algorithm fetching
*/
md = EVP_MD_fetch( library_context, "SHA3-512", NULL );
if (md == NULL) {
fprintf(stderr, "EVP_MD_fetch did not find SHA3-512.\n");
goto cleanup;
}
digest_size = EVP_MD_get_size(md);
digest_value = OPENSSL_malloc(digest_size);
if (digest_value == NULL) {
fprintf(stderr, "Can't allocate %lu bytes for the digest value.\n", (unsigned long)digest_size);
goto cleanup;
}
/* Make a bio that uses the digest */
bio_digest = BIO_new(BIO_f_md());
if (bio_digest == NULL) {
fprintf(stderr, "BIO_new(BIO_f_md()) returned NULL\n");
goto cleanup;
}
/* set our bio_digest BIO to digest data */
if (BIO_set_md(bio_digest,md) != 1) {
fprintf(stderr, "BIO_set_md failed.\n");
goto cleanup;
}
/*-
* We will use BIO chaining so that as we read, the digest gets updated
* See the man page for BIO_push
*/
BIO *reading = BIO_push( bio_digest, input );
while( BIO_read(reading, buffer, sizeof(buffer)) > 0 )
;
/*-
* BIO_gets must be used to calculate the final
* digest value and then copy it to digest_value.
*/
if (BIO_gets(bio_digest, digest_value, digest_size) != digest_size) {
fprintf(stderr, "BIO_gets(bio_digest) failed\n");
goto cleanup;
}
for (j=0; j<digest_size; j++) {
fprintf(stdout, "%02x", (unsigned char)digest_value[j]);
}
fprintf(stdout, "\n");
result = 0;
cleanup:
if (result != 0)
ERR_print_errors_fp(stderr);
OPENSSL_free(digest_value);
BIO_free(input);
BIO_free(bio_digest);
EVP_MD_free(md);
OSSL_LIB_CTX_free(library_context);
return result;
}
|
the_stack_data/187643600.c | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
void write_sprr(uint64_t v)
{
__asm__ __volatile__("msr s3_3_c15_c7_0, %0\n"
"isb sy\n" ::"r"(v)
:);
}
uint64_t read_sprr(void)
{
uint64_t v;
__asm__ __volatile__("isb sy\n"
"mrs %0, s3_3_c15_c7_0\n"
: "=r"(v)::"memory");
return v;
}
int main(int argc, char *argv[])
{
for (int i = 0; i < 64; ++i) {
printf("s3_3_c15_c7_0 bit %02d: %016llx\n", i, read_sprr());
}
}
|
the_stack_data/46327.c | #include <stdio.h>
int main()
{
int t, i;
long long n;
scanf("%d", &t);
for(i=0; i<t; i++){
scanf("%d", &n);
printf("%d", n+1);
}
return 0;
}
|
the_stack_data/61461.c | static char a;
static char foo(char *p) {
*p = 5;
a = 3;
return a;
}
int test138() {
char q;
char r;
r = foo(&q);
return 172 - r + q;
}
|
the_stack_data/883506.c | int max(int num1, int num2); |
the_stack_data/150452.c | void ctest2(int *i)
{
*i=100;
}
int ctest3(int i)
{
return i+1;
}
|
the_stack_data/398904.c | //Não foi implementado por falta de tempo.
// //Verifica e identifica qual é o PowerUp
// void verificaPowerUp(){
//
//
// }
//Para encerrar o PowerUp apos um periodo de tempo.
//Se pa tem de ir na main, pq precisa chamar o q1 -> jogador
// void encerraPowerUp(){
//
//
//
//
// }
|
the_stack_data/31829.c | #include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#define TAILLE 1024
int main(void)
{
key_t key;
int semid;
int id, del;
union semun {
int val;
struct semid_ds *buf;
ushort *array;
} arg;
id = shmget((key_t)1234,TAILLE+sizeof(int),0600|IPC_CREAT);
if (id < 0) { perror("Error shmget"); exit(1); }
del = shmctl(id, IPC_RMID, NULL);
if (del < 0) { perror("Error shmctl"); exit(1); }
if ((key = ftok("tp3.c", 'J')) == -1) {
perror("ftok");
exit(1);
}
if ((semid = semget(key, 1, 0)) == -1) {
perror("semget");
exit(1);
}
if (semctl(semid, 0, IPC_RMID, arg) == -1) {
perror("semctl");
exit(1);
}
return 0;
} |
the_stack_data/863040.c | #include <assert.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <portaudio.h>
#include <pthread.h>
#if __APPLE__
#include <dispatch/dispatch.h>
#endif
#define FAKE_AUDIO 0
#define USE_PRODUCE_THREAD 1
#define DETECT_UNDERRUNS 0
typedef struct _buffer {
uint8_t ready;
float* buf;
} _buffer;
static PaStream* g_stream = NULL;
static unsigned long g_frames_per_buffer = 0;
static _buffer* g_buffers;
static size_t g_buffer_count = 0;
static size_t g_next_buffer = 0;
static pthread_t g_produce_thread;
#if __APPLE__
static dispatch_semaphore_t g_produce_sem;
#else
static sem_t g_produce_sem;
#endif
static double g_produce_timestamp;
static uint32_t g_produce_underruns;
// the ponyland callbacks
typedef void (*pony_output_add_buffer_cb)(void* pony_object, float* io_buffer, uint8_t* io_ready);
typedef void (*pony_output_preroll_cb)(void* pony_object);
typedef void (*pony_output_produce_cb)(void* pony_object, double timestamp);
static pony_output_add_buffer_cb g_add_buffer_cb = NULL;
static pony_output_preroll_cb g_preroll_cb = NULL;
static pony_output_produce_cb g_produce_cb = NULL;
static void* g_pony_object;
// registers this thread with the pony runtime.
extern void pony_register_thread();
void init_buffers(unsigned long buffer_count) {
int i;
g_buffers = (_buffer*)malloc(sizeof(_buffer) * buffer_count);
for (i = 0; i < buffer_count; ++i) {
g_buffers[i].ready = 0;
g_buffers[i].buf = (float*) malloc(sizeof(float) * g_frames_per_buffer);
}
g_buffer_count = buffer_count;
}
void preroll() {
printf("preroll: add buffer %p preroll %p produce %p\n",
g_add_buffer_cb,
g_preroll_cb,
g_produce_cb);
// Send buffers.
int i;
for (i = 0; i < g_buffer_count; ++i) {
(*g_add_buffer_cb)(g_pony_object, g_buffers[i].buf, &g_buffers[i].ready);
}
// Signal start of preroll phase.
(*g_preroll_cb)(g_pony_object);
// Fill.
for (i = 0; i < g_buffer_count; ++i) {
(*g_produce_cb)(g_pony_object, 0.);
}
}
void* produce_thread(void* unused) {
pony_register_thread();
uint32_t underruns = g_produce_underruns;
while (1) {
#if __APPLE__
int wait_result = dispatch_semaphore_wait(
g_produce_sem, DISPATCH_TIME_FOREVER);
#else
int wait_result = sem_wait(&g_produce_sem);
#endif
if (wait_result != 0) {
printf("Producer thread done\n");
return NULL;
}
if (g_produce_underruns > underruns) {
printf("%d underruns\n", g_produce_underruns - underruns);
underruns = g_produce_underruns;
}
(*g_produce_cb)(g_pony_object, g_produce_timestamp);
}
return NULL;
}
void init_produce_thread() {
int result;
g_produce_timestamp = 0;
#if __APPLE__
g_produce_sem = dispatch_semaphore_create(0);
#else
result = sem_init(&g_produce_sem, 0, 0);
assert(result == 0);
#endif
pthread_attr_t attr;
pthread_attr_init(&attr);
result = pthread_create(&g_produce_thread, &attr, &produce_thread, NULL);
assert(result == 0);
}
#if FAKE_AUDIO
static int g_fakeaudio_run = 1;
static pthread_t g_fakeaudio_thread;
void* fakeaudio_thread(void* unused) {
int count = 0;
while (g_fakeaudio_run) {
// wait 128/44100 microseconds.
usleep(2902);
//usleep(1000000);
// notify the producer.
if (!(++count & 0x3f)) {
puts(".");
}
#if USE_PRODUCE_THREAD
#if __APPLE__
dispatch_semaphore_signal(g_produce_sem);
#else
sem_post(&g_produce_sem);
#endif
#else
(*g_produce_cb)(g_pony_object, g_produce_timestamp);
#endif
// +++ update timestamp
}
}
void init_fakeaudio_thread() {
int result;
g_fakeaudio_run = 1;
pthread_attr_t attr;
pthread_attr_init(&attr);
result = pthread_create(&g_fakeaudio_thread, &attr, &fakeaudio_thread, NULL);
assert(result == 0);
}
#endif // FAKE_AUDIO
// the portaudio callback
int output_stream_cb(const void* input,
void* output,
unsigned long frames_per_buffer,
const PaStreamCallbackTimeInfo* time_info,
PaStreamCallbackFlags status_flags,
void* user) {
#if !USE_PRODUCE_THREAD
static int first = 1;
if (first) {
first = 0;
pony_register_thread();
}
#endif
assert(frames_per_buffer == g_frames_per_buffer);
#if DETECT_UNDERRUNS
if (g_buffers[g_next_buffer].ready) {
#endif
memcpy(output, g_buffers[g_next_buffer].buf, frames_per_buffer * sizeof(float));
g_buffers[g_next_buffer].ready = 0;
g_produce_timestamp = time_info->outputBufferDacTime;
#if USE_PRODUCE_THREAD
#if __APPLE__
dispatch_semaphore_signal(g_produce_sem);
#else
sem_post(&g_produce_sem);
#endif
#else
(*g_produce_cb)(g_pony_object, g_produce_timestamp);
#endif
if (++g_next_buffer == g_buffer_count) {
g_next_buffer = 0;
}
#if DETECT_UNDERRUNS
} else {
// underrun!
g_produce_underruns++;
}
#endif
return paContinue;
}
int init_output_stream(unsigned long frames_per_buffer,
unsigned long buffer_count,
pony_output_add_buffer_cb add_buffer_cb,
pony_output_preroll_cb preroll_cb,
pony_output_produce_cb produce_cb,
void* pony_object) {
printf("init: cbs: add buffer %p preroll %p produce %p\n",
add_buffer_cb,
preroll_cb,
produce_cb);
if (NULL != g_stream) {
return paDeviceUnavailable;
}
#if FAKE_AUDIO
#else
PaError result = Pa_Initialize();
if (paNoError != result) {
return result;
}
PaDeviceIndex device_index = Pa_GetDefaultOutputDevice();
int device_count = Pa_GetDeviceCount();
int i;
for (i = 0; i < device_count; ++i) {
printf("dev %d: %s\n", i, Pa_GetDeviceInfo(i)->name);
if (!strcmp("pulse", Pa_GetDeviceInfo(i)->name)) {
device_index = i;
break;
}
}
if (device_index < 0) {
return device_index;
}
const PaDeviceInfo* device_info = Pa_GetDeviceInfo(device_index);
PaStream* stream;
#if 0
result = Pa_OpenDefaultStream(&stream,
0, // no inputs
1, // 1 output
paFloat32,
44100,
frames_per_buffer,
&output_stream_cb,
pony_object);
#else
PaStreamParameters output_params;
output_params.channelCount = 1;
output_params.device = device_index;
output_params.hostApiSpecificStreamInfo = NULL;
output_params.sampleFormat = paFloat32;
output_params.suggestedLatency = device_info->defaultLowOutputLatency;
output_params.hostApiSpecificStreamInfo = NULL;
result = Pa_IsFormatSupported(NULL, &output_params, 44100.0);
if (result != 0) {
printf("format not supported!\n");
return result;
}
const PaHostApiInfo* api_info = Pa_GetHostApiInfo(device_info->hostApi);
printf("using device '%s', API '%s'\n", device_info->name, api_info->name);
printf("latency: %lf\n", device_info->defaultLowOutputLatency);
result = Pa_OpenStream(
&stream,
NULL,
&output_params,
44100.0,
frames_per_buffer,
paNoFlag,
&output_stream_cb,
pony_object);
#endif
if (paNoError != result) {
return result;
}
g_stream = stream;
#endif // FAKE_AUDIO
g_frames_per_buffer = frames_per_buffer;
g_pony_object = pony_object;
g_add_buffer_cb = add_buffer_cb;
g_preroll_cb = preroll_cb;
g_produce_cb = produce_cb;
init_buffers(buffer_count);
preroll();
return paNoError;
}
int start_output_stream() {
#if USE_PRODUCE_THREAD
init_produce_thread();
#endif
#if FAKE_AUDIO
init_fakeaudio_thread();
return 0;
#else
PaError result = Pa_StartStream(g_stream);
return result;
#endif
}
int stop_output_stream() {
printf("stop_output_stream() IN\n");
#if FAKE_AUDIO
g_fakeaudio_run = 0;
return 0;
#else
PaError result = Pa_StopStream(g_stream);
return result;
#endif
}
|
the_stack_data/18886524.c | #include <stdlib.h>
extern void *__realloc_r(void *ptr, int s);
void *realloc(void *ptr, size_t size)
{
return (void*) __realloc_r(ptr, size);
}
|
the_stack_data/29826639.c | /* { dg-do compile } */
/* { dg-require-effective-target arm_v8_vfp_ok } */
/* { dg-options "-O2" } */
/* { dg-add-options arm_v8_vfp } */
double
foo (double x)
{
return __builtin_round (x);
}
/* { dg-final { scan-assembler-times "vrinta.f64\td\[0-9\]+" 1 } } */
|
the_stack_data/215768714.c | //superstr.c
#include <stdio.h>
#include <string.h>
int overlapf(char*, char*);
int main() {
int n, i, j, k, maxI, maxJ,
minlap = 100, strslen = 0, lapslen=0, max;
scanf("%d ", &n);
int overlap[n][n];
int blockedRow[n];
int blockedColomn[n];
int maxlaps[n];
char strs[n][100];
for(i=0; i<n; i++) {
gets(strs[i]);
strslen += strlen(strs[i]);
}
for(i=0; i<n; i++)
for(j=0; j<n; j++) {
overlap[i][j] = overlapf(strs[i], strs[j]);
if(i == j) overlap[i][j] = 0;
}
for(k=0; k<n; k++) {
maxI = maxJ = max = 0;
for(i = 0; i<n; i++)
for(j = 0; j<n; j++) {
if(!blockedRow[i] && !blockedColomn[j]
&& overlap[i][j] > max) {
maxI = i;
maxJ = j;
max = overlap[i][j];
}
}
blockedRow[maxI] = 1;
blockedColomn[maxJ] = 1;
maxlaps[k] = max;
}
for(i=0; i<n; i++) {
if(maxlaps[i] < minlap) minlap = maxlaps[i];
lapslen += maxlaps[i];
}
lapslen -= minlap;
printf("%d\n", strslen - lapslen);
return 0;
}
int overlapf(char* s1, char* s2) {
int lap = 0;
char *str1, *str2;
while(*s1 != '\0') {
str1 = s1;
str2 = s2;
lap = 0;
for(; (*str1 == *str2) && (*str1 != '\0'); lap++, str1++, str2++);
if(*str1 == '\0')
return lap;
s1++;
}
}
|
the_stack_data/67324605.c | /***********************************************************************************
***********************************************************************************/
#include "stdio.h"
#include "math.h"
#include "string.h"
#include "stdlib.h"
#include "float.h"
#define MAX_CHROM_NUM 24 //maximum chromosome number
typedef struct
{
char chromName[100];
int chromSize;
}CHROM_INFO;
//Structure defining the histone modification regions
CHROM_INFO chromInfo[MAX_CHROM_NUM];
//total number of bins
int totalBinNum;
int chromNum;
int ChromToIndex(char *chrom);
char *IndexToChrom(int index, char *chrom, int len);
int GetChromInfo(char *fileName);
float **GetBinCount(char *l1FileName, char *l2FileName,int binsize);
int ReadHistoneFile(char *histoneFilename,char *cell_name,int binsize);
int main(int argc, char* argv[])
{
char histoneFileName[1000],chromFileName[1000],projectName[1000];
int binsize;
int count=0;
if (argc!=5)
{
printf("Usage: <Histone File Name> <Chromosome Description File Name> <bin size> <cell-type name>\n");
return 0;
}
strcpy(histoneFileName,argv[1]);
strcpy(chromFileName,argv[2]);
binsize=atoi(argv[3]);
strcpy(projectName,argv[4]);
//Read chromosome description file
if (!GetChromInfo(chromFileName))
{
printf("chromosome description file is not valid\n");
return 0;
}
//Read tag files of L1 and L2, and define the histone modification regions
float **binrpkm;
int i,j;
ReadHistoneFile(histoneFileName,projectName,binsize);
return 0;
}
//transform chromosome name the chromosome index
//
//
//
//
//
int ChromToIndex(char *chrom)
{
int i;
for (i=0;i<chromNum;i++)
{
if (!strcmp(chrom, chromInfo[i].chromName))
{
break;
}
}
if (i<chromNum)
{
return i;
}
else
{
return -1;
}
}
//transfrom chromosome index to chromosome name
char *IndexToChrom(int index, char *chrom, int len)
{
if ((index<0)||(index>=chromNum))
{
return 0;
}
if (strlen(chromInfo[index].chromName)>=len)
{
return 0;
}
strcpy(chrom, chromInfo[index].chromName);
return chrom;
}
//Read the chromosome description file
int GetChromInfo(char *fileName)
{
FILE *fh;
char tmpStr[1000];
fh = (FILE *)fopen(fileName, "r");
if (!fh)
{
return -1;
}
chromNum = 0;
fscanf(fh, "%s", tmpStr);
while (!feof(fh))
{
strcpy(chromInfo[chromNum].chromName, tmpStr);
fscanf(fh, "%s", tmpStr);
chromInfo[chromNum].chromSize = atoi(tmpStr);
fscanf(fh, "%s", tmpStr);
chromNum++;
}
fclose(fh);
return chromNum;
}
int ReadHistoneFile(char *histoneFileName,char *cell_name,int BIN_SIZE)
{
FILE *fh,*fh2;
float **avgBinRPKM,**binRPKM;
int i,j,k,num_reps;
char word[100],hist_mod[20],l1FileName[1000],l2FileName[1000];
binRPKM =(float **)malloc(chromNum*sizeof(float *));
avgBinRPKM=(float **)malloc(chromNum*sizeof(float *));
totalBinNum = 0;
for (i=0;i<chromNum;i++)
{
totalBinNum += chromInfo[i].chromSize/BIN_SIZE+1;
binRPKM[i] = (float *)malloc((chromInfo[i].chromSize/BIN_SIZE+1)*sizeof(float));
memset(binRPKM[i], 0, (chromInfo[i].chromSize/BIN_SIZE+1)*sizeof(float));
avgBinRPKM[i] = (float *)malloc((chromInfo[i].chromSize/BIN_SIZE+1)*sizeof(float));
memset(avgBinRPKM[i], 0, (chromInfo[i].chromSize/BIN_SIZE+1)*sizeof(float));
}
fh = (FILE *)fopen(histoneFileName, "r");
char binFileName[1000];
if (!fh)
{
return -1;
}
while (!feof(fh))
{ fscanf(fh, "%s",word);
if((word[0]=='E')&&(word[1]=='O')&&(word[2]=='F')){break;}
if((word[0]=='M')&&(word[1]=='a'))
{ fscanf(fh, "%s",hist_mod);fscanf(fh,"%d",&num_reps);
printf("Mark:%s\n",hist_mod);
sprintf(binFileName,"%s.%s.rpkm",cell_name,hist_mod);
fh2 = (FILE *)fopen(binFileName, "w");}
else{sprintf(l1FileName,"%s",word);
fscanf(fh, "%s",l2FileName);
printf("%s\n%s\n",l1FileName,l2FileName);
binRPKM=GetBinCount(l1FileName,l2FileName,BIN_SIZE);
for(j=0;j<chromNum;j++){
for(k=0;k<(chromInfo[j].chromSize/BIN_SIZE);k++){
avgBinRPKM[j][k]=binRPKM[j][k];}}
printf("Done with replicate 1!\n");
for(i=1;i<num_reps;i++){
fscanf(fh, "%s",l1FileName);
fscanf(fh, "%s",l2FileName);
binRPKM=GetBinCount(l1FileName,l2FileName,BIN_SIZE);
for(j=0;j<chromNum;j++){
for(k=0;k<(chromInfo[j].chromSize/BIN_SIZE);k++){
avgBinRPKM[j][k]=avgBinRPKM[j][k]+binRPKM[j][k];}}
printf("Done with Replicate %d\n",i+1);
}
for (i=0;i<chromNum;i++)
{
free(binRPKM[i]);
}
free(binRPKM);
for(j=0;j<chromNum;j++){
for(k=1;k<(chromInfo[j].chromSize/BIN_SIZE);k++){
if(avgBinRPKM[j][k]!=0.0000){fprintf(fh2,"%d\t%d\t%f\n",j+1,k*BIN_SIZE,(avgBinRPKM[j][k]/num_reps));}}}
fclose(fh2);
}
}
fclose(fh);
return 0;
}
//Read the tag files of L1 and L2, and determine the histone modification sites
float **GetBinCount(char *l1FileName, char *l2FileName,int BIN_SIZE)
{
int l1TagNum,l2TagNum;
//binCounts and binCounts2 store the fragment counts in each bin. mask=1 flags histone modification site
int **binCounts1, **binCounts2;
float **binRPKM;
char tmpStr[1000];
char tmpChrom[100];
int tmpPos,tmpNeg,tmpIndex;
char tmpStrand;
int tmpStart, tmpEnd;
int i,j,k;
FILE *fh;
//Allocate Memory
binCounts1 = (int **)malloc(chromNum*sizeof(int *));
binCounts2 = (int **)malloc(chromNum*sizeof(int *));
binRPKM =(float **)malloc(chromNum*sizeof(float *));
//Initialize the arrays
totalBinNum = 0;
for (i=0;i<chromNum;i++)
{
totalBinNum += chromInfo[i].chromSize/BIN_SIZE+1;
binCounts1[i] = (int *)malloc((chromInfo[i].chromSize/BIN_SIZE+1)*sizeof(int));
binCounts2[i] = (int *)malloc((chromInfo[i].chromSize/BIN_SIZE+1)*sizeof(int));
binRPKM[i] = (float *)malloc((chromInfo[i].chromSize/BIN_SIZE+1)*sizeof(float));
memset(binCounts1[i], 0, (chromInfo[i].chromSize/BIN_SIZE+1)*sizeof(int));
memset(binCounts2[i], 0, (chromInfo[i].chromSize/BIN_SIZE+1)*sizeof(int));
memset(binRPKM[i], 0, (chromInfo[i].chromSize/BIN_SIZE+1)*sizeof(float));
}
// Read library 1 tag file
l1TagNum = 0;
char a[100],b[100];
fh = (FILE *)fopen(l1FileName, "r");
fscanf(fh, "%s", tmpChrom);
while (!feof(fh))
{
tmpIndex = ChromToIndex(tmpChrom);
if (tmpIndex<0)
{
fscanf(fh, "%d", &tmpPos); fscanf(fh, "%d", &tmpNeg);
fscanf(fh, "%s",a);
//fscanf(fh, "%s",b);
fscanf(fh, "%s",tmpStr);
fscanf(fh, "%s", tmpChrom);
continue;
}
fscanf(fh, "%d", &tmpPos);fscanf(fh, "%d", &tmpNeg);
fscanf(fh, "%s",a);
//fscanf(fh, "%s",b);
fscanf(fh, "%s",tmpStr);
tmpStrand=tmpStr[0];
if ((tmpPos>=chromInfo[tmpIndex].chromSize)||(tmpPos<0))
{
fscanf(fh, "%s", tmpChrom);
continue;
}
l1TagNum++;
if(tmpStrand=='+'){
binCounts1[tmpIndex][tmpPos/BIN_SIZE]++;}
if(tmpStrand=='-'){
binCounts1[tmpIndex][tmpNeg/BIN_SIZE]++;}
fscanf(fh,"%s", tmpChrom);
}
printf("Done reading file1! Number of tags=%d\n",l1TagNum);
fclose(fh);
//read library 2 tag file
l2TagNum = 0;
fh = (FILE *)fopen(l2FileName, "r");
fscanf(fh, "%s", tmpChrom);
while (!feof(fh))
{
tmpIndex = ChromToIndex(tmpChrom);
if (tmpIndex<0)
{
fscanf(fh, "%d", &tmpPos);fscanf(fh, "%d", &tmpNeg);
fscanf(fh, "%s",a);
//fscanf(fh, "%s",b);
fscanf(fh, "%s",tmpStr);
fscanf(fh, "%s", tmpChrom);
continue;
}
fscanf(fh, "%d", &tmpPos);fscanf(fh, "%d", &tmpNeg);
fscanf(fh, "%s",a);
//fscanf(fh, "%s",b);
fscanf(fh, "%s",tmpStr);
tmpStrand=tmpStr[0];
if ((tmpPos>=chromInfo[tmpIndex].chromSize)||(tmpPos<0))
{
fscanf(fh, "%s", tmpChrom);
continue;
}
l2TagNum++;
if(tmpStrand=='+'){
binCounts2[tmpIndex][tmpPos/BIN_SIZE]++;}
if(tmpStrand=='-'){
binCounts2[tmpIndex][tmpNeg/BIN_SIZE]++;}
fscanf(fh,"%s", tmpChrom);
}
fclose(fh);
printf("Done reading file2! Number of tags=%d\n",l2TagNum);
float binnum1,binnum2;
for (i=0;i<chromNum;i++)
{
for (j=0;j<=(chromInfo[i].chromSize/BIN_SIZE);j++)
{
binnum1=10000000*binCounts1[i][j];
if((j>=2)||(j<(chromInfo[i].chromSize/BIN_SIZE)-2))
{ binnum2=2000000*(binCounts2[i][j-2]+binCounts2[i][j-1]+binCounts2[i][j]+binCounts2[i][j+1]+binCounts2[i][j+2]);
}
else
{ binnum2=10000000*binCounts2[i][j];}
float abc1 = (binnum1/l1TagNum);
float abc2 = (binnum2/l2TagNum);
binRPKM[i][j]=abc1-abc2;
}
}
//Free memory
for (i=0;i<chromNum;i++)
{
free(binCounts1[i]);
free(binCounts2[i]);
}
free(binCounts1);
free(binCounts2);
return binRPKM;
}
|
the_stack_data/117328484.c | /* This testcase is part of GDB, the GNU debugger.
Copyright (C) 2013-2016 Free Software Foundation, Inc.
This program 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 3 of the License, or
(at your option) any later version.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */
int
return_false (void)
{
return 0;
}
int
test (void)
{
int a = 0;
while (a < 10)
a++; /* set breakpoint here */
return 0; /* set end breakpoint here */
}
|
the_stack_data/764251.c | /* This testcase is part of GDB, the GNU debugger.
Copyright 2002-2016 Free Software Foundation, Inc.
This program 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 3 of the License, or
(at your option) any later version.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
unsigned int args[2];
int trigger = 0;
void *
thread_function0 (void *arg)
{
int my_number = (long) arg;
volatile int *myp = (volatile int *) &args[my_number];
while (*myp > 0)
{
(*myp) ++;
usleep (1); /* Loop increment 1. */
}
return NULL;
}
void *
thread_function0_1 (void *arg)
{
void *ret = thread_function0 (arg);
return ret; /* set breakpoint here */
}
void *
thread_function1 (void *arg)
{
int my_number = (long) arg;
volatile int *myp = (volatile int *) &args[my_number];
while (*myp > 0)
{
(*myp) ++;
usleep (1); /* Loop increment 2. */
}
return NULL;
}
int
main ()
{
int res;
pthread_t threads[2];
void *thread_result;
long i = 0;
args[i] = 1; /* Init value. */
res = pthread_create (&threads[i], NULL,
thread_function0_1,
(void *) i);
i++;
args[i] = 1; /* Init value. */
res = pthread_create(&threads[i], NULL,
thread_function1,
(void *) i);
pthread_join (threads[0], &thread_result);
pthread_join (threads[1], &thread_result);
exit(EXIT_SUCCESS);
}
|
the_stack_data/61076616.c | #include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main(){
int x1;
int v1;
int x2;
int v2;
int flag=0;
scanf("%d %d %d %d",&x1,&v1,&x2,&v2);
if(x2>x1 && v2>v1)
printf("NO");
else if(x1>x2 && v1>v2)
printf("NO");
else if(x1>x2 && v1==v2)
printf("NO");
else if(x2>x1 && v1==v2)
printf("NO");
else if(x1>x2 && v1<v2){
if(x1-x2%v2-v1==0)
printf("YES");
else
printf("NO");
}
else if(x1<x2 && v1>v2){
if((x2-x1)% (v1-v2)==0)
printf("YES");
else
printf("NO");
}
return 0;
} |
the_stack_data/145269.c | // Ogg Vorbis audio decoder - v1.20 - public domain
// http://nothings.org/stb_vorbis/
//
// Original version written by Sean Barrett in 2007.
//
// Originally sponsored by RAD Game Tools. Seeking implementation
// sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker,
// Elias Software, Aras Pranckevicius, and Sean Barrett.
//
// LICENSE
//
// See end of file for license information.
//
// Limitations:
//
// - floor 0 not supported (used in old ogg vorbis files pre-2004)
// - lossless sample-truncation at beginning ignored
// - cannot concatenate multiple vorbis streams
// - sample positions are 32-bit, limiting seekable 192Khz
// files to around 6 hours (Ogg supports 64-bit)
//
// Feature contributors:
// Dougall Johnson (sample-exact seeking)
//
// Bugfix/warning contributors:
// Terje Mathisen Niklas Frykholm Andy Hill
// Casey Muratori John Bolton Gargaj
// Laurent Gomila Marc LeBlanc Ronny Chevalier
// Bernhard Wodo Evan Balster github:alxprd
// Tom Beaumont Ingo Leitgeb Nicolas Guillemot
// Phillip Bennefall Rohit Thiago Goulart
// github:manxorist saga musix github:infatum
// Timur Gagiev Maxwell Koo Peter Waller
// github:audinowho Dougall Johnson David Reid
// github:Clownacy Pedro J. Estebanez Remi Verschelde
//
// Partial history:
// 1.20 - 2020-07-11 - several small fixes
// 1.19 - 2020-02-05 - warnings
// 1.18 - 2020-02-02 - fix seek bugs; parse header comments; misc warnings etc.
// 1.17 - 2019-07-08 - fix CVE-2019-13217..CVE-2019-13223 (by ForAllSecure)
// 1.16 - 2019-03-04 - fix warnings
// 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found
// 1.14 - 2018-02-11 - delete bogus dealloca usage
// 1.13 - 2018-01-29 - fix truncation of last frame (hopefully)
// 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files
// 1.11 - 2017-07-23 - fix MinGW compilation
// 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory
// 1.09 - 2016-04-04 - back out 'truncation of last frame' fix from previous version
// 1.08 - 2016-04-02 - warnings; setup memory leaks; truncation of last frame
// 1.07 - 2015-01-16 - fixes for crashes on invalid files; warning fixes; const
// 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson)
// some crash fixes when out of memory or with corrupt files
// fix some inappropriately signed shifts
// 1.05 - 2015-04-19 - don't define __forceinline if it's redundant
// 1.04 - 2014-08-27 - fix missing const-correct case in API
// 1.03 - 2014-08-07 - warning fixes
// 1.02 - 2014-07-09 - declare qsort comparison as explicitly _cdecl in Windows
// 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float (interleaved was correct)
// 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in >2-channel;
// (API change) report sample rate for decode-full-file funcs
//
// See end of file for full version history.
//////////////////////////////////////////////////////////////////////////////
//
// HEADER BEGINS HERE
//
#ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H
#define STB_VORBIS_INCLUDE_STB_VORBIS_H
#if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
#define STB_VORBIS_NO_STDIO 1
#endif
#ifndef STB_VORBIS_NO_STDIO
#include <stdio.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
/////////// THREAD SAFETY
// Individual stb_vorbis* handles are not thread-safe; you cannot decode from
// them from multiple threads at the same time. However, you can have multiple
// stb_vorbis* handles and decode from them independently in multiple thrads.
/////////// MEMORY ALLOCATION
// normally stb_vorbis uses malloc() to allocate memory at startup,
// and alloca() to allocate temporary memory during a frame on the
// stack. (Memory consumption will depend on the amount of setup
// data in the file and how you set the compile flags for speed
// vs. size. In my test files the maximal-size usage is ~150KB.)
//
// You can modify the wrapper functions in the source (setup_malloc,
// setup_temp_malloc, temp_malloc) to change this behavior, or you
// can use a simpler allocation model: you pass in a buffer from
// which stb_vorbis will allocate _all_ its memory (including the
// temp memory). "open" may fail with a VORBIS_outofmem if you
// do not pass in enough data; there is no way to determine how
// much you do need except to succeed (at which point you can
// query get_info to find the exact amount required. yes I know
// this is lame).
//
// If you pass in a non-NULL buffer of the type below, allocation
// will occur from it as described above. Otherwise just pass NULL
// to use malloc()/alloca()
typedef struct
{
char *alloc_buffer;
int alloc_buffer_length_in_bytes;
} stb_vorbis_alloc;
/////////// FUNCTIONS USEABLE WITH ALL INPUT MODES
typedef struct stb_vorbis stb_vorbis;
typedef struct
{
unsigned int sample_rate;
int channels;
unsigned int setup_memory_required;
unsigned int setup_temp_memory_required;
unsigned int temp_memory_required;
int max_frame_size;
} stb_vorbis_info;
typedef struct
{
char *vendor;
int comment_list_length;
char **comment_list;
} stb_vorbis_comment;
// get general information about the file
extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f);
// get ogg comments
extern stb_vorbis_comment stb_vorbis_get_comment(stb_vorbis *f);
// get the last error detected (clears it, too)
extern int stb_vorbis_get_error(stb_vorbis *f);
// close an ogg vorbis file and free all memory in use
extern void stb_vorbis_close(stb_vorbis *f);
// this function returns the offset (in samples) from the beginning of the
// file that will be returned by the next decode, if it is known, or -1
// otherwise. after a flush_pushdata() call, this may take a while before
// it becomes valid again.
// NOT WORKING YET after a seek with PULLDATA API
extern int stb_vorbis_get_sample_offset(stb_vorbis *f);
// returns the current seek point within the file, or offset from the beginning
// of the memory buffer. In pushdata mode it returns 0.
extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f);
/////////// PUSHDATA API
#ifndef STB_VORBIS_NO_PUSHDATA_API
// this API allows you to get blocks of data from any source and hand
// them to stb_vorbis. you have to buffer them; stb_vorbis will tell
// you how much it used, and you have to give it the rest next time;
// and stb_vorbis may not have enough data to work with and you will
// need to give it the same data again PLUS more. Note that the Vorbis
// specification does not bound the size of an individual frame.
extern stb_vorbis *stb_vorbis_open_pushdata(
const unsigned char * datablock, int datablock_length_in_bytes,
int *datablock_memory_consumed_in_bytes,
int *error,
const stb_vorbis_alloc *alloc_buffer);
// create a vorbis decoder by passing in the initial data block containing
// the ogg&vorbis headers (you don't need to do parse them, just provide
// the first N bytes of the file--you're told if it's not enough, see below)
// on success, returns an stb_vorbis *, does not set error, returns the amount of
// data parsed/consumed on this call in *datablock_memory_consumed_in_bytes;
// on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed
// if returns NULL and *error is VORBIS_need_more_data, then the input block was
// incomplete and you need to pass in a larger block from the start of the file
extern int stb_vorbis_decode_frame_pushdata(
stb_vorbis *f,
const unsigned char *datablock, int datablock_length_in_bytes,
int *channels, // place to write number of float * buffers
float ***output, // place to write float ** array of float * buffers
int *samples // place to write number of output samples
);
// decode a frame of audio sample data if possible from the passed-in data block
//
// return value: number of bytes we used from datablock
//
// possible cases:
// 0 bytes used, 0 samples output (need more data)
// N bytes used, 0 samples output (resynching the stream, keep going)
// N bytes used, M samples output (one frame of data)
// note that after opening a file, you will ALWAYS get one N-bytes,0-sample
// frame, because Vorbis always "discards" the first frame.
//
// Note that on resynch, stb_vorbis will rarely consume all of the buffer,
// instead only datablock_length_in_bytes-3 or less. This is because it wants
// to avoid missing parts of a page header if they cross a datablock boundary,
// without writing state-machiney code to record a partial detection.
//
// The number of channels returned are stored in *channels (which can be
// NULL--it is always the same as the number of channels reported by
// get_info). *output will contain an array of float* buffers, one per
// channel. In other words, (*output)[0][0] contains the first sample from
// the first channel, and (*output)[1][0] contains the first sample from
// the second channel.
extern void stb_vorbis_flush_pushdata(stb_vorbis *f);
// inform stb_vorbis that your next datablock will not be contiguous with
// previous ones (e.g. you've seeked in the data); future attempts to decode
// frames will cause stb_vorbis to resynchronize (as noted above), and
// once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it
// will begin decoding the _next_ frame.
//
// if you want to seek using pushdata, you need to seek in your file, then
// call stb_vorbis_flush_pushdata(), then start calling decoding, then once
// decoding is returning you data, call stb_vorbis_get_sample_offset, and
// if you don't like the result, seek your file again and repeat.
#endif
////////// PULLING INPUT API
#ifndef STB_VORBIS_NO_PULLDATA_API
// This API assumes stb_vorbis is allowed to pull data from a source--
// either a block of memory containing the _entire_ vorbis stream, or a
// FILE * that you or it create, or possibly some other reading mechanism
// if you go modify the source to replace the FILE * case with some kind
// of callback to your code. (But if you don't support seeking, you may
// just want to go ahead and use pushdata.)
#if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION)
extern int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output);
#endif
#if !defined(STB_VORBIS_NO_INTEGER_CONVERSION)
extern int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *channels, int *sample_rate, short **output);
#endif
// decode an entire file and output the data interleaved into a malloc()ed
// buffer stored in *output. The return value is the number of samples
// decoded, or -1 if the file could not be opened or was not an ogg vorbis file.
// When you're done with it, just free() the pointer returned in *output.
extern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len,
int *error, const stb_vorbis_alloc *alloc_buffer);
// create an ogg vorbis decoder from an ogg vorbis stream in memory (note
// this must be the entire stream!). on failure, returns NULL and sets *error
#ifndef STB_VORBIS_NO_STDIO
extern stb_vorbis * stb_vorbis_open_filename(const char *filename,
int *error, const stb_vorbis_alloc *alloc_buffer);
// create an ogg vorbis decoder from a filename via fopen(). on failure,
// returns NULL and sets *error (possibly to VORBIS_file_open_failure).
extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close,
int *error, const stb_vorbis_alloc *alloc_buffer);
// create an ogg vorbis decoder from an open FILE *, looking for a stream at
// the _current_ seek point (ftell). on failure, returns NULL and sets *error.
// note that stb_vorbis must "own" this stream; if you seek it in between
// calls to stb_vorbis, it will become confused. Moreover, if you attempt to
// perform stb_vorbis_seek_*() operations on this file, it will assume it
// owns the _entire_ rest of the file after the start point. Use the next
// function, stb_vorbis_open_file_section(), to limit it.
extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close,
int *error, const stb_vorbis_alloc *alloc_buffer, unsigned int len);
// create an ogg vorbis decoder from an open FILE *, looking for a stream at
// the _current_ seek point (ftell); the stream will be of length 'len' bytes.
// on failure, returns NULL and sets *error. note that stb_vorbis must "own"
// this stream; if you seek it in between calls to stb_vorbis, it will become
// confused.
#endif
extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number);
extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number);
// these functions seek in the Vorbis file to (approximately) 'sample_number'.
// after calling seek_frame(), the next call to get_frame_*() will include
// the specified sample. after calling stb_vorbis_seek(), the next call to
// stb_vorbis_get_samples_* will start with the specified sample. If you
// do not need to seek to EXACTLY the target sample when using get_samples_*,
// you can also use seek_frame().
extern int stb_vorbis_seek_start(stb_vorbis *f);
// this function is equivalent to stb_vorbis_seek(f,0)
extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f);
extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f);
// these functions return the total length of the vorbis stream
extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output);
// decode the next frame and return the number of samples. the number of
// channels returned are stored in *channels (which can be NULL--it is always
// the same as the number of channels reported by get_info). *output will
// contain an array of float* buffers, one per channel. These outputs will
// be overwritten on the next call to stb_vorbis_get_frame_*.
//
// You generally should not intermix calls to stb_vorbis_get_frame_*()
// and stb_vorbis_get_samples_*(), since the latter calls the former.
#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts);
extern int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples);
#endif
// decode the next frame and return the number of *samples* per channel.
// Note that for interleaved data, you pass in the number of shorts (the
// size of your array), but the return value is the number of samples per
// channel, not the total number of samples.
//
// The data is coerced to the number of channels you request according to the
// channel coercion rules (see below). You must pass in the size of your
// buffer(s) so that stb_vorbis will not overwrite the end of the buffer.
// The maximum buffer size needed can be gotten from get_info(); however,
// the Vorbis I specification implies an absolute maximum of 4096 samples
// per channel.
// Channel coercion rules:
// Let M be the number of channels requested, and N the number of channels present,
// and Cn be the nth channel; let stereo L be the sum of all L and center channels,
// and stereo R be the sum of all R and center channels (channel assignment from the
// vorbis spec).
// M N output
// 1 k sum(Ck) for all k
// 2 * stereo L, stereo R
// k l k > l, the first l channels, then 0s
// k l k <= l, the first k channels
// Note that this is not _good_ surround etc. mixing at all! It's just so
// you get something useful.
extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats);
extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples);
// gets num_samples samples, not necessarily on a frame boundary--this requires
// buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES.
// Returns the number of samples stored per channel; it may be less than requested
// at the end of the file. If there are no more samples in the file, returns 0.
#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts);
extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples);
#endif
// gets num_samples samples, not necessarily on a frame boundary--this requires
// buffering so you have to supply the buffers. Applies the coercion rules above
// to produce 'channels' channels. Returns the number of samples stored per channel;
// it may be less than requested at the end of the file. If there are no more
// samples in the file, returns 0.
#endif
//////// ERROR CODES
enum STBVorbisError
{
VORBIS__no_error,
VORBIS_need_more_data=1, // not a real error
VORBIS_invalid_api_mixing, // can't mix API modes
VORBIS_outofmem, // not enough memory
VORBIS_feature_not_supported, // uses floor 0
VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small
VORBIS_file_open_failure, // fopen() failed
VORBIS_seek_without_length, // can't seek in unknown-length file
VORBIS_unexpected_eof=10, // file is truncated?
VORBIS_seek_invalid, // seek past EOF
// decoding errors (corrupt/invalid stream) -- you probably
// don't care about the exact details of these
// vorbis errors:
VORBIS_invalid_setup=20,
VORBIS_invalid_stream,
// ogg errors:
VORBIS_missing_capture_pattern=30,
VORBIS_invalid_stream_structure_version,
VORBIS_continued_packet_flag_invalid,
VORBIS_incorrect_stream_serial_number,
VORBIS_invalid_first_page,
VORBIS_bad_packet_type,
VORBIS_cant_find_last_page,
VORBIS_seek_failed,
VORBIS_ogg_skeleton_not_supported
};
#ifdef __cplusplus
}
#endif
#endif // STB_VORBIS_INCLUDE_STB_VORBIS_H
//
// HEADER ENDS HERE
//
//////////////////////////////////////////////////////////////////////////////
#ifndef STB_VORBIS_HEADER_ONLY
// global configuration settings (e.g. set these in the project/makefile),
// or just set them in this file at the top (although ideally the first few
// should be visible when the header file is compiled too, although it's not
// crucial)
// STB_VORBIS_NO_PUSHDATA_API
// does not compile the code for the various stb_vorbis_*_pushdata()
// functions
// #define STB_VORBIS_NO_PUSHDATA_API
// STB_VORBIS_NO_PULLDATA_API
// does not compile the code for the non-pushdata APIs
// #define STB_VORBIS_NO_PULLDATA_API
// STB_VORBIS_NO_STDIO
// does not compile the code for the APIs that use FILE *s internally
// or externally (implied by STB_VORBIS_NO_PULLDATA_API)
// #define STB_VORBIS_NO_STDIO
// STB_VORBIS_NO_INTEGER_CONVERSION
// does not compile the code for converting audio sample data from
// float to integer (implied by STB_VORBIS_NO_PULLDATA_API)
// #define STB_VORBIS_NO_INTEGER_CONVERSION
// STB_VORBIS_NO_FAST_SCALED_FLOAT
// does not use a fast float-to-int trick to accelerate float-to-int on
// most platforms which requires endianness be defined correctly.
//#define STB_VORBIS_NO_FAST_SCALED_FLOAT
// STB_VORBIS_MAX_CHANNELS [number]
// globally define this to the maximum number of channels you need.
// The spec does not put a restriction on channels except that
// the count is stored in a byte, so 255 is the hard limit.
// Reducing this saves about 16 bytes per value, so using 16 saves
// (255-16)*16 or around 4KB. Plus anything other memory usage
// I forgot to account for. Can probably go as low as 8 (7.1 audio),
// 6 (5.1 audio), or 2 (stereo only).
#ifndef STB_VORBIS_MAX_CHANNELS
#define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone?
#endif
// STB_VORBIS_PUSHDATA_CRC_COUNT [number]
// after a flush_pushdata(), stb_vorbis begins scanning for the
// next valid page, without backtracking. when it finds something
// that looks like a page, it streams through it and verifies its
// CRC32. Should that validation fail, it keeps scanning. But it's
// possible that _while_ streaming through to check the CRC32 of
// one candidate page, it sees another candidate page. This #define
// determines how many "overlapping" candidate pages it can search
// at once. Note that "real" pages are typically ~4KB to ~8KB, whereas
// garbage pages could be as big as 64KB, but probably average ~16KB.
// So don't hose ourselves by scanning an apparent 64KB page and
// missing a ton of real ones in the interim; so minimum of 2
#ifndef STB_VORBIS_PUSHDATA_CRC_COUNT
#define STB_VORBIS_PUSHDATA_CRC_COUNT 4
#endif
// STB_VORBIS_FAST_HUFFMAN_LENGTH [number]
// sets the log size of the huffman-acceleration table. Maximum
// supported value is 24. with larger numbers, more decodings are O(1),
// but the table size is larger so worse cache missing, so you'll have
// to probe (and try multiple ogg vorbis files) to find the sweet spot.
#ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH
#define STB_VORBIS_FAST_HUFFMAN_LENGTH 10
#endif
// STB_VORBIS_FAST_BINARY_LENGTH [number]
// sets the log size of the binary-search acceleration table. this
// is used in similar fashion to the fast-huffman size to set initial
// parameters for the binary search
// STB_VORBIS_FAST_HUFFMAN_INT
// The fast huffman tables are much more efficient if they can be
// stored as 16-bit results instead of 32-bit results. This restricts
// the codebooks to having only 65535 possible outcomes, though.
// (At least, accelerated by the huffman table.)
#ifndef STB_VORBIS_FAST_HUFFMAN_INT
#define STB_VORBIS_FAST_HUFFMAN_SHORT
#endif
// STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
// If the 'fast huffman' search doesn't succeed, then stb_vorbis falls
// back on binary searching for the correct one. This requires storing
// extra tables with the huffman codes in sorted order. Defining this
// symbol trades off space for speed by forcing a linear search in the
// non-fast case, except for "sparse" codebooks.
// #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
// STB_VORBIS_DIVIDES_IN_RESIDUE
// stb_vorbis precomputes the result of the scalar residue decoding
// that would otherwise require a divide per chunk. you can trade off
// space for time by defining this symbol.
// #define STB_VORBIS_DIVIDES_IN_RESIDUE
// STB_VORBIS_DIVIDES_IN_CODEBOOK
// vorbis VQ codebooks can be encoded two ways: with every case explicitly
// stored, or with all elements being chosen from a small range of values,
// and all values possible in all elements. By default, stb_vorbis expands
// this latter kind out to look like the former kind for ease of decoding,
// because otherwise an integer divide-per-vector-element is required to
// unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can
// trade off storage for speed.
//#define STB_VORBIS_DIVIDES_IN_CODEBOOK
#ifdef STB_VORBIS_CODEBOOK_SHORTS
#error "STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats"
#endif
// STB_VORBIS_DIVIDE_TABLE
// this replaces small integer divides in the floor decode loop with
// table lookups. made less than 1% difference, so disabled by default.
// STB_VORBIS_NO_INLINE_DECODE
// disables the inlining of the scalar codebook fast-huffman decode.
// might save a little codespace; useful for debugging
// #define STB_VORBIS_NO_INLINE_DECODE
// STB_VORBIS_NO_DEFER_FLOOR
// Normally we only decode the floor without synthesizing the actual
// full curve. We can instead synthesize the curve immediately. This
// requires more memory and is very likely slower, so I don't think
// you'd ever want to do it except for debugging.
// #define STB_VORBIS_NO_DEFER_FLOOR
//////////////////////////////////////////////////////////////////////////////
#ifdef STB_VORBIS_NO_PULLDATA_API
#define STB_VORBIS_NO_INTEGER_CONVERSION
#ifndef STB_VORBIS_NO_STDIO // OpenMPT
#define STB_VORBIS_NO_STDIO
#endif // OpenMPT
#endif
#if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
#define STB_VORBIS_NO_STDIO 1
#endif
#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
#ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
// only need endianness for fast-float-to-int, which we don't
// use for pushdata
#ifndef STB_VORBIS_BIG_ENDIAN
#define STB_VORBIS_ENDIAN 0
#else
#define STB_VORBIS_ENDIAN 1
#endif
#endif
#endif
#ifndef STB_VORBIS_NO_STDIO
#include <stdio.h>
#endif
#ifndef STB_VORBIS_NO_CRT
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <math.h>
// find definition of alloca if it's not in stdlib.h:
#if defined(_MSC_VER) || defined(__MINGW32__)
#include <malloc.h>
#endif
#if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__) || defined(__NEWLIB__)
#include <alloca.h>
#endif
#else // STB_VORBIS_NO_CRT
#define NULL 0
#define malloc(s) 0
#define free(s) ((void) 0)
#define realloc(s) 0
#endif // STB_VORBIS_NO_CRT
#include <limits.h>
#ifdef __MINGW32__
// eff you mingw:
// "fixed":
// http://sourceforge.net/p/mingw-w64/mailman/message/32882927/
// "no that broke the build, reverted, who cares about C":
// http://sourceforge.net/p/mingw-w64/mailman/message/32890381/
#ifdef __forceinline
#undef __forceinline
#endif
#define __forceinline
#if 0 // OpenMPT
#ifndef alloca
#define alloca __builtin_alloca
#endif
#endif // OpenMPT
#elif !defined(_MSC_VER)
#if __GNUC__
#define __forceinline inline
#else
#define __forceinline
#endif
#endif
#if STB_VORBIS_MAX_CHANNELS > 256
#error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range"
#endif
#if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24
#error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range"
#endif
#if 0
#include <crtdbg.h>
#define CHECK(f) _CrtIsValidHeapPointer(f->channel_buffers[1])
#else
#define CHECK(f) ((void) 0)
#endif
#define MAX_BLOCKSIZE_LOG 13 // from specification
#define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG)
typedef unsigned char uint8;
typedef signed char int8;
typedef unsigned short uint16;
typedef signed short int16;
typedef unsigned int uint32;
typedef signed int int32;
#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif
typedef float codetype;
// @NOTE
//
// Some arrays below are tagged "//varies", which means it's actually
// a variable-sized piece of data, but rather than malloc I assume it's
// small enough it's better to just allocate it all together with the
// main thing
//
// Most of the variables are specified with the smallest size I could pack
// them into. It might give better performance to make them all full-sized
// integers. It should be safe to freely rearrange the structures or change
// the sizes larger--nothing relies on silently truncating etc., nor the
// order of variables.
#define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH)
#define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1)
typedef struct
{
int dimensions, entries;
uint8 *codeword_lengths;
float minimum_value;
float delta_value;
uint8 value_bits;
uint8 lookup_type;
uint8 sequence_p;
uint8 sparse;
uint32 lookup_values;
codetype *multiplicands;
uint32 *codewords;
#ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
#else
int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
#endif
uint32 *sorted_codewords;
int *sorted_values;
int sorted_entries;
} Codebook;
typedef struct
{
uint8 order;
uint16 rate;
uint16 bark_map_size;
uint8 amplitude_bits;
uint8 amplitude_offset;
uint8 number_of_books;
uint8 book_list[16]; // varies
} Floor0;
typedef struct
{
uint8 partitions;
uint8 partition_class_list[32]; // varies
uint8 class_dimensions[16]; // varies
uint8 class_subclasses[16]; // varies
uint8 class_masterbooks[16]; // varies
int16 subclass_books[16][8]; // varies
uint16 Xlist[31*8+2]; // varies
uint8 sorted_order[31*8+2];
uint8 neighbors[31*8+2][2];
uint8 floor1_multiplier;
uint8 rangebits;
int values;
} Floor1;
typedef union
{
Floor0 floor0;
Floor1 floor1;
} Floor;
typedef struct
{
uint32 begin, end;
uint32 part_size;
uint8 classifications;
uint8 classbook;
uint8 **classdata;
int16 (*residue_books)[8];
} Residue;
typedef struct
{
uint8 magnitude;
uint8 angle;
uint8 mux;
} MappingChannel;
typedef struct
{
uint16 coupling_steps;
MappingChannel *chan;
uint8 submaps;
uint8 submap_floor[15]; // varies
uint8 submap_residue[15]; // varies
} Mapping;
typedef struct
{
uint8 blockflag;
uint8 mapping;
uint16 windowtype;
uint16 transformtype;
} Mode;
typedef struct
{
uint32 goal_crc; // expected crc if match
int bytes_left; // bytes left in packet
uint32 crc_so_far; // running crc
int bytes_done; // bytes processed in _current_ chunk
uint32 sample_loc; // granule pos encoded in page
} CRCscan;
typedef struct
{
uint32 page_start, page_end;
uint32 last_decoded_sample;
} ProbedPage;
struct stb_vorbis
{
// user-accessible info
unsigned int sample_rate;
int channels;
unsigned int setup_memory_required;
unsigned int temp_memory_required;
unsigned int setup_temp_memory_required;
char *vendor;
int comment_list_length;
char **comment_list;
// input config
#ifndef STB_VORBIS_NO_STDIO
FILE *f;
uint32 f_start;
int close_on_free;
#endif
uint8 *stream;
uint8 *stream_start;
uint8 *stream_end;
uint32 stream_len;
uint8 push_mode;
// the page to seek to when seeking to start, may be zero
uint32 first_audio_page_offset;
// p_first is the page on which the first audio packet ends
// (but not necessarily the page on which it starts)
ProbedPage p_first, p_last;
// memory management
stb_vorbis_alloc alloc;
int setup_offset;
int temp_offset;
// run-time results
int eof;
enum STBVorbisError error;
// user-useful data
// header info
int blocksize[2];
int blocksize_0, blocksize_1;
int codebook_count;
Codebook *codebooks;
int floor_count;
uint16 floor_types[64]; // varies
Floor *floor_config;
int residue_count;
uint16 residue_types[64]; // varies
Residue *residue_config;
int mapping_count;
Mapping *mapping;
int mode_count;
Mode mode_config[64]; // varies
uint32 total_samples;
// decode buffer
float *channel_buffers[STB_VORBIS_MAX_CHANNELS];
float *outputs [STB_VORBIS_MAX_CHANNELS];
float *previous_window[STB_VORBIS_MAX_CHANNELS];
int previous_length;
#ifndef STB_VORBIS_NO_DEFER_FLOOR
int16 *finalY[STB_VORBIS_MAX_CHANNELS];
#else
float *floor_buffers[STB_VORBIS_MAX_CHANNELS];
#endif
uint32 current_loc; // sample location of next frame to decode
int current_loc_valid;
// per-blocksize precomputed data
// twiddle factors
float *A[2],*B[2],*C[2];
float *window[2];
uint16 *bit_reverse[2];
// current page/packet/segment streaming info
uint32 serial; // stream serial number for verification
int last_page;
int segment_count;
uint8 segments[255];
uint8 page_flag;
uint8 bytes_in_seg;
uint8 first_decode;
int next_seg;
int last_seg; // flag that we're on the last segment
int last_seg_which; // what was the segment number of the last seg?
uint32 acc;
int valid_bits;
int packet_bytes;
int end_seg_with_known_loc;
uint32 known_loc_for_packet;
int discard_samples_deferred;
uint32 samples_output;
// push mode scanning
int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching
#ifndef STB_VORBIS_NO_PUSHDATA_API
CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT];
#endif
// sample-access
int channel_buffer_start;
int channel_buffer_end;
};
#if defined(STB_VORBIS_NO_PUSHDATA_API)
#define IS_PUSH_MODE(f) FALSE
#elif defined(STB_VORBIS_NO_PULLDATA_API)
#define IS_PUSH_MODE(f) TRUE
#else
#define IS_PUSH_MODE(f) ((f)->push_mode)
#endif
typedef struct stb_vorbis vorb;
static int error(vorb *f, enum STBVorbisError e)
{
f->error = e;
if (!f->eof && e != VORBIS_need_more_data) {
f->error=e; // breakpoint for debugging
}
return 0;
}
// these functions are used for allocating temporary memory
// while decoding. if you can afford the stack space, use
// alloca(); otherwise, provide a temp buffer and it will
// allocate out of those.
#define array_size_required(count,size) (count*(sizeof(void *)+(size)))
#if 0 // OpenMPT
#define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size))
#define temp_free(f,p) (void)0
#else // OpenMPT
#define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : malloc(size)) // OpenMPT
#define temp_free(f,p) (f->alloc.alloc_buffer ? (void)0 : free(p)) // OpenMPT
#endif // OpenMPT
#define temp_alloc_save(f) ((f)->temp_offset)
#define temp_alloc_restore(f,p) ((f)->temp_offset = (p))
#define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size)
// given a sufficiently large block of memory, make an array of pointers to subblocks of it
static void *make_block_array(void *mem, int count, int size)
{
int i;
void ** p = (void **) mem;
char *q = (char *) (p + count);
for (i=0; i < count; ++i) {
p[i] = q;
q += size;
}
return p;
}
static void *setup_malloc(vorb *f, int sz)
{
sz = (sz+7) & ~7; // round up to nearest 8 for alignment of future allocs.
f->setup_memory_required += sz;
if (f->alloc.alloc_buffer) {
void *p = (char *) f->alloc.alloc_buffer + f->setup_offset;
if (f->setup_offset + sz > f->temp_offset) return NULL;
f->setup_offset += sz;
return p;
}
return sz ? malloc(sz) : NULL;
}
static void setup_free(vorb *f, void *p)
{
if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack
free(p);
}
static void *setup_temp_malloc(vorb *f, int sz)
{
sz = (sz+7) & ~7; // round up to nearest 8 for alignment of future allocs.
if (f->alloc.alloc_buffer) {
if (f->temp_offset - sz < f->setup_offset) return NULL;
f->temp_offset -= sz;
return (char *) f->alloc.alloc_buffer + f->temp_offset;
}
return malloc(sz);
}
static void setup_temp_free(vorb *f, void *p, int sz)
{
if (f->alloc.alloc_buffer) {
f->temp_offset += (sz+7)&~7;
return;
}
free(p);
}
#define CRC32_POLY 0x04c11db7 // from spec
static uint32 crc_table[256];
static void crc32_init(void)
{
int i,j;
uint32 s;
for(i=0; i < 256; i++) {
for (s=(uint32) i << 24, j=0; j < 8; ++j)
s = (s << 1) ^ (s >= (1U<<31) ? CRC32_POLY : 0);
crc_table[i] = s;
}
}
static __forceinline uint32 crc32_update(uint32 crc, uint8 byte)
{
return (crc << 8) ^ crc_table[byte ^ (crc >> 24)];
}
// used in setup, and for huffman that doesn't go fast path
static unsigned int bit_reverse(unsigned int n)
{
n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1);
n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2);
n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4);
n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8);
return (n >> 16) | (n << 16);
}
static float square(float x)
{
return x*x;
}
// this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3
// as required by the specification. fast(?) implementation from stb.h
// @OPTIMIZE: called multiple times per-packet with "constants"; move to setup
static int ilog(int32 n)
{
static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 };
if (n < 0) return 0; // signed n returns 0
// 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29)
if (n < (1 << 14))
if (n < (1 << 4)) return 0 + log2_4[n ];
else if (n < (1 << 9)) return 5 + log2_4[n >> 5];
else return 10 + log2_4[n >> 10];
else if (n < (1 << 24))
if (n < (1 << 19)) return 15 + log2_4[n >> 15];
else return 20 + log2_4[n >> 20];
else if (n < (1 << 29)) return 25 + log2_4[n >> 25];
else return 30 + log2_4[n >> 30];
}
#ifndef M_PI
#define M_PI 3.14159265358979323846264f // from CRC
#endif
// code length assigned to a value with no huffman encoding
#define NO_CODE 255
/////////////////////// LEAF SETUP FUNCTIONS //////////////////////////
//
// these functions are only called at setup, and only a few times
// per file
static float float32_unpack(uint32 x)
{
// from the specification
uint32 mantissa = x & 0x1fffff;
uint32 sign = x & 0x80000000;
uint32 exp = (x & 0x7fe00000) >> 21;
double res = sign ? -(double)mantissa : (double)mantissa;
return (float) ldexp((float)res, exp-788);
}
// zlib & jpeg huffman tables assume that the output symbols
// can either be arbitrarily arranged, or have monotonically
// increasing frequencies--they rely on the lengths being sorted;
// this makes for a very simple generation algorithm.
// vorbis allows a huffman table with non-sorted lengths. This
// requires a more sophisticated construction, since symbols in
// order do not map to huffman codes "in order".
static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values)
{
if (!c->sparse) {
c->codewords [symbol] = huff_code;
} else {
c->codewords [count] = huff_code;
c->codeword_lengths[count] = len;
values [count] = symbol;
}
}
static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values)
{
int i,k,m=0;
uint32 available[32];
memset(available, 0, sizeof(available));
// find the first entry
for (k=0; k < n; ++k) if (len[k] < NO_CODE) break;
if (k == n) { assert(c->sorted_entries == 0); return TRUE; }
// add to the list
add_entry(c, 0, k, m++, len[k], values);
// add all available leaves
for (i=1; i <= len[k]; ++i)
available[i] = 1U << (32-i);
// note that the above code treats the first case specially,
// but it's really the same as the following code, so they
// could probably be combined (except the initial code is 0,
// and I use 0 in available[] to mean 'empty')
for (i=k+1; i < n; ++i) {
uint32 res;
int z = len[i], y;
if (z == NO_CODE) continue;
// find lowest available leaf (should always be earliest,
// which is what the specification calls for)
// note that this property, and the fact we can never have
// more than one free leaf at a given level, isn't totally
// trivial to prove, but it seems true and the assert never
// fires, so!
while (z > 0 && !available[z]) --z;
if (z == 0) { return FALSE; }
res = available[z];
assert(z >= 0 && z < 32);
available[z] = 0;
add_entry(c, bit_reverse(res), i, m++, len[i], values);
// propagate availability up the tree
if (z != len[i]) {
assert(len[i] >= 0 && len[i] < 32);
for (y=len[i]; y > z; --y) {
assert(available[y] == 0);
available[y] = res + (1 << (32-y));
}
}
}
return TRUE;
}
// accelerated huffman table allows fast O(1) match of all symbols
// of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH
static void compute_accelerated_huffman(Codebook *c)
{
int i, len;
for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i)
c->fast_huffman[i] = -1;
len = c->sparse ? c->sorted_entries : c->entries;
#ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
if (len > 32767) len = 32767; // largest possible value we can encode!
#endif
for (i=0; i < len; ++i) {
if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) {
uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i];
// set table entries for all bit combinations in the higher bits
while (z < FAST_HUFFMAN_TABLE_SIZE) {
c->fast_huffman[z] = i;
z += 1 << c->codeword_lengths[i];
}
}
}
}
#ifdef _MSC_VER
#define STBV_CDECL __cdecl
#else
#define STBV_CDECL
#endif
static int STBV_CDECL uint32_compare(const void *p, const void *q)
{
uint32 x = * (uint32 *) p;
uint32 y = * (uint32 *) q;
return x < y ? -1 : x > y;
}
static int include_in_sort(Codebook *c, uint8 len)
{
if (c->sparse) { assert(len != NO_CODE); return TRUE; }
if (len == NO_CODE) return FALSE;
if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE;
return FALSE;
}
// if the fast table above doesn't work, we want to binary
// search them... need to reverse the bits
static void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values)
{
int i, len;
// build a list of all the entries
// OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN.
// this is kind of a frivolous optimization--I don't see any performance improvement,
// but it's like 4 extra lines of code, so.
if (!c->sparse) {
int k = 0;
for (i=0; i < c->entries; ++i)
if (include_in_sort(c, lengths[i]))
c->sorted_codewords[k++] = bit_reverse(c->codewords[i]);
assert(k == c->sorted_entries);
} else {
for (i=0; i < c->sorted_entries; ++i)
c->sorted_codewords[i] = bit_reverse(c->codewords[i]);
}
qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare);
c->sorted_codewords[c->sorted_entries] = 0xffffffff;
len = c->sparse ? c->sorted_entries : c->entries;
// now we need to indicate how they correspond; we could either
// #1: sort a different data structure that says who they correspond to
// #2: for each sorted entry, search the original list to find who corresponds
// #3: for each original entry, find the sorted entry
// #1 requires extra storage, #2 is slow, #3 can use binary search!
for (i=0; i < len; ++i) {
int huff_len = c->sparse ? lengths[values[i]] : lengths[i];
if (include_in_sort(c,huff_len)) {
uint32 code = bit_reverse(c->codewords[i]);
int x=0, n=c->sorted_entries;
while (n > 1) {
// invariant: sc[x] <= code < sc[x+n]
int m = x + (n >> 1);
if (c->sorted_codewords[m] <= code) {
x = m;
n -= (n>>1);
} else {
n >>= 1;
}
}
assert(c->sorted_codewords[x] == code);
if (c->sparse) {
c->sorted_values[x] = values[i];
c->codeword_lengths[x] = huff_len;
} else {
c->sorted_values[x] = i;
}
}
}
}
// only run while parsing the header (3 times)
static int vorbis_validate(uint8 *data)
{
static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' };
return memcmp(data, vorbis, 6) == 0;
}
// called from setup only, once per code book
// (formula implied by specification)
static int lookup1_values(int entries, int dim)
{
int r = (int) floor(exp((float) log((float) entries) / dim));
if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
++r; // floor() to avoid _ftol() when non-CRT
if (pow((float) r+1, dim) <= entries)
return -1;
if ((int) floor(pow((float) r, dim)) > entries)
return -1;
return r;
}
// called twice per file
static void compute_twiddle_factors(int n, float *A, float *B, float *C)
{
int n4 = n >> 2, n8 = n >> 3;
int k,k2;
for (k=k2=0; k < n4; ++k,k2+=2) {
A[k2 ] = (float) cos(4*k*M_PI/n);
A[k2+1] = (float) -sin(4*k*M_PI/n);
B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f;
B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f;
}
for (k=k2=0; k < n8; ++k,k2+=2) {
C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
}
}
static void compute_window(int n, float *window)
{
int n2 = n >> 1, i;
for (i=0; i < n2; ++i)
window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI)));
}
static void compute_bitreverse(int n, uint16 *rev)
{
int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
int i, n8 = n >> 3;
for (i=0; i < n8; ++i)
rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2;
}
static int init_blocksize(vorb *f, int b, int n)
{
int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3;
f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2);
f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2);
f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4);
if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem);
compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]);
f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2);
if (!f->window[b]) return error(f, VORBIS_outofmem);
compute_window(n, f->window[b]);
f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8);
if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem);
compute_bitreverse(n, f->bit_reverse[b]);
return TRUE;
}
static void neighbors(uint16 *x, int n, int *plow, int *phigh)
{
int low = -1;
int high = 65536;
int i;
for (i=0; i < n; ++i) {
if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; }
if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; }
}
}
// this has been repurposed so y is now the original index instead of y
typedef struct
{
uint16 x,id;
} stbv__floor_ordering;
static int STBV_CDECL point_compare(const void *p, const void *q)
{
stbv__floor_ordering *a = (stbv__floor_ordering *) p;
stbv__floor_ordering *b = (stbv__floor_ordering *) q;
return a->x < b->x ? -1 : a->x > b->x;
}
//
/////////////////////// END LEAF SETUP FUNCTIONS //////////////////////////
#if defined(STB_VORBIS_NO_STDIO)
#define USE_MEMORY(z) TRUE
#else
#define USE_MEMORY(z) ((z)->stream)
#endif
static uint8 get8(vorb *z)
{
if (USE_MEMORY(z)) {
if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; }
return *z->stream++;
}
#ifndef STB_VORBIS_NO_STDIO
{
int c = fgetc(z->f);
if (c == EOF) { z->eof = TRUE; return 0; }
return c;
}
#endif
}
static uint32 get32(vorb *f)
{
uint32 x;
x = get8(f);
x += get8(f) << 8;
x += get8(f) << 16;
x += (uint32) get8(f) << 24;
return x;
}
static int getn(vorb *z, uint8 *data, int n)
{
if (USE_MEMORY(z)) {
if (z->stream+n > z->stream_end) { z->eof = 1; return 0; }
memcpy(data, z->stream, n);
z->stream += n;
return 1;
}
#ifndef STB_VORBIS_NO_STDIO
if (fread(data, n, 1, z->f) == 1)
return 1;
else {
z->eof = 1;
return 0;
}
#endif
}
static void skip(vorb *z, int n)
{
if (USE_MEMORY(z)) {
z->stream += n;
if (z->stream >= z->stream_end) z->eof = 1;
return;
}
#ifndef STB_VORBIS_NO_STDIO
{
long x = ftell(z->f);
fseek(z->f, x+n, SEEK_SET);
}
#endif
}
static int set_file_offset(stb_vorbis *f, unsigned int loc)
{
#ifndef STB_VORBIS_NO_PUSHDATA_API
if (f->push_mode) return 0;
#endif
f->eof = 0;
if (USE_MEMORY(f)) {
if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) {
f->stream = f->stream_end;
f->eof = 1;
return 0;
} else {
f->stream = f->stream_start + loc;
return 1;
}
}
#ifndef STB_VORBIS_NO_STDIO
if (loc + f->f_start < loc || loc >= 0x80000000) {
loc = 0x7fffffff;
f->eof = 1;
} else {
loc += f->f_start;
}
if (!fseek(f->f, loc, SEEK_SET))
return 1;
f->eof = 1;
fseek(f->f, f->f_start, SEEK_END);
return 0;
#endif
}
static uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 };
static int capture_pattern(vorb *f)
{
if (0x4f != get8(f)) return FALSE;
if (0x67 != get8(f)) return FALSE;
if (0x67 != get8(f)) return FALSE;
if (0x53 != get8(f)) return FALSE;
return TRUE;
}
#define PAGEFLAG_continued_packet 1
#define PAGEFLAG_first_page 2
#define PAGEFLAG_last_page 4
static int start_page_no_capturepattern(vorb *f)
{
uint32 loc0,loc1,n;
if (f->first_decode && !IS_PUSH_MODE(f)) {
f->p_first.page_start = stb_vorbis_get_file_offset(f) - 4;
}
// stream structure version
if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version);
// header flag
f->page_flag = get8(f);
// absolute granule position
loc0 = get32(f);
loc1 = get32(f);
// @TODO: validate loc0,loc1 as valid positions?
// stream serial number -- vorbis doesn't interleave, so discard
get32(f);
//if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number);
// page sequence number
n = get32(f);
f->last_page = n;
// CRC32
get32(f);
// page_segments
f->segment_count = get8(f);
if (!getn(f, f->segments, f->segment_count))
return error(f, VORBIS_unexpected_eof);
// assume we _don't_ know any the sample position of any segments
f->end_seg_with_known_loc = -2;
if (loc0 != ~0U || loc1 != ~0U) {
int i;
// determine which packet is the last one that will complete
for (i=f->segment_count-1; i >= 0; --i)
if (f->segments[i] < 255)
break;
// 'i' is now the index of the _last_ segment of a packet that ends
if (i >= 0) {
f->end_seg_with_known_loc = i;
f->known_loc_for_packet = loc0;
}
}
if (f->first_decode) {
int i,len;
len = 0;
for (i=0; i < f->segment_count; ++i)
len += f->segments[i];
len += 27 + f->segment_count;
f->p_first.page_end = f->p_first.page_start + len;
f->p_first.last_decoded_sample = loc0;
}
f->next_seg = 0;
return TRUE;
}
static int start_page(vorb *f)
{
if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern);
return start_page_no_capturepattern(f);
}
static int start_packet(vorb *f)
{
while (f->next_seg == -1) {
if (!start_page(f)) return FALSE;
if (f->page_flag & PAGEFLAG_continued_packet)
return error(f, VORBIS_continued_packet_flag_invalid);
}
f->last_seg = FALSE;
f->valid_bits = 0;
f->packet_bytes = 0;
f->bytes_in_seg = 0;
// f->next_seg is now valid
return TRUE;
}
static int maybe_start_packet(vorb *f)
{
if (f->next_seg == -1) {
int x = get8(f);
if (f->eof) return FALSE; // EOF at page boundary is not an error!
if (0x4f != x ) return error(f, VORBIS_missing_capture_pattern);
if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
if (!start_page_no_capturepattern(f)) return FALSE;
if (f->page_flag & PAGEFLAG_continued_packet) {
// set up enough state that we can read this packet if we want,
// e.g. during recovery
f->last_seg = FALSE;
f->bytes_in_seg = 0;
return error(f, VORBIS_continued_packet_flag_invalid);
}
}
return start_packet(f);
}
static int next_segment(vorb *f)
{
int len;
if (f->last_seg) return 0;
if (f->next_seg == -1) {
f->last_seg_which = f->segment_count-1; // in case start_page fails
if (!start_page(f)) { f->last_seg = 1; return 0; }
if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid);
}
len = f->segments[f->next_seg++];
if (len < 255) {
f->last_seg = TRUE;
f->last_seg_which = f->next_seg-1;
}
if (f->next_seg >= f->segment_count)
f->next_seg = -1;
assert(f->bytes_in_seg == 0);
f->bytes_in_seg = len;
return len;
}
#define EOP (-1)
#define INVALID_BITS (-1)
static int get8_packet_raw(vorb *f)
{
if (!f->bytes_in_seg) { // CLANG!
if (f->last_seg) return EOP;
else if (!next_segment(f)) return EOP;
}
assert(f->bytes_in_seg > 0);
--f->bytes_in_seg;
++f->packet_bytes;
return get8(f);
}
static int get8_packet(vorb *f)
{
int x = get8_packet_raw(f);
f->valid_bits = 0;
return x;
}
static int get32_packet(vorb *f)
{
uint32 x;
x = get8_packet(f);
x += get8_packet(f) << 8;
x += get8_packet(f) << 16;
x += (uint32) get8_packet(f) << 24;
return x;
}
static void flush_packet(vorb *f)
{
while (get8_packet_raw(f) != EOP);
}
// @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important
// as the huffman decoder?
static uint32 get_bits(vorb *f, int n)
{
uint32 z;
if (f->valid_bits < 0) return 0;
if (f->valid_bits < n) {
if (n > 24) {
// the accumulator technique below would not work correctly in this case
z = get_bits(f, 24);
z += get_bits(f, n-24) << 24;
return z;
}
if (f->valid_bits == 0) f->acc = 0;
while (f->valid_bits < n) {
int z = get8_packet_raw(f);
if (z == EOP) {
f->valid_bits = INVALID_BITS;
return 0;
}
f->acc += z << f->valid_bits;
f->valid_bits += 8;
}
}
assert(f->valid_bits >= n);
z = f->acc & ((1 << n)-1);
f->acc >>= n;
f->valid_bits -= n;
return z;
}
// @OPTIMIZE: primary accumulator for huffman
// expand the buffer to as many bits as possible without reading off end of packet
// it might be nice to allow f->valid_bits and f->acc to be stored in registers,
// e.g. cache them locally and decode locally
static __forceinline void prep_huffman(vorb *f)
{
if (f->valid_bits <= 24) {
if (f->valid_bits == 0) f->acc = 0;
do {
int z;
if (f->last_seg && !f->bytes_in_seg) return;
z = get8_packet_raw(f);
if (z == EOP) return;
f->acc += (unsigned) z << f->valid_bits;
f->valid_bits += 8;
} while (f->valid_bits <= 24);
}
}
enum
{
VORBIS_packet_id = 1,
VORBIS_packet_comment = 3,
VORBIS_packet_setup = 5
};
static int codebook_decode_scalar_raw(vorb *f, Codebook *c)
{
int i;
prep_huffman(f);
if (c->codewords == NULL && c->sorted_codewords == NULL)
return -1;
// cases to use binary search: sorted_codewords && !c->codewords
// sorted_codewords && c->entries > 8
if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) {
// binary search
uint32 code = bit_reverse(f->acc);
int x=0, n=c->sorted_entries, len;
while (n > 1) {
// invariant: sc[x] <= code < sc[x+n]
int m = x + (n >> 1);
if (c->sorted_codewords[m] <= code) {
x = m;
n -= (n>>1);
} else {
n >>= 1;
}
}
// x is now the sorted index
if (!c->sparse) x = c->sorted_values[x];
// x is now sorted index if sparse, or symbol otherwise
len = c->codeword_lengths[x];
if (f->valid_bits >= len) {
f->acc >>= len;
f->valid_bits -= len;
return x;
}
f->valid_bits = 0;
return -1;
}
// if small, linear search
assert(!c->sparse);
for (i=0; i < c->entries; ++i) {
if (c->codeword_lengths[i] == NO_CODE) continue;
if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) {
if (f->valid_bits >= c->codeword_lengths[i]) {
f->acc >>= c->codeword_lengths[i];
f->valid_bits -= c->codeword_lengths[i];
return i;
}
f->valid_bits = 0;
return -1;
}
}
error(f, VORBIS_invalid_stream);
f->valid_bits = 0;
return -1;
}
#ifndef STB_VORBIS_NO_INLINE_DECODE
#define DECODE_RAW(var, f,c) \
if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \
prep_huffman(f); \
var = f->acc & FAST_HUFFMAN_TABLE_MASK; \
var = c->fast_huffman[var]; \
if (var >= 0) { \
int n = c->codeword_lengths[var]; \
f->acc >>= n; \
f->valid_bits -= n; \
if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \
} else { \
var = codebook_decode_scalar_raw(f,c); \
}
#else
static int codebook_decode_scalar(vorb *f, Codebook *c)
{
int i;
if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH)
prep_huffman(f);
// fast huffman table lookup
i = f->acc & FAST_HUFFMAN_TABLE_MASK;
i = c->fast_huffman[i];
if (i >= 0) {
f->acc >>= c->codeword_lengths[i];
f->valid_bits -= c->codeword_lengths[i];
if (f->valid_bits < 0) { f->valid_bits = 0; return -1; }
return i;
}
return codebook_decode_scalar_raw(f,c);
}
#define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c);
#endif
#define DECODE(var,f,c) \
DECODE_RAW(var,f,c) \
if (c->sparse) var = c->sorted_values[var];
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
#define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c)
#else
#define DECODE_VQ(var,f,c) DECODE(var,f,c)
#endif
// CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case
// where we avoid one addition
#define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off])
#define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off])
#define CODEBOOK_ELEMENT_BASE(c) (0)
static int codebook_decode_start(vorb *f, Codebook *c)
{
int z = -1;
// type 0 is only legal in a scalar context
if (c->lookup_type == 0)
error(f, VORBIS_invalid_stream);
else {
DECODE_VQ(z,f,c);
if (c->sparse) assert(z < c->sorted_entries);
if (z < 0) { // check for EOP
if (!f->bytes_in_seg)
if (f->last_seg)
return z;
error(f, VORBIS_invalid_stream);
}
}
return z;
}
static int codebook_decode(vorb *f, Codebook *c, float *output, int len)
{
int i,z = codebook_decode_start(f,c);
if (z < 0) return FALSE;
if (len > c->dimensions) len = c->dimensions;
#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
float last = CODEBOOK_ELEMENT_BASE(c);
int div = 1;
for (i=0; i < len; ++i) {
int off = (z / div) % c->lookup_values;
float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
output[i] += val;
if (c->sequence_p) last = val + c->minimum_value;
div *= c->lookup_values;
}
return TRUE;
}
#endif
z *= c->dimensions;
if (c->sequence_p) {
float last = CODEBOOK_ELEMENT_BASE(c);
for (i=0; i < len; ++i) {
float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
output[i] += val;
last = val + c->minimum_value;
}
} else {
float last = CODEBOOK_ELEMENT_BASE(c);
for (i=0; i < len; ++i) {
output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last;
}
}
return TRUE;
}
static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step)
{
int i,z = codebook_decode_start(f,c);
float last = CODEBOOK_ELEMENT_BASE(c);
if (z < 0) return FALSE;
if (len > c->dimensions) len = c->dimensions;
#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
int div = 1;
for (i=0; i < len; ++i) {
int off = (z / div) % c->lookup_values;
float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
output[i*step] += val;
if (c->sequence_p) last = val;
div *= c->lookup_values;
}
return TRUE;
}
#endif
z *= c->dimensions;
for (i=0; i < len; ++i) {
float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
output[i*step] += val;
if (c->sequence_p) last = val;
}
return TRUE;
}
static int codebook_decode_deinterleave_repeat(vorb *f, Codebook *c, float **outputs, int ch, int *c_inter_p, int *p_inter_p, int len, int total_decode)
{
int c_inter = *c_inter_p;
int p_inter = *p_inter_p;
int i,z, effective = c->dimensions;
// type 0 is only legal in a scalar context
if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream);
while (total_decode > 0) {
float last = CODEBOOK_ELEMENT_BASE(c);
DECODE_VQ(z,f,c);
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
assert(!c->sparse || z < c->sorted_entries);
#endif
if (z < 0) {
if (!f->bytes_in_seg)
if (f->last_seg) return FALSE;
return error(f, VORBIS_invalid_stream);
}
// if this will take us off the end of the buffers, stop short!
// we check by computing the length of the virtual interleaved
// buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter),
// and the length we'll be using (effective)
if (c_inter + p_inter*ch + effective > len * ch) {
effective = len*ch - (p_inter*ch - c_inter);
}
#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
int div = 1;
for (i=0; i < effective; ++i) {
int off = (z / div) % c->lookup_values;
float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
if (outputs[c_inter])
outputs[c_inter][p_inter] += val;
if (++c_inter == ch) { c_inter = 0; ++p_inter; }
if (c->sequence_p) last = val;
div *= c->lookup_values;
}
} else
#endif
{
z *= c->dimensions;
if (c->sequence_p) {
for (i=0; i < effective; ++i) {
float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
if (outputs[c_inter])
outputs[c_inter][p_inter] += val;
if (++c_inter == ch) { c_inter = 0; ++p_inter; }
last = val;
}
} else {
for (i=0; i < effective; ++i) {
float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
if (outputs[c_inter])
outputs[c_inter][p_inter] += val;
if (++c_inter == ch) { c_inter = 0; ++p_inter; }
}
}
}
total_decode -= effective;
}
*c_inter_p = c_inter;
*p_inter_p = p_inter;
return TRUE;
}
static int predict_point(int x, int x0, int x1, int y0, int y1)
{
int dy = y1 - y0;
int adx = x1 - x0;
// @OPTIMIZE: force int division to round in the right direction... is this necessary on x86?
int err = abs(dy) * (x - x0);
int off = err / adx;
return dy < 0 ? y0 - off : y0 + off;
}
// the following table is block-copied from the specification
static float inverse_db_table[256] =
{
1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f,
1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f,
1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f,
2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f,
2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f,
3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f,
4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f,
6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f,
7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f,
1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f,
1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f,
1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f,
2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f,
2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f,
3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f,
4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f,
5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f,
7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f,
9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f,
1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f,
1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f,
2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f,
2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f,
3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f,
4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f,
5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f,
7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f,
9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f,
0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f,
0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f,
0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f,
0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f,
0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f,
0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f,
0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f,
0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f,
0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f,
0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f,
0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f,
0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f,
0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f,
0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f,
0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f,
0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f,
0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f,
0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f,
0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f,
0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f,
0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f,
0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f,
0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f,
0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f,
0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f,
0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f,
0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f,
0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f,
0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f,
0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f,
0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f,
0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f,
0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f,
0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f,
0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f,
0.82788260f, 0.88168307f, 0.9389798f, 1.0f
};
// @OPTIMIZE: if you want to replace this bresenham line-drawing routine,
// note that you must produce bit-identical output to decode correctly;
// this specific sequence of operations is specified in the spec (it's
// drawing integer-quantized frequency-space lines that the encoder
// expects to be exactly the same)
// ... also, isn't the whole point of Bresenham's algorithm to NOT
// have to divide in the setup? sigh.
#ifndef STB_VORBIS_NO_DEFER_FLOOR
#define LINE_OP(a,b) a *= b
#else
#define LINE_OP(a,b) a = b
#endif
#ifdef STB_VORBIS_DIVIDE_TABLE
#define DIVTAB_NUMER 32
#define DIVTAB_DENOM 64
int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB
#endif
static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)
{
int dy = y1 - y0;
int adx = x1 - x0;
int ady = abs(dy);
int base;
int x=x0,y=y0;
int err = 0;
int sy;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {
if (dy < 0) {
base = -integer_divide_table[ady][adx];
sy = base-1;
} else {
base = integer_divide_table[ady][adx];
sy = base+1;
}
} else {
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
}
#else
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
#endif
ady -= abs(base) * adx;
if (x1 > n) x1 = n;
if (x < x1) {
LINE_OP(output[x], inverse_db_table[y&255]);
for (++x; x < x1; ++x) {
err += ady;
if (err >= adx) {
err -= adx;
y += sy;
} else
y += base;
LINE_OP(output[x], inverse_db_table[y&255]);
}
}
}
static int residue_decode(vorb *f, Codebook *book, float *target, int offset, int n, int rtype)
{
int k;
if (rtype == 0) {
int step = n / book->dimensions;
for (k=0; k < step; ++k)
if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step))
return FALSE;
} else {
for (k=0; k < n; ) {
if (!codebook_decode(f, book, target+offset, n-k))
return FALSE;
k += book->dimensions;
offset += book->dimensions;
}
}
return TRUE;
}
// n is 1/2 of the blocksize --
// specification: "Correct per-vector decode length is [n]/2"
static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode)
{
int i,j,pass;
Residue *r = f->residue_config + rn;
int rtype = f->residue_types[rn];
int c = r->classbook;
int classwords = f->codebooks[c].dimensions;
unsigned int actual_size = rtype == 2 ? n*2 : n;
unsigned int limit_r_begin = (r->begin < actual_size ? r->begin : actual_size);
unsigned int limit_r_end = (r->end < actual_size ? r->end : actual_size);
int n_read = limit_r_end - limit_r_begin;
int part_read = n_read / r->part_size;
int temp_alloc_point = temp_alloc_save(f);
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata));
#else
int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications));
#endif
CHECK(f);
for (i=0; i < ch; ++i)
if (!do_not_decode[i])
memset(residue_buffers[i], 0, sizeof(float) * n);
if (rtype == 2 && ch != 1) {
for (j=0; j < ch; ++j)
if (!do_not_decode[j])
break;
if (j == ch)
goto done;
for (pass=0; pass < 8; ++pass) {
int pcount = 0, class_set = 0;
if (ch == 2) {
while (pcount < part_read) {
int z = r->begin + pcount*r->part_size;
int c_inter = (z & 1), p_inter = z>>1;
if (pass == 0) {
Codebook *c = f->codebooks+r->classbook;
int q;
DECODE(q,f,c);
if (q == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[0][class_set] = r->classdata[q];
#else
for (i=classwords-1; i >= 0; --i) {
classifications[0][i+pcount] = q % r->classifications;
q /= r->classifications;
}
#endif
}
for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
int z = r->begin + pcount*r->part_size;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[0][class_set][i];
#else
int c = classifications[0][pcount];
#endif
int b = r->residue_books[c][pass];
if (b >= 0) {
Codebook *book = f->codebooks + b;
#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
goto done;
#else
// saves 1%
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
goto done;
#endif
} else {
z += r->part_size;
c_inter = z & 1;
p_inter = z >> 1;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
} else if (ch > 2) {
while (pcount < part_read) {
int z = r->begin + pcount*r->part_size;
int c_inter = z % ch, p_inter = z/ch;
if (pass == 0) {
Codebook *c = f->codebooks+r->classbook;
int q;
DECODE(q,f,c);
if (q == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[0][class_set] = r->classdata[q];
#else
for (i=classwords-1; i >= 0; --i) {
classifications[0][i+pcount] = q % r->classifications;
q /= r->classifications;
}
#endif
}
for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
int z = r->begin + pcount*r->part_size;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[0][class_set][i];
#else
int c = classifications[0][pcount];
#endif
int b = r->residue_books[c][pass];
if (b >= 0) {
Codebook *book = f->codebooks + b;
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
goto done;
} else {
z += r->part_size;
c_inter = z % ch;
p_inter = z / ch;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
}
}
goto done;
}
CHECK(f);
for (pass=0; pass < 8; ++pass) {
int pcount = 0, class_set=0;
while (pcount < part_read) {
if (pass == 0) {
for (j=0; j < ch; ++j) {
if (!do_not_decode[j]) {
Codebook *c = f->codebooks+r->classbook;
int temp;
DECODE(temp,f,c);
if (temp == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[j][class_set] = r->classdata[temp];
#else
for (i=classwords-1; i >= 0; --i) {
classifications[j][i+pcount] = temp % r->classifications;
temp /= r->classifications;
}
#endif
}
}
}
for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
for (j=0; j < ch; ++j) {
if (!do_not_decode[j]) {
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[j][class_set][i];
#else
int c = classifications[j][pcount];
#endif
int b = r->residue_books[c][pass];
if (b >= 0) {
float *target = residue_buffers[j];
int offset = r->begin + pcount * r->part_size;
int n = r->part_size;
Codebook *book = f->codebooks + b;
if (!residue_decode(f, book, target, offset, n, rtype))
goto done;
}
}
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
}
done:
CHECK(f);
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
temp_free(f,part_classdata);
#else
temp_free(f,classifications);
#endif
temp_alloc_restore(f,temp_alloc_point);
}
#if 0
// slow way for debugging
void inverse_mdct_slow(float *buffer, int n)
{
int i,j;
int n2 = n >> 1;
float *x = (float *) malloc(sizeof(*x) * n2);
memcpy(x, buffer, sizeof(*x) * n2);
for (i=0; i < n; ++i) {
float acc = 0;
for (j=0; j < n2; ++j)
// formula from paper:
//acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
// formula from wikipedia
//acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
// these are equivalent, except the formula from the paper inverts the multiplier!
// however, what actually works is NO MULTIPLIER!?!
//acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
buffer[i] = acc;
}
free(x);
}
#elif 0
// same as above, but just barely able to run in real time on modern machines
void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)
{
float mcos[16384];
int i,j;
int n2 = n >> 1, nmask = (n << 2) -1;
float *x = (float *) malloc(sizeof(*x) * n2);
memcpy(x, buffer, sizeof(*x) * n2);
for (i=0; i < 4*n; ++i)
mcos[i] = (float) cos(M_PI / 2 * i / n);
for (i=0; i < n; ++i) {
float acc = 0;
for (j=0; j < n2; ++j)
acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask];
buffer[i] = acc;
}
free(x);
}
#elif 0
// transform to use a slow dct-iv; this is STILL basically trivial,
// but only requires half as many ops
void dct_iv_slow(float *buffer, int n)
{
float mcos[16384];
float x[2048];
int i,j;
int n2 = n >> 1, nmask = (n << 3) - 1;
memcpy(x, buffer, sizeof(*x) * n);
for (i=0; i < 8*n; ++i)
mcos[i] = (float) cos(M_PI / 4 * i / n);
for (i=0; i < n; ++i) {
float acc = 0;
for (j=0; j < n; ++j)
acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask];
buffer[i] = acc;
}
}
void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)
{
int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4;
float temp[4096];
memcpy(temp, buffer, n2 * sizeof(float));
dct_iv_slow(temp, n2); // returns -c'-d, a-b'
for (i=0; i < n4 ; ++i) buffer[i] = temp[i+n4]; // a-b'
for ( ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d'
for ( ; i < n ; ++i) buffer[i] = -temp[i - n3_4]; // c'+d
}
#endif
#ifndef LIBVORBIS_MDCT
#define LIBVORBIS_MDCT 0
#endif
#if LIBVORBIS_MDCT
// directly call the vorbis MDCT using an interface documented
// by Jeff Roberts... useful for performance comparison
typedef struct
{
int n;
int log2n;
float *trig;
int *bitrev;
float scale;
} mdct_lookup;
extern void mdct_init(mdct_lookup *lookup, int n);
extern void mdct_clear(mdct_lookup *l);
extern void mdct_backward(mdct_lookup *init, float *in, float *out);
mdct_lookup M1,M2;
void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)
{
mdct_lookup *M;
if (M1.n == n) M = &M1;
else if (M2.n == n) M = &M2;
else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; }
else {
if (M2.n) __asm int 3;
mdct_init(&M2, n);
M = &M2;
}
mdct_backward(M, buffer, buffer);
}
#endif
// the following were split out into separate functions while optimizing;
// they could be pushed back up but eh. __forceinline showed no change;
// they're probably already being inlined.
static void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A)
{
float *ee0 = e + i_off;
float *ee2 = ee0 + k_off;
int i;
assert((n & 3) == 0);
for (i=(n>>2); i > 0; --i) {
float k00_20, k01_21;
k00_20 = ee0[ 0] - ee2[ 0];
k01_21 = ee0[-1] - ee2[-1];
ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0] + ee2[ 0];
ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1];
ee2[ 0] = k00_20 * A[0] - k01_21 * A[1];
ee2[-1] = k01_21 * A[0] + k00_20 * A[1];
A += 8;
k00_20 = ee0[-2] - ee2[-2];
k01_21 = ee0[-3] - ee2[-3];
ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2];
ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3];
ee2[-2] = k00_20 * A[0] - k01_21 * A[1];
ee2[-3] = k01_21 * A[0] + k00_20 * A[1];
A += 8;
k00_20 = ee0[-4] - ee2[-4];
k01_21 = ee0[-5] - ee2[-5];
ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4];
ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5];
ee2[-4] = k00_20 * A[0] - k01_21 * A[1];
ee2[-5] = k01_21 * A[0] + k00_20 * A[1];
A += 8;
k00_20 = ee0[-6] - ee2[-6];
k01_21 = ee0[-7] - ee2[-7];
ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6];
ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7];
ee2[-6] = k00_20 * A[0] - k01_21 * A[1];
ee2[-7] = k01_21 * A[0] + k00_20 * A[1];
A += 8;
ee0 -= 8;
ee2 -= 8;
}
}
static void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1)
{
int i;
float k00_20, k01_21;
float *e0 = e + d0;
float *e2 = e0 + k_off;
for (i=lim >> 2; i > 0; --i) {
k00_20 = e0[-0] - e2[-0];
k01_21 = e0[-1] - e2[-1];
e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0];
e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1];
e2[-0] = (k00_20)*A[0] - (k01_21) * A[1];
e2[-1] = (k01_21)*A[0] + (k00_20) * A[1];
A += k1;
k00_20 = e0[-2] - e2[-2];
k01_21 = e0[-3] - e2[-3];
e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2];
e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3];
e2[-2] = (k00_20)*A[0] - (k01_21) * A[1];
e2[-3] = (k01_21)*A[0] + (k00_20) * A[1];
A += k1;
k00_20 = e0[-4] - e2[-4];
k01_21 = e0[-5] - e2[-5];
e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4];
e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5];
e2[-4] = (k00_20)*A[0] - (k01_21) * A[1];
e2[-5] = (k01_21)*A[0] + (k00_20) * A[1];
A += k1;
k00_20 = e0[-6] - e2[-6];
k01_21 = e0[-7] - e2[-7];
e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6];
e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7];
e2[-6] = (k00_20)*A[0] - (k01_21) * A[1];
e2[-7] = (k01_21)*A[0] + (k00_20) * A[1];
e0 -= 8;
e2 -= 8;
A += k1;
}
}
static void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0)
{
int i;
float A0 = A[0];
float A1 = A[0+1];
float A2 = A[0+a_off];
float A3 = A[0+a_off+1];
float A4 = A[0+a_off*2+0];
float A5 = A[0+a_off*2+1];
float A6 = A[0+a_off*3+0];
float A7 = A[0+a_off*3+1];
float k00,k11;
float *ee0 = e +i_off;
float *ee2 = ee0+k_off;
for (i=n; i > 0; --i) {
k00 = ee0[ 0] - ee2[ 0];
k11 = ee0[-1] - ee2[-1];
ee0[ 0] = ee0[ 0] + ee2[ 0];
ee0[-1] = ee0[-1] + ee2[-1];
ee2[ 0] = (k00) * A0 - (k11) * A1;
ee2[-1] = (k11) * A0 + (k00) * A1;
k00 = ee0[-2] - ee2[-2];
k11 = ee0[-3] - ee2[-3];
ee0[-2] = ee0[-2] + ee2[-2];
ee0[-3] = ee0[-3] + ee2[-3];
ee2[-2] = (k00) * A2 - (k11) * A3;
ee2[-3] = (k11) * A2 + (k00) * A3;
k00 = ee0[-4] - ee2[-4];
k11 = ee0[-5] - ee2[-5];
ee0[-4] = ee0[-4] + ee2[-4];
ee0[-5] = ee0[-5] + ee2[-5];
ee2[-4] = (k00) * A4 - (k11) * A5;
ee2[-5] = (k11) * A4 + (k00) * A5;
k00 = ee0[-6] - ee2[-6];
k11 = ee0[-7] - ee2[-7];
ee0[-6] = ee0[-6] + ee2[-6];
ee0[-7] = ee0[-7] + ee2[-7];
ee2[-6] = (k00) * A6 - (k11) * A7;
ee2[-7] = (k11) * A6 + (k00) * A7;
ee0 -= k0;
ee2 -= k0;
}
}
static __forceinline void iter_54(float *z)
{
float k00,k11,k22,k33;
float y0,y1,y2,y3;
k00 = z[ 0] - z[-4];
y0 = z[ 0] + z[-4];
y2 = z[-2] + z[-6];
k22 = z[-2] - z[-6];
z[-0] = y0 + y2; // z0 + z4 + z2 + z6
z[-2] = y0 - y2; // z0 + z4 - z2 - z6
// done with y0,y2
k33 = z[-3] - z[-7];
z[-4] = k00 + k33; // z0 - z4 + z3 - z7
z[-6] = k00 - k33; // z0 - z4 - z3 + z7
// done with k33
k11 = z[-1] - z[-5];
y1 = z[-1] + z[-5];
y3 = z[-3] + z[-7];
z[-1] = y1 + y3; // z1 + z5 + z3 + z7
z[-3] = y1 - y3; // z1 + z5 - z3 - z7
z[-5] = k11 - k22; // z1 - z5 + z2 - z6
z[-7] = k11 + k22; // z1 - z5 - z2 + z6
}
static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n)
{
int a_off = base_n >> 3;
float A2 = A[0+a_off];
float *z = e + i_off;
float *base = z - 16 * n;
while (z > base) {
float k00,k11;
k00 = z[-0] - z[-8];
k11 = z[-1] - z[-9];
z[-0] = z[-0] + z[-8];
z[-1] = z[-1] + z[-9];
z[-8] = k00;
z[-9] = k11 ;
k00 = z[ -2] - z[-10];
k11 = z[ -3] - z[-11];
z[ -2] = z[ -2] + z[-10];
z[ -3] = z[ -3] + z[-11];
z[-10] = (k00+k11) * A2;
z[-11] = (k11-k00) * A2;
k00 = z[-12] - z[ -4]; // reverse to avoid a unary negation
k11 = z[ -5] - z[-13];
z[ -4] = z[ -4] + z[-12];
z[ -5] = z[ -5] + z[-13];
z[-12] = k11;
z[-13] = k00;
k00 = z[-14] - z[ -6]; // reverse to avoid a unary negation
k11 = z[ -7] - z[-15];
z[ -6] = z[ -6] + z[-14];
z[ -7] = z[ -7] + z[-15];
z[-14] = (k00+k11) * A2;
z[-15] = (k00-k11) * A2;
iter_54(z);
iter_54(z-8);
z -= 16;
}
}
static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)
{
int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
int ld;
// @OPTIMIZE: reduce register pressure by using fewer variables?
int save_point = temp_alloc_save(f);
float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2));
float *u=NULL,*v=NULL;
// twiddle factors
float *A = f->A[blocktype];
// IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
// See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function.
// kernel from paper
// merged:
// copy and reflect spectral data
// step 0
// note that it turns out that the items added together during
// this step are, in fact, being added to themselves (as reflected
// by step 0). inexplicable inefficiency! this became obvious
// once I combined the passes.
// so there's a missing 'times 2' here (for adding X to itself).
// this propagates through linearly to the end, where the numbers
// are 1/2 too small, and need to be compensated for.
{
float *d,*e, *AA, *e_stop;
d = &buf2[n2-2];
AA = A;
e = &buffer[0];
e_stop = &buffer[n2];
while (e != e_stop) {
d[1] = (e[0] * AA[0] - e[2]*AA[1]);
d[0] = (e[0] * AA[1] + e[2]*AA[0]);
d -= 2;
AA += 2;
e += 4;
}
e = &buffer[n2-3];
while (d >= buf2) {
d[1] = (-e[2] * AA[0] - -e[0]*AA[1]);
d[0] = (-e[2] * AA[1] + -e[0]*AA[0]);
d -= 2;
AA += 2;
e -= 4;
}
}
// now we use symbolic names for these, so that we can
// possibly swap their meaning as we change which operations
// are in place
u = buffer;
v = buf2;
// step 2 (paper output is w, now u)
// this could be in place, but the data ends up in the wrong
// place... _somebody_'s got to swap it, so this is nominated
{
float *AA = &A[n2-8];
float *d0,*d1, *e0, *e1;
e0 = &v[n4];
e1 = &v[0];
d0 = &u[n4];
d1 = &u[0];
while (AA >= A) {
float v40_20, v41_21;
v41_21 = e0[1] - e1[1];
v40_20 = e0[0] - e1[0];
d0[1] = e0[1] + e1[1];
d0[0] = e0[0] + e1[0];
d1[1] = v41_21*AA[4] - v40_20*AA[5];
d1[0] = v40_20*AA[4] + v41_21*AA[5];
v41_21 = e0[3] - e1[3];
v40_20 = e0[2] - e1[2];
d0[3] = e0[3] + e1[3];
d0[2] = e0[2] + e1[2];
d1[3] = v41_21*AA[0] - v40_20*AA[1];
d1[2] = v40_20*AA[0] + v41_21*AA[1];
AA -= 8;
d0 += 4;
d1 += 4;
e0 += 4;
e1 += 4;
}
}
// step 3
ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
// optimized step 3:
// the original step3 loop can be nested r inside s or s inside r;
// it's written originally as s inside r, but this is dumb when r
// iterates many times, and s few. So I have two copies of it and
// switch between them halfway.
// this is iteration 0 of step 3
imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A);
imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A);
// this is iteration 1 of step 3
imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16);
imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16);
imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16);
imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16);
l=2;
for (; l < (ld-3)>>1; ++l) {
int k0 = n >> (l+2), k0_2 = k0>>1;
int lim = 1 << (l+1);
int i;
for (i=0; i < lim; ++i)
imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3));
}
for (; l < ld-6; ++l) {
int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1;
int rlim = n >> (l+6), r;
int lim = 1 << (l+1);
int i_off;
float *A0 = A;
i_off = n2-1;
for (r=rlim; r > 0; --r) {
imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0);
A0 += k1*4;
i_off -= 8;
}
}
// iterations with count:
// ld-6,-5,-4 all interleaved together
// the big win comes from getting rid of needless flops
// due to the constants on pass 5 & 4 being all 1 and 0;
// combining them to be simultaneous to improve cache made little difference
imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n);
// output is u
// step 4, 5, and 6
// cannot be in-place because of step 5
{
uint16 *bitrev = f->bit_reverse[blocktype];
// weirdly, I'd have thought reading sequentially and writing
// erratically would have been better than vice-versa, but in
// fact that's not what my testing showed. (That is, with
// j = bitreverse(i), do you read i and write j, or read j and write i.)
float *d0 = &v[n4-4];
float *d1 = &v[n2-4];
while (d0 >= v) {
int k4;
k4 = bitrev[0];
d1[3] = u[k4+0];
d1[2] = u[k4+1];
d0[3] = u[k4+2];
d0[2] = u[k4+3];
k4 = bitrev[1];
d1[1] = u[k4+0];
d1[0] = u[k4+1];
d0[1] = u[k4+2];
d0[0] = u[k4+3];
d0 -= 4;
d1 -= 4;
bitrev += 2;
}
}
// (paper output is u, now v)
// data must be in buf2
assert(v == buf2);
// step 7 (paper output is v, now v)
// this is now in place
{
float *C = f->C[blocktype];
float *d, *e;
d = v;
e = v + n2 - 4;
while (d < e) {
float a02,a11,b0,b1,b2,b3;
a02 = d[0] - e[2];
a11 = d[1] + e[3];
b0 = C[1]*a02 + C[0]*a11;
b1 = C[1]*a11 - C[0]*a02;
b2 = d[0] + e[ 2];
b3 = d[1] - e[ 3];
d[0] = b2 + b0;
d[1] = b3 + b1;
e[2] = b2 - b0;
e[3] = b1 - b3;
a02 = d[2] - e[0];
a11 = d[3] + e[1];
b0 = C[3]*a02 + C[2]*a11;
b1 = C[3]*a11 - C[2]*a02;
b2 = d[2] + e[ 0];
b3 = d[3] - e[ 1];
d[2] = b2 + b0;
d[3] = b3 + b1;
e[0] = b2 - b0;
e[1] = b1 - b3;
C += 4;
d += 4;
e -= 4;
}
}
// data must be in buf2
// step 8+decode (paper output is X, now buffer)
// this generates pairs of data a la 8 and pushes them directly through
// the decode kernel (pushing rather than pulling) to avoid having
// to make another pass later
// this cannot POSSIBLY be in place, so we refer to the buffers directly
{
float *d0,*d1,*d2,*d3;
float *B = f->B[blocktype] + n2 - 8;
float *e = buf2 + n2 - 8;
d0 = &buffer[0];
d1 = &buffer[n2-4];
d2 = &buffer[n2];
d3 = &buffer[n-4];
while (e >= v) {
float p0,p1,p2,p3;
p3 = e[6]*B[7] - e[7]*B[6];
p2 = -e[6]*B[6] - e[7]*B[7];
d0[0] = p3;
d1[3] = - p3;
d2[0] = p2;
d3[3] = p2;
p1 = e[4]*B[5] - e[5]*B[4];
p0 = -e[4]*B[4] - e[5]*B[5];
d0[1] = p1;
d1[2] = - p1;
d2[1] = p0;
d3[2] = p0;
p3 = e[2]*B[3] - e[3]*B[2];
p2 = -e[2]*B[2] - e[3]*B[3];
d0[2] = p3;
d1[1] = - p3;
d2[2] = p2;
d3[1] = p2;
p1 = e[0]*B[1] - e[1]*B[0];
p0 = -e[0]*B[0] - e[1]*B[1];
d0[3] = p1;
d1[0] = - p1;
d2[3] = p0;
d3[0] = p0;
B -= 8;
e -= 8;
d0 += 4;
d2 += 4;
d1 -= 4;
d3 -= 4;
}
}
temp_free(f,buf2);
temp_alloc_restore(f,save_point);
}
#if 0
// this is the original version of the above code, if you want to optimize it from scratch
void inverse_mdct_naive(float *buffer, int n)
{
float s;
float A[1 << 12], B[1 << 12], C[1 << 11];
int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
int n3_4 = n - n4, ld;
// how can they claim this only uses N words?!
// oh, because they're only used sparsely, whoops
float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13];
// set up twiddle factors
for (k=k2=0; k < n4; ++k,k2+=2) {
A[k2 ] = (float) cos(4*k*M_PI/n);
A[k2+1] = (float) -sin(4*k*M_PI/n);
B[k2 ] = (float) cos((k2+1)*M_PI/n/2);
B[k2+1] = (float) sin((k2+1)*M_PI/n/2);
}
for (k=k2=0; k < n8; ++k,k2+=2) {
C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
}
// IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
// Note there are bugs in that pseudocode, presumably due to them attempting
// to rename the arrays nicely rather than representing the way their actual
// implementation bounces buffers back and forth. As a result, even in the
// "some formulars corrected" version, a direct implementation fails. These
// are noted below as "paper bug".
// copy and reflect spectral data
for (k=0; k < n2; ++k) u[k] = buffer[k];
for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1];
// kernel from paper
// step 1
for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) {
v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1];
v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2];
}
// step 2
for (k=k4=0; k < n8; k+=1, k4+=4) {
w[n2+3+k4] = v[n2+3+k4] + v[k4+3];
w[n2+1+k4] = v[n2+1+k4] + v[k4+1];
w[k4+3] = (v[n2+3+k4] - v[k4+3])*A[n2-4-k4] - (v[n2+1+k4]-v[k4+1])*A[n2-3-k4];
w[k4+1] = (v[n2+1+k4] - v[k4+1])*A[n2-4-k4] + (v[n2+3+k4]-v[k4+3])*A[n2-3-k4];
}
// step 3
ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
for (l=0; l < ld-3; ++l) {
int k0 = n >> (l+2), k1 = 1 << (l+3);
int rlim = n >> (l+4), r4, r;
int s2lim = 1 << (l+2), s2;
for (r=r4=0; r < rlim; r4+=4,++r) {
for (s2=0; s2 < s2lim; s2+=2) {
u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4];
u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4];
u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1]
- (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1];
u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1]
+ (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1];
}
}
if (l+1 < ld-3) {
// paper bug: ping-ponging of u&w here is omitted
memcpy(w, u, sizeof(u));
}
}
// step 4
for (i=0; i < n8; ++i) {
int j = bit_reverse(i) >> (32-ld+3);
assert(j < n8);
if (i == j) {
// paper bug: original code probably swapped in place; if copying,
// need to directly copy in this case
int i8 = i << 3;
v[i8+1] = u[i8+1];
v[i8+3] = u[i8+3];
v[i8+5] = u[i8+5];
v[i8+7] = u[i8+7];
} else if (i < j) {
int i8 = i << 3, j8 = j << 3;
v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1];
v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3];
v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5];
v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7];
}
}
// step 5
for (k=0; k < n2; ++k) {
w[k] = v[k*2+1];
}
// step 6
for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) {
u[n-1-k2] = w[k4];
u[n-2-k2] = w[k4+1];
u[n3_4 - 1 - k2] = w[k4+2];
u[n3_4 - 2 - k2] = w[k4+3];
}
// step 7
for (k=k2=0; k < n8; ++k, k2 += 2) {
v[n2 + k2 ] = ( u[n2 + k2] + u[n-2-k2] + C[k2+1]*(u[n2+k2]-u[n-2-k2]) + C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;
v[n-2 - k2] = ( u[n2 + k2] + u[n-2-k2] - C[k2+1]*(u[n2+k2]-u[n-2-k2]) - C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;
v[n2+1+ k2] = ( u[n2+1+k2] - u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;
v[n-1 - k2] = (-u[n2+1+k2] + u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;
}
// step 8
for (k=k2=0; k < n4; ++k,k2 += 2) {
X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1];
X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ];
}
// decode kernel to output
// determined the following value experimentally
// (by first figuring out what made inverse_mdct_slow work); then matching that here
// (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?)
s = 0.5; // theoretically would be n4
// [[[ note! the s value of 0.5 is compensated for by the B[] in the current code,
// so it needs to use the "old" B values to behave correctly, or else
// set s to 1.0 ]]]
for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4];
for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1];
for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4];
}
#endif
static float *get_window(vorb *f, int len)
{
len <<= 1;
if (len == f->blocksize_0) return f->window[0];
if (len == f->blocksize_1) return f->window[1];
return NULL;
}
#ifndef STB_VORBIS_NO_DEFER_FLOOR
typedef int16 YTYPE;
#else
typedef int YTYPE;
#endif
static int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *finalY, uint8 *step2_flag)
{
int n2 = n >> 1;
int s = map->chan[i].mux, floor;
floor = map->submap_floor[s];
if (f->floor_types[floor] == 0) {
return error(f, VORBIS_invalid_stream);
} else {
Floor1 *g = &f->floor_config[floor].floor1;
int j,q;
int lx = 0, ly = finalY[0] * g->floor1_multiplier;
for (q=1; q < g->values; ++q) {
j = g->sorted_order[q];
#ifndef STB_VORBIS_NO_DEFER_FLOOR
if (finalY[j] >= 0)
#else
if (step2_flag[j])
#endif
{
int hy = finalY[j] * g->floor1_multiplier;
int hx = g->Xlist[j];
if (lx != hx)
draw_line(target, lx,ly, hx,hy, n2);
CHECK(f);
lx = hx, ly = hy;
}
}
if (lx < n2) {
// optimization of: draw_line(target, lx,ly, n,ly, n2);
for (j=lx; j < n2; ++j)
LINE_OP(target[j], inverse_db_table[ly]);
CHECK(f);
}
}
return TRUE;
}
// The meaning of "left" and "right"
//
// For a given frame:
// we compute samples from 0..n
// window_center is n/2
// we'll window and mix the samples from left_start to left_end with data from the previous frame
// all of the samples from left_end to right_start can be output without mixing; however,
// this interval is 0-length except when transitioning between short and long frames
// all of the samples from right_start to right_end need to be mixed with the next frame,
// which we don't have, so those get saved in a buffer
// frame N's right_end-right_start, the number of samples to mix with the next frame,
// has to be the same as frame N+1's left_end-left_start (which they are by
// construction)
static int vorbis_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode)
{
Mode *m;
int i, n, prev, next, window_center;
f->channel_buffer_start = f->channel_buffer_end = 0;
retry:
if (f->eof) return FALSE;
if (!maybe_start_packet(f))
return FALSE;
// check packet type
if (get_bits(f,1) != 0) {
if (IS_PUSH_MODE(f))
return error(f,VORBIS_bad_packet_type);
while (EOP != get8_packet(f));
goto retry;
}
if (f->alloc.alloc_buffer)
assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
i = get_bits(f, ilog(f->mode_count-1));
if (i == EOP) return FALSE;
if (i >= f->mode_count) return FALSE;
*mode = i;
m = f->mode_config + i;
if (m->blockflag) {
n = f->blocksize_1;
prev = get_bits(f,1);
next = get_bits(f,1);
} else {
prev = next = 0;
n = f->blocksize_0;
}
// WINDOWING
window_center = n >> 1;
if (m->blockflag && !prev) {
*p_left_start = (n - f->blocksize_0) >> 2;
*p_left_end = (n + f->blocksize_0) >> 2;
} else {
*p_left_start = 0;
*p_left_end = window_center;
}
if (m->blockflag && !next) {
*p_right_start = (n*3 - f->blocksize_0) >> 2;
*p_right_end = (n*3 + f->blocksize_0) >> 2;
} else {
*p_right_start = window_center;
*p_right_end = n;
}
return TRUE;
}
static int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start, int left_end, int right_start, int right_end, int *p_left)
{
Mapping *map;
int i,j,k,n,n2;
int zero_channel[256];
int really_zero_channel[256];
// WINDOWING
n = f->blocksize[m->blockflag];
map = &f->mapping[m->mapping];
// FLOORS
n2 = n >> 1;
CHECK(f);
for (i=0; i < f->channels; ++i) {
int s = map->chan[i].mux, floor;
zero_channel[i] = FALSE;
floor = map->submap_floor[s];
if (f->floor_types[floor] == 0) {
return error(f, VORBIS_invalid_stream);
} else {
Floor1 *g = &f->floor_config[floor].floor1;
if (get_bits(f, 1)) {
short *finalY;
uint8 step2_flag[256];
static int range_list[4] = { 256, 128, 86, 64 };
int range = range_list[g->floor1_multiplier-1];
int offset = 2;
finalY = f->finalY[i];
finalY[0] = get_bits(f, ilog(range)-1);
finalY[1] = get_bits(f, ilog(range)-1);
for (j=0; j < g->partitions; ++j) {
int pclass = g->partition_class_list[j];
int cdim = g->class_dimensions[pclass];
int cbits = g->class_subclasses[pclass];
int csub = (1 << cbits)-1;
int cval = 0;
if (cbits) {
Codebook *c = f->codebooks + g->class_masterbooks[pclass];
DECODE(cval,f,c);
}
for (k=0; k < cdim; ++k) {
int book = g->subclass_books[pclass][cval & csub];
cval = cval >> cbits;
if (book >= 0) {
int temp;
Codebook *c = f->codebooks + book;
DECODE(temp,f,c);
finalY[offset++] = temp;
} else
finalY[offset++] = 0;
}
}
if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec
step2_flag[0] = step2_flag[1] = 1;
for (j=2; j < g->values; ++j) {
int low, high, pred, highroom, lowroom, room, val;
low = g->neighbors[j][0];
high = g->neighbors[j][1];
//neighbors(g->Xlist, j, &low, &high);
pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]);
val = finalY[j];
highroom = range - pred;
lowroom = pred;
if (highroom < lowroom)
room = highroom * 2;
else
room = lowroom * 2;
if (val) {
step2_flag[low] = step2_flag[high] = 1;
step2_flag[j] = 1;
if (val >= room)
if (highroom > lowroom)
finalY[j] = val - lowroom + pred;
else
finalY[j] = pred - val + highroom - 1;
else
if (val & 1)
finalY[j] = pred - ((val+1)>>1);
else
finalY[j] = pred + (val>>1);
} else {
step2_flag[j] = 0;
finalY[j] = pred;
}
}
#ifdef STB_VORBIS_NO_DEFER_FLOOR
do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag);
#else
// defer final floor computation until _after_ residue
for (j=0; j < g->values; ++j) {
if (!step2_flag[j])
finalY[j] = -1;
}
#endif
} else {
error:
zero_channel[i] = TRUE;
}
// So we just defer everything else to later
// at this point we've decoded the floor into buffer
}
}
CHECK(f);
// at this point we've decoded all floors
if (f->alloc.alloc_buffer)
assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
// re-enable coupled channels if necessary
memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels);
for (i=0; i < map->coupling_steps; ++i)
if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) {
zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE;
}
CHECK(f);
// RESIDUE DECODE
for (i=0; i < map->submaps; ++i) {
float *residue_buffers[STB_VORBIS_MAX_CHANNELS];
int r;
uint8 do_not_decode[256];
int ch = 0;
for (j=0; j < f->channels; ++j) {
if (map->chan[j].mux == i) {
if (zero_channel[j]) {
do_not_decode[ch] = TRUE;
residue_buffers[ch] = NULL;
} else {
do_not_decode[ch] = FALSE;
residue_buffers[ch] = f->channel_buffers[j];
}
++ch;
}
}
r = map->submap_residue[i];
decode_residue(f, residue_buffers, ch, n2, r, do_not_decode);
}
if (f->alloc.alloc_buffer)
assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
CHECK(f);
// INVERSE COUPLING
for (i = map->coupling_steps-1; i >= 0; --i) {
int n2 = n >> 1;
float *m = f->channel_buffers[map->chan[i].magnitude];
float *a = f->channel_buffers[map->chan[i].angle ];
for (j=0; j < n2; ++j) {
float a2,m2;
if (m[j] > 0)
if (a[j] > 0)
m2 = m[j], a2 = m[j] - a[j];
else
a2 = m[j], m2 = m[j] + a[j];
else
if (a[j] > 0)
m2 = m[j], a2 = m[j] + a[j];
else
a2 = m[j], m2 = m[j] - a[j];
m[j] = m2;
a[j] = a2;
}
}
CHECK(f);
// finish decoding the floors
#ifndef STB_VORBIS_NO_DEFER_FLOOR
for (i=0; i < f->channels; ++i) {
if (really_zero_channel[i]) {
memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
} else {
do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL);
}
}
#else
for (i=0; i < f->channels; ++i) {
if (really_zero_channel[i]) {
memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
} else {
for (j=0; j < n2; ++j)
f->channel_buffers[i][j] *= f->floor_buffers[i][j];
}
}
#endif
// INVERSE MDCT
CHECK(f);
for (i=0; i < f->channels; ++i)
inverse_mdct(f->channel_buffers[i], n, f, m->blockflag);
CHECK(f);
// this shouldn't be necessary, unless we exited on an error
// and want to flush to get to the next packet
flush_packet(f);
if (f->first_decode) {
// assume we start so first non-discarded sample is sample 0
// this isn't to spec, but spec would require us to read ahead
// and decode the size of all current frames--could be done,
// but presumably it's not a commonly used feature
f->current_loc = -n2; // start of first frame is positioned for discard
// we might have to discard samples "from" the next frame too,
// if we're lapping a large block then a small at the start?
f->discard_samples_deferred = n - right_end;
f->current_loc_valid = TRUE;
f->first_decode = FALSE;
} else if (f->discard_samples_deferred) {
if (f->discard_samples_deferred >= right_start - left_start) {
f->discard_samples_deferred -= (right_start - left_start);
left_start = right_start;
*p_left = left_start;
} else {
left_start += f->discard_samples_deferred;
*p_left = left_start;
f->discard_samples_deferred = 0;
}
} else if (f->previous_length == 0 && f->current_loc_valid) {
// we're recovering from a seek... that means we're going to discard
// the samples from this packet even though we know our position from
// the last page header, so we need to update the position based on
// the discarded samples here
// but wait, the code below is going to add this in itself even
// on a discard, so we don't need to do it here...
}
// check if we have ogg information about the sample # for this packet
if (f->last_seg_which == f->end_seg_with_known_loc) {
// if we have a valid current loc, and this is final:
if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) {
uint32 current_end = f->known_loc_for_packet;
// then let's infer the size of the (probably) short final frame
if (current_end < f->current_loc + (right_end-left_start)) {
if (current_end < f->current_loc) {
// negative truncation, that's impossible!
*len = 0;
} else {
*len = current_end - f->current_loc;
}
*len += left_start; // this doesn't seem right, but has no ill effect on my test files
if (*len > right_end) *len = right_end; // this should never happen
f->current_loc += *len;
return TRUE;
}
}
// otherwise, just set our sample loc
// guess that the ogg granule pos refers to the _middle_ of the
// last frame?
// set f->current_loc to the position of left_start
f->current_loc = f->known_loc_for_packet - (n2-left_start);
f->current_loc_valid = TRUE;
}
if (f->current_loc_valid)
f->current_loc += (right_start - left_start);
if (f->alloc.alloc_buffer)
assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
*len = right_end; // ignore samples after the window goes to 0
CHECK(f);
return TRUE;
}
static int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right)
{
int mode, left_end, right_end;
if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0;
return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left);
}
static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right)
{
int prev,i,j;
// we use right&left (the start of the right- and left-window sin()-regions)
// to determine how much to return, rather than inferring from the rules
// (same result, clearer code); 'left' indicates where our sin() window
// starts, therefore where the previous window's right edge starts, and
// therefore where to start mixing from the previous buffer. 'right'
// indicates where our sin() ending-window starts, therefore that's where
// we start saving, and where our returned-data ends.
// mixin from previous window
if (f->previous_length) {
int i,j, n = f->previous_length;
float *w = get_window(f, n);
if (w == NULL) return 0;
for (i=0; i < f->channels; ++i) {
for (j=0; j < n; ++j)
f->channel_buffers[i][left+j] =
f->channel_buffers[i][left+j]*w[ j] +
f->previous_window[i][ j]*w[n-1-j];
}
}
prev = f->previous_length;
// last half of this data becomes previous window
f->previous_length = len - right;
// @OPTIMIZE: could avoid this copy by double-buffering the
// output (flipping previous_window with channel_buffers), but
// then previous_window would have to be 2x as large, and
// channel_buffers couldn't be temp mem (although they're NOT
// currently temp mem, they could be (unless we want to level
// performance by spreading out the computation))
for (i=0; i < f->channels; ++i)
for (j=0; right+j < len; ++j)
f->previous_window[i][j] = f->channel_buffers[i][right+j];
if (!prev)
// there was no previous packet, so this data isn't valid...
// this isn't entirely true, only the would-have-overlapped data
// isn't valid, but this seems to be what the spec requires
return 0;
// truncate a short frame
if (len < right) right = len;
f->samples_output += right-left;
return right - left;
}
static int vorbis_pump_first_frame(stb_vorbis *f)
{
int len, right, left, res;
res = vorbis_decode_packet(f, &len, &left, &right);
if (res)
vorbis_finish_frame(f, len, left, right);
return res;
}
#ifndef STB_VORBIS_NO_PUSHDATA_API
static int is_whole_packet_present(stb_vorbis *f)
{
// make sure that we have the packet available before continuing...
// this requires a full ogg parse, but we know we can fetch from f->stream
// instead of coding this out explicitly, we could save the current read state,
// read the next packet with get8() until end-of-packet, check f->eof, then
// reset the state? but that would be slower, esp. since we'd have over 256 bytes
// of state to restore (primarily the page segment table)
int s = f->next_seg, first = TRUE;
uint8 *p = f->stream;
if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag
for (; s < f->segment_count; ++s) {
p += f->segments[s];
if (f->segments[s] < 255) // stop at first short segment
break;
}
// either this continues, or it ends it...
if (s == f->segment_count)
s = -1; // set 'crosses page' flag
if (p > f->stream_end) return error(f, VORBIS_need_more_data);
first = FALSE;
}
for (; s == -1;) {
uint8 *q;
int n;
// check that we have the page header ready
if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data);
// validate the page
if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream);
if (p[4] != 0) return error(f, VORBIS_invalid_stream);
if (first) { // the first segment must NOT have 'continued_packet', later ones MUST
if (f->previous_length)
if ((p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream);
// if no previous length, we're resynching, so we can come in on a continued-packet,
// which we'll just drop
} else {
if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream);
}
n = p[26]; // segment counts
q = p+27; // q points to segment table
p = q + n; // advance past header
// make sure we've read the segment table
if (p > f->stream_end) return error(f, VORBIS_need_more_data);
for (s=0; s < n; ++s) {
p += q[s];
if (q[s] < 255)
break;
}
if (s == n)
s = -1; // set 'crosses page' flag
if (p > f->stream_end) return error(f, VORBIS_need_more_data);
first = FALSE;
}
return TRUE;
}
#endif // !STB_VORBIS_NO_PUSHDATA_API
static int start_decoder(vorb *f)
{
uint8 header[6], x,y;
int len,i,j,k, max_submaps = 0;
int longest_floorlist=0;
// first page, first packet
f->first_decode = TRUE;
if (!start_page(f)) return FALSE;
// validate page flag
if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page);
if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page);
if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page);
// check for expected packet length
if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page);
if (f->segments[0] != 30) {
// check for the Ogg skeleton fishead identifying header to refine our error
if (f->segments[0] == 64 &&
getn(f, header, 6) &&
header[0] == 'f' &&
header[1] == 'i' &&
header[2] == 's' &&
header[3] == 'h' &&
header[4] == 'e' &&
header[5] == 'a' &&
get8(f) == 'd' &&
get8(f) == '\0') return error(f, VORBIS_ogg_skeleton_not_supported);
else
return error(f, VORBIS_invalid_first_page);
}
// read packet
// check packet header
if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page);
if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page);
// vorbis_version
if (get32(f) != 0) return error(f, VORBIS_invalid_first_page);
f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page);
if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels);
f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page);
get32(f); // bitrate_maximum
get32(f); // bitrate_nominal
get32(f); // bitrate_minimum
x = get8(f);
{
int log0,log1;
log0 = x & 15;
log1 = x >> 4;
f->blocksize_0 = 1 << log0;
f->blocksize_1 = 1 << log1;
if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup);
if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup);
if (log0 > log1) return error(f, VORBIS_invalid_setup);
}
// framing_flag
x = get8(f);
if (!(x & 1)) return error(f, VORBIS_invalid_first_page);
// second packet!
if (!start_page(f)) return FALSE;
if (!start_packet(f)) return FALSE;
if (!next_segment(f)) return FALSE;
if (get8_packet(f) != VORBIS_packet_comment) return error(f, VORBIS_invalid_setup);
for (i=0; i < 6; ++i) header[i] = get8_packet(f);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);
//file vendor
len = get32_packet(f);
f->vendor = (char*)setup_malloc(f, sizeof(char) * (len+1));
if (f->vendor == NULL) return error(f, VORBIS_outofmem);
for(i=0; i < len; ++i) {
f->vendor[i] = get8_packet(f);
}
f->vendor[len] = (char)'\0';
//user comments
f->comment_list_length = get32_packet(f);
f->comment_list = (char**)setup_malloc(f, sizeof(char*) * (f->comment_list_length));
if (f->comment_list == NULL) return error(f, VORBIS_outofmem);
for(i=0; i < f->comment_list_length; ++i) {
len = get32_packet(f);
f->comment_list[i] = (char*)setup_malloc(f, sizeof(char) * (len+1));
if (f->comment_list[i] == NULL) return error(f, VORBIS_outofmem);
for(j=0; j < len; ++j) {
f->comment_list[i][j] = get8_packet(f);
}
f->comment_list[i][len] = (char)'\0';
}
// framing_flag
x = get8_packet(f);
if (!(x & 1)) return error(f, VORBIS_invalid_setup);
skip(f, f->bytes_in_seg);
f->bytes_in_seg = 0;
do {
len = next_segment(f);
skip(f, len);
f->bytes_in_seg = 0;
} while (len);
// third packet!
if (!start_packet(f)) return FALSE;
#ifndef STB_VORBIS_NO_PUSHDATA_API
if (IS_PUSH_MODE(f)) {
if (!is_whole_packet_present(f)) {
// convert error in ogg header to write type
if (f->error == VORBIS_invalid_stream)
f->error = VORBIS_invalid_setup;
return FALSE;
}
}
#endif
crc32_init(); // always init it, to avoid multithread race conditions
if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup);
for (i=0; i < 6; ++i) header[i] = get8_packet(f);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);
// codebooks
f->codebook_count = get_bits(f,8) + 1;
f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count);
if (f->codebooks == NULL) return error(f, VORBIS_outofmem);
memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count);
for (i=0; i < f->codebook_count; ++i) {
uint32 *values;
int ordered, sorted_count;
int total=0;
uint8 *lengths;
Codebook *c = f->codebooks+i;
CHECK(f);
x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8);
c->dimensions = (get_bits(f, 8)<<8) + x;
x = get_bits(f, 8);
y = get_bits(f, 8);
c->entries = (get_bits(f, 8)<<16) + (y<<8) + x;
ordered = get_bits(f,1);
c->sparse = ordered ? 0 : get_bits(f,1);
if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup);
if (c->sparse)
lengths = (uint8 *) setup_temp_malloc(f, c->entries);
else
lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
if (!lengths) return error(f, VORBIS_outofmem);
if (ordered) {
int current_entry = 0;
int current_length = get_bits(f,5) + 1;
while (current_entry < c->entries) {
int limit = c->entries - current_entry;
int n = get_bits(f, ilog(limit));
if (current_length >= 32) return error(f, VORBIS_invalid_setup);
if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); }
memset(lengths + current_entry, current_length, n);
current_entry += n;
++current_length;
}
} else {
for (j=0; j < c->entries; ++j) {
int present = c->sparse ? get_bits(f,1) : 1;
if (present) {
lengths[j] = get_bits(f, 5) + 1;
++total;
if (lengths[j] == 32)
return error(f, VORBIS_invalid_setup);
} else {
lengths[j] = NO_CODE;
}
}
}
if (c->sparse && total >= c->entries >> 2) {
// convert sparse items to non-sparse!
if (c->entries > (int) f->setup_temp_memory_required)
f->setup_temp_memory_required = c->entries;
c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem);
memcpy(c->codeword_lengths, lengths, c->entries);
setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs!
lengths = c->codeword_lengths;
c->sparse = 0;
}
// compute the size of the sorted tables
if (c->sparse) {
sorted_count = total;
} else {
sorted_count = 0;
#ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
for (j=0; j < c->entries; ++j)
if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE)
++sorted_count;
#endif
}
c->sorted_entries = sorted_count;
values = NULL;
CHECK(f);
if (!c->sparse) {
c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries);
if (!c->codewords) return error(f, VORBIS_outofmem);
} else {
unsigned int size;
if (c->sorted_entries) {
c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries);
if (!c->codeword_lengths) return error(f, VORBIS_outofmem);
c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries);
if (!c->codewords) return error(f, VORBIS_outofmem);
values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries);
if (!values) return error(f, VORBIS_outofmem);
}
size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries;
if (size > f->setup_temp_memory_required)
f->setup_temp_memory_required = size;
}
if (!compute_codewords(c, lengths, c->entries, values)) {
if (c->sparse) setup_temp_free(f, values, 0);
return error(f, VORBIS_invalid_setup);
}
if (c->sorted_entries) {
// allocate an extra slot for sentinels
c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1));
if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem);
// allocate an extra slot at the front so that c->sorted_values[-1] is defined
// so that we can catch that case without an extra if
c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1));
if (c->sorted_values == NULL) return error(f, VORBIS_outofmem);
++c->sorted_values;
c->sorted_values[-1] = -1;
compute_sorted_huffman(c, lengths, values);
}
if (c->sparse) {
setup_temp_free(f, values, sizeof(*values)*c->sorted_entries);
setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries);
setup_temp_free(f, lengths, c->entries);
c->codewords = NULL;
}
compute_accelerated_huffman(c);
CHECK(f);
c->lookup_type = get_bits(f, 4);
if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup);
if (c->lookup_type > 0) {
uint16 *mults;
c->minimum_value = float32_unpack(get_bits(f, 32));
c->delta_value = float32_unpack(get_bits(f, 32));
c->value_bits = get_bits(f, 4)+1;
c->sequence_p = get_bits(f,1);
if (c->lookup_type == 1) {
int values = lookup1_values(c->entries, c->dimensions);
if (values < 0) return error(f, VORBIS_invalid_setup);
c->lookup_values = (uint32) values;
} else {
c->lookup_values = c->entries * c->dimensions;
}
if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup);
mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values);
if (mults == NULL) return error(f, VORBIS_outofmem);
for (j=0; j < (int) c->lookup_values; ++j) {
int q = get_bits(f, c->value_bits);
if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); }
mults[j] = q;
}
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
int len, sparse = c->sparse;
float last=0;
// pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop
if (sparse) {
if (c->sorted_entries == 0) goto skip;
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions);
} else
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions);
if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
len = sparse ? c->sorted_entries : c->entries;
for (j=0; j < len; ++j) {
unsigned int z = sparse ? c->sorted_values[j] : j;
unsigned int div=1;
for (k=0; k < c->dimensions; ++k) {
int off = (z / div) % c->lookup_values;
float val = mults[off];
val = mults[off]*c->delta_value + c->minimum_value + last;
c->multiplicands[j*c->dimensions + k] = val;
if (c->sequence_p)
last = val;
if (k+1 < c->dimensions) {
if (div > UINT_MAX / (unsigned int) c->lookup_values) {
setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);
return error(f, VORBIS_invalid_setup);
}
div *= c->lookup_values;
}
}
}
c->lookup_type = 2;
}
else
#endif
{
float last=0;
CHECK(f);
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values);
if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
for (j=0; j < (int) c->lookup_values; ++j) {
float val = mults[j] * c->delta_value + c->minimum_value + last;
c->multiplicands[j] = val;
if (c->sequence_p)
last = val;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
skip:;
#endif
setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values);
CHECK(f);
}
CHECK(f);
}
// time domain transfers (notused)
x = get_bits(f, 6) + 1;
for (i=0; i < x; ++i) {
uint32 z = get_bits(f, 16);
if (z != 0) return error(f, VORBIS_invalid_setup);
}
// Floors
f->floor_count = get_bits(f, 6)+1;
f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config));
if (f->floor_config == NULL) return error(f, VORBIS_outofmem);
for (i=0; i < f->floor_count; ++i) {
f->floor_types[i] = get_bits(f, 16);
if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup);
if (f->floor_types[i] == 0) {
Floor0 *g = &f->floor_config[i].floor0;
g->order = get_bits(f,8);
g->rate = get_bits(f,16);
g->bark_map_size = get_bits(f,16);
g->amplitude_bits = get_bits(f,6);
g->amplitude_offset = get_bits(f,8);
g->number_of_books = get_bits(f,4) + 1;
for (j=0; j < g->number_of_books; ++j)
g->book_list[j] = get_bits(f,8);
return error(f, VORBIS_feature_not_supported);
} else {
stbv__floor_ordering p[31*8+2];
Floor1 *g = &f->floor_config[i].floor1;
int max_class = -1;
g->partitions = get_bits(f, 5);
for (j=0; j < g->partitions; ++j) {
g->partition_class_list[j] = get_bits(f, 4);
if (g->partition_class_list[j] > max_class)
max_class = g->partition_class_list[j];
}
for (j=0; j <= max_class; ++j) {
g->class_dimensions[j] = get_bits(f, 3)+1;
g->class_subclasses[j] = get_bits(f, 2);
if (g->class_subclasses[j]) {
g->class_masterbooks[j] = get_bits(f, 8);
if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
}
for (k=0; k < 1 << g->class_subclasses[j]; ++k) {
g->subclass_books[j][k] = get_bits(f,8)-1;
if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
}
}
g->floor1_multiplier = get_bits(f,2)+1;
g->rangebits = get_bits(f,4);
g->Xlist[0] = 0;
g->Xlist[1] = 1 << g->rangebits;
g->values = 2;
for (j=0; j < g->partitions; ++j) {
int c = g->partition_class_list[j];
for (k=0; k < g->class_dimensions[c]; ++k) {
g->Xlist[g->values] = get_bits(f, g->rangebits);
++g->values;
}
}
// precompute the sorting
for (j=0; j < g->values; ++j) {
p[j].x = g->Xlist[j];
p[j].id = j;
}
qsort(p, g->values, sizeof(p[0]), point_compare);
for (j=0; j < g->values-1; ++j)
if (p[j].x == p[j+1].x)
return error(f, VORBIS_invalid_setup);
for (j=0; j < g->values; ++j)
g->sorted_order[j] = (uint8) p[j].id;
// precompute the neighbors
for (j=2; j < g->values; ++j) {
int low = 0,hi = 0;
neighbors(g->Xlist, j, &low,&hi);
g->neighbors[j][0] = low;
g->neighbors[j][1] = hi;
}
if (g->values > longest_floorlist)
longest_floorlist = g->values;
}
}
// Residue
f->residue_count = get_bits(f, 6)+1;
f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0]));
if (f->residue_config == NULL) return error(f, VORBIS_outofmem);
memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0]));
for (i=0; i < f->residue_count; ++i) {
uint8 residue_cascade[64];
Residue *r = f->residue_config+i;
f->residue_types[i] = get_bits(f, 16);
if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup);
r->begin = get_bits(f, 24);
r->end = get_bits(f, 24);
if (r->end < r->begin) return error(f, VORBIS_invalid_setup);
r->part_size = get_bits(f,24)+1;
r->classifications = get_bits(f,6)+1;
r->classbook = get_bits(f,8);
if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup);
for (j=0; j < r->classifications; ++j) {
uint8 high_bits=0;
uint8 low_bits=get_bits(f,3);
if (get_bits(f,1))
high_bits = get_bits(f,5);
residue_cascade[j] = high_bits*8 + low_bits;
}
r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications);
if (r->residue_books == NULL) return error(f, VORBIS_outofmem);
for (j=0; j < r->classifications; ++j) {
for (k=0; k < 8; ++k) {
if (residue_cascade[j] & (1 << k)) {
r->residue_books[j][k] = get_bits(f, 8);
if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
} else {
r->residue_books[j][k] = -1;
}
}
}
// precompute the classifications[] array to avoid inner-loop mod/divide
// call it 'classdata' since we already have r->classifications
r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
if (!r->classdata) return error(f, VORBIS_outofmem);
memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
for (j=0; j < f->codebooks[r->classbook].entries; ++j) {
int classwords = f->codebooks[r->classbook].dimensions;
int temp = j;
r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords);
if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem);
for (k=classwords-1; k >= 0; --k) {
r->classdata[j][k] = temp % r->classifications;
temp /= r->classifications;
}
}
}
f->mapping_count = get_bits(f,6)+1;
f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping));
if (f->mapping == NULL) return error(f, VORBIS_outofmem);
memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping));
for (i=0; i < f->mapping_count; ++i) {
Mapping *m = f->mapping + i;
int mapping_type = get_bits(f,16);
if (mapping_type != 0) return error(f, VORBIS_invalid_setup);
m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan));
if (m->chan == NULL) return error(f, VORBIS_outofmem);
if (get_bits(f,1))
m->submaps = get_bits(f,4)+1;
else
m->submaps = 1;
if (m->submaps > max_submaps)
max_submaps = m->submaps;
if (get_bits(f,1)) {
m->coupling_steps = get_bits(f,8)+1;
if (m->coupling_steps > f->channels) return error(f, VORBIS_invalid_setup);
for (k=0; k < m->coupling_steps; ++k) {
m->chan[k].magnitude = get_bits(f, ilog(f->channels-1));
m->chan[k].angle = get_bits(f, ilog(f->channels-1));
if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup);
if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup);
if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup);
}
} else
m->coupling_steps = 0;
// reserved field
if (get_bits(f,2)) return error(f, VORBIS_invalid_setup);
if (m->submaps > 1) {
for (j=0; j < f->channels; ++j) {
m->chan[j].mux = get_bits(f, 4);
if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup);
}
} else
// @SPECIFICATION: this case is missing from the spec
for (j=0; j < f->channels; ++j)
m->chan[j].mux = 0;
for (j=0; j < m->submaps; ++j) {
get_bits(f,8); // discard
m->submap_floor[j] = get_bits(f,8);
m->submap_residue[j] = get_bits(f,8);
if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup);
if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup);
}
}
// Modes
f->mode_count = get_bits(f, 6)+1;
for (i=0; i < f->mode_count; ++i) {
Mode *m = f->mode_config+i;
m->blockflag = get_bits(f,1);
m->windowtype = get_bits(f,16);
m->transformtype = get_bits(f,16);
m->mapping = get_bits(f,8);
if (m->windowtype != 0) return error(f, VORBIS_invalid_setup);
if (m->transformtype != 0) return error(f, VORBIS_invalid_setup);
if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup);
}
flush_packet(f);
f->previous_length = 0;
for (i=0; i < f->channels; ++i) {
f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1);
f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist);
if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem);
memset(f->channel_buffers[i], 0, sizeof(float) * f->blocksize_1);
#ifdef STB_VORBIS_NO_DEFER_FLOOR
f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem);
#endif
}
if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE;
if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE;
f->blocksize[0] = f->blocksize_0;
f->blocksize[1] = f->blocksize_1;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (integer_divide_table[1][1]==0)
for (i=0; i < DIVTAB_NUMER; ++i)
for (j=1; j < DIVTAB_DENOM; ++j)
integer_divide_table[i][j] = i / j;
#endif
// compute how much temporary memory is needed
// 1.
{
uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1);
uint32 classify_mem;
int i,max_part_read=0;
for (i=0; i < f->residue_count; ++i) {
Residue *r = f->residue_config + i;
unsigned int actual_size = f->blocksize_1 / 2;
unsigned int limit_r_begin = r->begin < actual_size ? r->begin : actual_size;
unsigned int limit_r_end = r->end < actual_size ? r->end : actual_size;
int n_read = limit_r_end - limit_r_begin;
int part_read = n_read / r->part_size;
if (part_read > max_part_read)
max_part_read = part_read;
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *));
#else
classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *));
#endif
// maximum reasonable partition size is f->blocksize_1
f->temp_memory_required = classify_mem;
if (imdct_mem > f->temp_memory_required)
f->temp_memory_required = imdct_mem;
}
if (f->alloc.alloc_buffer) {
assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes);
// check if there's enough temp memory so we don't error later
if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset)
return error(f, VORBIS_outofmem);
}
// @TODO: stb_vorbis_seek_start expects first_audio_page_offset to point to a page
// without PAGEFLAG_continued_packet, so this either points to the first page, or
// the page after the end of the headers. It might be cleaner to point to a page
// in the middle of the headers, when that's the page where the first audio packet
// starts, but we'd have to also correctly skip the end of any continued packet in
// stb_vorbis_seek_start.
if (f->next_seg == -1) {
f->first_audio_page_offset = stb_vorbis_get_file_offset(f);
} else {
f->first_audio_page_offset = 0;
}
return TRUE;
}
static void vorbis_deinit(stb_vorbis *p)
{
int i,j;
setup_free(p, p->vendor);
for (i=0; i < p->comment_list_length; ++i) {
setup_free(p, p->comment_list[i]);
}
setup_free(p, p->comment_list);
if (p->residue_config) {
for (i=0; i < p->residue_count; ++i) {
Residue *r = p->residue_config+i;
if (r->classdata) {
for (j=0; j < p->codebooks[r->classbook].entries; ++j)
setup_free(p, r->classdata[j]);
setup_free(p, r->classdata);
}
setup_free(p, r->residue_books);
}
}
if (p->codebooks) {
CHECK(p);
for (i=0; i < p->codebook_count; ++i) {
Codebook *c = p->codebooks + i;
setup_free(p, c->codeword_lengths);
setup_free(p, c->multiplicands);
setup_free(p, c->codewords);
setup_free(p, c->sorted_codewords);
// c->sorted_values[-1] is the first entry in the array
setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL);
}
setup_free(p, p->codebooks);
}
setup_free(p, p->floor_config);
setup_free(p, p->residue_config);
if (p->mapping) {
for (i=0; i < p->mapping_count; ++i)
setup_free(p, p->mapping[i].chan);
setup_free(p, p->mapping);
}
CHECK(p);
for (i=0; i < p->channels && i < STB_VORBIS_MAX_CHANNELS; ++i) {
setup_free(p, p->channel_buffers[i]);
setup_free(p, p->previous_window[i]);
#ifdef STB_VORBIS_NO_DEFER_FLOOR
setup_free(p, p->floor_buffers[i]);
#endif
setup_free(p, p->finalY[i]);
}
for (i=0; i < 2; ++i) {
setup_free(p, p->A[i]);
setup_free(p, p->B[i]);
setup_free(p, p->C[i]);
setup_free(p, p->window[i]);
setup_free(p, p->bit_reverse[i]);
}
#ifndef STB_VORBIS_NO_STDIO
if (p->close_on_free) fclose(p->f);
#endif
}
void stb_vorbis_close(stb_vorbis *p)
{
if (p == NULL) return;
vorbis_deinit(p);
setup_free(p,p);
}
static void vorbis_init(stb_vorbis *p, const stb_vorbis_alloc *z)
{
memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start
if (z) {
p->alloc = *z;
p->alloc.alloc_buffer_length_in_bytes &= ~7;
p->temp_offset = p->alloc.alloc_buffer_length_in_bytes;
}
p->eof = 0;
p->error = VORBIS__no_error;
p->stream = NULL;
p->codebooks = NULL;
p->page_crc_tests = -1;
#ifndef STB_VORBIS_NO_STDIO
p->close_on_free = FALSE;
p->f = NULL;
#endif
}
int stb_vorbis_get_sample_offset(stb_vorbis *f)
{
if (f->current_loc_valid)
return f->current_loc;
else
return -1;
}
stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f)
{
stb_vorbis_info d;
d.channels = f->channels;
d.sample_rate = f->sample_rate;
d.setup_memory_required = f->setup_memory_required;
d.setup_temp_memory_required = f->setup_temp_memory_required;
d.temp_memory_required = f->temp_memory_required;
d.max_frame_size = f->blocksize_1 >> 1;
return d;
}
stb_vorbis_comment stb_vorbis_get_comment(stb_vorbis *f)
{
stb_vorbis_comment d;
d.vendor = f->vendor;
d.comment_list_length = f->comment_list_length;
d.comment_list = f->comment_list;
return d;
}
int stb_vorbis_get_error(stb_vorbis *f)
{
int e = f->error;
f->error = VORBIS__no_error;
return e;
}
static stb_vorbis * vorbis_alloc(stb_vorbis *f)
{
stb_vorbis *p = (stb_vorbis *) setup_malloc(f, sizeof(*p));
return p;
}
#ifndef STB_VORBIS_NO_PUSHDATA_API
void stb_vorbis_flush_pushdata(stb_vorbis *f)
{
f->previous_length = 0;
f->page_crc_tests = 0;
f->discard_samples_deferred = 0;
f->current_loc_valid = FALSE;
f->first_decode = FALSE;
f->samples_output = 0;
f->channel_buffer_start = 0;
f->channel_buffer_end = 0;
}
static int vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len)
{
int i,n;
for (i=0; i < f->page_crc_tests; ++i)
f->scan[i].bytes_done = 0;
// if we have room for more scans, search for them first, because
// they may cause us to stop early if their header is incomplete
if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) {
if (data_len < 4) return 0;
data_len -= 3; // need to look for 4-byte sequence, so don't miss
// one that straddles a boundary
for (i=0; i < data_len; ++i) {
if (data[i] == 0x4f) {
if (0==memcmp(data+i, ogg_page_header, 4)) {
int j,len;
uint32 crc;
// make sure we have the whole page header
if (i+26 >= data_len || i+27+data[i+26] >= data_len) {
// only read up to this page start, so hopefully we'll
// have the whole page header start next time
data_len = i;
break;
}
// ok, we have it all; compute the length of the page
len = 27 + data[i+26];
for (j=0; j < data[i+26]; ++j)
len += data[i+27+j];
// scan everything up to the embedded crc (which we must 0)
crc = 0;
for (j=0; j < 22; ++j)
crc = crc32_update(crc, data[i+j]);
// now process 4 0-bytes
for ( ; j < 26; ++j)
crc = crc32_update(crc, 0);
// len is the total number of bytes we need to scan
n = f->page_crc_tests++;
f->scan[n].bytes_left = len-j;
f->scan[n].crc_so_far = crc;
f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24);
// if the last frame on a page is continued to the next, then
// we can't recover the sample_loc immediately
if (data[i+27+data[i+26]-1] == 255)
f->scan[n].sample_loc = ~0;
else
f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24);
f->scan[n].bytes_done = i+j;
if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT)
break;
// keep going if we still have room for more
}
}
}
}
for (i=0; i < f->page_crc_tests;) {
uint32 crc;
int j;
int n = f->scan[i].bytes_done;
int m = f->scan[i].bytes_left;
if (m > data_len - n) m = data_len - n;
// m is the bytes to scan in the current chunk
crc = f->scan[i].crc_so_far;
for (j=0; j < m; ++j)
crc = crc32_update(crc, data[n+j]);
f->scan[i].bytes_left -= m;
f->scan[i].crc_so_far = crc;
if (f->scan[i].bytes_left == 0) {
// does it match?
if (f->scan[i].crc_so_far == f->scan[i].goal_crc) {
// Houston, we have page
data_len = n+m; // consumption amount is wherever that scan ended
f->page_crc_tests = -1; // drop out of page scan mode
f->previous_length = 0; // decode-but-don't-output one frame
f->next_seg = -1; // start a new page
f->current_loc = f->scan[i].sample_loc; // set the current sample location
// to the amount we'd have decoded had we decoded this page
f->current_loc_valid = f->current_loc != ~0U;
return data_len;
}
// delete entry
f->scan[i] = f->scan[--f->page_crc_tests];
} else {
++i;
}
}
return data_len;
}
// return value: number of bytes we used
int stb_vorbis_decode_frame_pushdata(
stb_vorbis *f, // the file we're decoding
const uint8 *data, int data_len, // the memory available for decoding
int *channels, // place to write number of float * buffers
float ***output, // place to write float ** array of float * buffers
int *samples // place to write number of output samples
)
{
int i;
int len,right,left;
if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
if (f->page_crc_tests >= 0) {
*samples = 0;
return vorbis_search_for_page_pushdata(f, (uint8 *) data, data_len);
}
f->stream = (uint8 *) data;
f->stream_end = (uint8 *) data + data_len;
f->error = VORBIS__no_error;
// check that we have the entire packet in memory
if (!is_whole_packet_present(f)) {
*samples = 0;
return 0;
}
if (!vorbis_decode_packet(f, &len, &left, &right)) {
// save the actual error we encountered
enum STBVorbisError error = f->error;
if (error == VORBIS_bad_packet_type) {
// flush and resynch
f->error = VORBIS__no_error;
while (get8_packet(f) != EOP)
if (f->eof) break;
*samples = 0;
return (int) (f->stream - data);
}
if (error == VORBIS_continued_packet_flag_invalid) {
if (f->previous_length == 0) {
// we may be resynching, in which case it's ok to hit one
// of these; just discard the packet
f->error = VORBIS__no_error;
while (get8_packet(f) != EOP)
if (f->eof) break;
*samples = 0;
return (int) (f->stream - data);
}
}
// if we get an error while parsing, what to do?
// well, it DEFINITELY won't work to continue from where we are!
stb_vorbis_flush_pushdata(f);
// restore the error that actually made us bail
f->error = error;
*samples = 0;
return 1;
}
// success!
len = vorbis_finish_frame(f, len, left, right);
for (i=0; i < f->channels; ++i)
f->outputs[i] = f->channel_buffers[i] + left;
if (channels) *channels = f->channels;
*samples = len;
*output = f->outputs;
return (int) (f->stream - data);
}
stb_vorbis *stb_vorbis_open_pushdata(
const unsigned char *data, int data_len, // the memory available for decoding
int *data_used, // only defined if result is not NULL
int *error, const stb_vorbis_alloc *alloc)
{
stb_vorbis *f, p;
vorbis_init(&p, alloc);
p.stream = (uint8 *) data;
p.stream_end = (uint8 *) data + data_len;
p.push_mode = TRUE;
if (!start_decoder(&p)) {
if (p.eof)
*error = VORBIS_need_more_data;
else
*error = p.error;
return NULL;
}
f = vorbis_alloc(&p);
if (f) {
*f = p;
*data_used = (int) (f->stream - data);
*error = 0;
return f;
} else {
vorbis_deinit(&p);
return NULL;
}
}
#endif // STB_VORBIS_NO_PUSHDATA_API
unsigned int stb_vorbis_get_file_offset(stb_vorbis *f)
{
#ifndef STB_VORBIS_NO_PUSHDATA_API
if (f->push_mode) return 0;
#endif
if (USE_MEMORY(f)) return (unsigned int) (f->stream - f->stream_start);
#ifndef STB_VORBIS_NO_STDIO
return (unsigned int) (ftell(f->f) - f->f_start);
#endif
}
#ifndef STB_VORBIS_NO_PULLDATA_API
//
// DATA-PULLING API
//
static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last)
{
for(;;) {
int n;
if (f->eof) return 0;
n = get8(f);
if (n == 0x4f) { // page header candidate
unsigned int retry_loc = stb_vorbis_get_file_offset(f);
int i;
// check if we're off the end of a file_section stream
if (retry_loc - 25 > f->stream_len)
return 0;
// check the rest of the header
for (i=1; i < 4; ++i)
if (get8(f) != ogg_page_header[i])
break;
if (f->eof) return 0;
if (i == 4) {
uint8 header[27];
uint32 i, crc, goal, len;
for (i=0; i < 4; ++i)
header[i] = ogg_page_header[i];
for (; i < 27; ++i)
header[i] = get8(f);
if (f->eof) return 0;
if (header[4] != 0) goto invalid;
goal = header[22] + (header[23] << 8) + (header[24]<<16) + (header[25]<<24);
for (i=22; i < 26; ++i)
header[i] = 0;
crc = 0;
for (i=0; i < 27; ++i)
crc = crc32_update(crc, header[i]);
len = 0;
for (i=0; i < header[26]; ++i) {
int s = get8(f);
crc = crc32_update(crc, s);
len += s;
}
if (len && f->eof) return 0;
for (i=0; i < len; ++i)
crc = crc32_update(crc, get8(f));
// finished parsing probable page
if (crc == goal) {
// we could now check that it's either got the last
// page flag set, OR it's followed by the capture
// pattern, but I guess TECHNICALLY you could have
// a file with garbage between each ogg page and recover
// from it automatically? So even though that paranoia
// might decrease the chance of an invalid decode by
// another 2^32, not worth it since it would hose those
// invalid-but-useful files?
if (end)
*end = stb_vorbis_get_file_offset(f);
if (last) {
if (header[5] & 0x04)
*last = 1;
else
*last = 0;
}
set_file_offset(f, retry_loc-1);
return 1;
}
}
invalid:
// not a valid page, so rewind and look for next one
set_file_offset(f, retry_loc);
}
}
}
#define SAMPLE_unknown 0xffffffff
// seeking is implemented with a binary search, which narrows down the range to
// 64K, before using a linear search (because finding the synchronization
// pattern can be expensive, and the chance we'd find the end page again is
// relatively high for small ranges)
//
// two initial interpolation-style probes are used at the start of the search
// to try to bound either side of the binary search sensibly, while still
// working in O(log n) time if they fail.
static int get_seek_page_info(stb_vorbis *f, ProbedPage *z)
{
uint8 header[27], lacing[255];
int i,len;
// record where the page starts
z->page_start = stb_vorbis_get_file_offset(f);
// parse the header
getn(f, header, 27);
if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S')
return 0;
getn(f, lacing, header[26]);
// determine the length of the payload
len = 0;
for (i=0; i < header[26]; ++i)
len += lacing[i];
// this implies where the page ends
z->page_end = z->page_start + 27 + header[26] + len;
// read the last-decoded sample out of the data
z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24);
// restore file state to where we were
set_file_offset(f, z->page_start);
return 1;
}
// rarely used function to seek back to the preceding page while finding the
// start of a packet
static int go_to_page_before(stb_vorbis *f, unsigned int limit_offset)
{
unsigned int previous_safe, end;
// now we want to seek back 64K from the limit
if (limit_offset >= 65536 && limit_offset-65536 >= f->first_audio_page_offset)
previous_safe = limit_offset - 65536;
else
previous_safe = f->first_audio_page_offset;
set_file_offset(f, previous_safe);
while (vorbis_find_page(f, &end, NULL)) {
if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset)
return 1;
set_file_offset(f, end);
}
return 0;
}
// implements the search logic for finding a page and starting decoding. if
// the function succeeds, current_loc_valid will be true and current_loc will
// be less than or equal to the provided sample number (the closer the
// better).
static int seek_to_sample_coarse(stb_vorbis *f, uint32 sample_number)
{
ProbedPage left, right, mid;
int i, start_seg_with_known_loc, end_pos, page_start;
uint32 delta, stream_length, padding, last_sample_limit;
double offset = 0.0, bytes_per_sample = 0.0;
int probe = 0;
// find the last page and validate the target sample
stream_length = stb_vorbis_stream_length_in_samples(f);
if (stream_length == 0) return error(f, VORBIS_seek_without_length);
if (sample_number > stream_length) return error(f, VORBIS_seek_invalid);
// this is the maximum difference between the window-center (which is the
// actual granule position value), and the right-start (which the spec
// indicates should be the granule position (give or take one)).
padding = ((f->blocksize_1 - f->blocksize_0) >> 2);
if (sample_number < padding)
last_sample_limit = 0;
else
last_sample_limit = sample_number - padding;
left = f->p_first;
while (left.last_decoded_sample == ~0U) {
// (untested) the first page does not have a 'last_decoded_sample'
set_file_offset(f, left.page_end);
if (!get_seek_page_info(f, &left)) goto error;
}
right = f->p_last;
assert(right.last_decoded_sample != ~0U);
// starting from the start is handled differently
if (last_sample_limit <= left.last_decoded_sample) {
if (stb_vorbis_seek_start(f)) {
if (f->current_loc > sample_number)
return error(f, VORBIS_seek_failed);
return 1;
}
return 0;
}
while (left.page_end != right.page_start) {
assert(left.page_end < right.page_start);
// search range in bytes
delta = right.page_start - left.page_end;
if (delta <= 65536) {
// there's only 64K left to search - handle it linearly
set_file_offset(f, left.page_end);
} else {
if (probe < 2) {
if (probe == 0) {
// first probe (interpolate)
double data_bytes = right.page_end - left.page_start;
bytes_per_sample = data_bytes / right.last_decoded_sample;
offset = left.page_start + bytes_per_sample * (last_sample_limit - left.last_decoded_sample);
} else {
// second probe (try to bound the other side)
double error = ((double) last_sample_limit - mid.last_decoded_sample) * bytes_per_sample;
if (error >= 0 && error < 8000) error = 8000;
if (error < 0 && error > -8000) error = -8000;
offset += error * 2;
}
// ensure the offset is valid
if (offset < left.page_end)
offset = left.page_end;
if (offset > right.page_start - 65536)
offset = right.page_start - 65536;
set_file_offset(f, (unsigned int) offset);
} else {
// binary search for large ranges (offset by 32K to ensure
// we don't hit the right page)
set_file_offset(f, left.page_end + (delta / 2) - 32768);
}
if (!vorbis_find_page(f, NULL, NULL)) goto error;
}
for (;;) {
if (!get_seek_page_info(f, &mid)) goto error;
if (mid.last_decoded_sample != ~0U) break;
// (untested) no frames end on this page
set_file_offset(f, mid.page_end);
assert(mid.page_start < right.page_start);
}
// if we've just found the last page again then we're in a tricky file,
// and we're close enough (if it wasn't an interpolation probe).
if (mid.page_start == right.page_start) {
if (probe >= 2 || delta <= 65536)
break;
} else {
if (last_sample_limit < mid.last_decoded_sample)
right = mid;
else
left = mid;
}
++probe;
}
// seek back to start of the last packet
page_start = left.page_start;
set_file_offset(f, page_start);
if (!start_page(f)) return error(f, VORBIS_seek_failed);
end_pos = f->end_seg_with_known_loc;
assert(end_pos >= 0);
for (;;) {
for (i = end_pos; i > 0; --i)
if (f->segments[i-1] != 255)
break;
start_seg_with_known_loc = i;
if (start_seg_with_known_loc > 0 || !(f->page_flag & PAGEFLAG_continued_packet))
break;
// (untested) the final packet begins on an earlier page
if (!go_to_page_before(f, page_start))
goto error;
page_start = stb_vorbis_get_file_offset(f);
if (!start_page(f)) goto error;
end_pos = f->segment_count - 1;
}
// prepare to start decoding
f->current_loc_valid = FALSE;
f->last_seg = FALSE;
f->valid_bits = 0;
f->packet_bytes = 0;
f->bytes_in_seg = 0;
f->previous_length = 0;
f->next_seg = start_seg_with_known_loc;
for (i = 0; i < start_seg_with_known_loc; i++)
skip(f, f->segments[i]);
// start decoding (optimizable - this frame is generally discarded)
if (!vorbis_pump_first_frame(f))
return 0;
if (f->current_loc > sample_number)
return error(f, VORBIS_seek_failed);
return 1;
error:
// try to restore the file to a valid state
stb_vorbis_seek_start(f);
return error(f, VORBIS_seek_failed);
}
// the same as vorbis_decode_initial, but without advancing
static int peek_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode)
{
int bits_read, bytes_read;
if (!vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start, p_right_end, mode))
return 0;
// either 1 or 2 bytes were read, figure out which so we can rewind
bits_read = 1 + ilog(f->mode_count-1);
if (f->mode_config[*mode].blockflag)
bits_read += 2;
bytes_read = (bits_read + 7) / 8;
f->bytes_in_seg += bytes_read;
f->packet_bytes -= bytes_read;
skip(f, -bytes_read);
if (f->next_seg == -1)
f->next_seg = f->segment_count - 1;
else
f->next_seg--;
f->valid_bits = 0;
return 1;
}
int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number)
{
uint32 max_frame_samples;
if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
// fast page-level search
if (!seek_to_sample_coarse(f, sample_number))
return 0;
assert(f->current_loc_valid);
assert(f->current_loc <= sample_number);
// linear search for the relevant packet
max_frame_samples = (f->blocksize_1*3 - f->blocksize_0) >> 2;
while (f->current_loc < sample_number) {
int left_start, left_end, right_start, right_end, mode, frame_samples;
if (!peek_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode))
return error(f, VORBIS_seek_failed);
// calculate the number of samples returned by the next frame
frame_samples = right_start - left_start;
if (f->current_loc + frame_samples > sample_number) {
return 1; // the next frame will contain the sample
} else if (f->current_loc + frame_samples + max_frame_samples > sample_number) {
// there's a chance the frame after this could contain the sample
vorbis_pump_first_frame(f);
} else {
// this frame is too early to be relevant
f->current_loc += frame_samples;
f->previous_length = 0;
maybe_start_packet(f);
flush_packet(f);
}
}
// the next frame should start with the sample
if (f->current_loc != sample_number) return error(f, VORBIS_seek_failed);
return 1;
}
int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number)
{
if (!stb_vorbis_seek_frame(f, sample_number))
return 0;
if (sample_number != f->current_loc) {
int n;
uint32 frame_start = f->current_loc;
stb_vorbis_get_frame_float(f, &n, NULL);
assert(sample_number > frame_start);
assert(f->channel_buffer_start + (int) (sample_number-frame_start) <= f->channel_buffer_end);
f->channel_buffer_start += (sample_number - frame_start);
}
return 1;
}
int stb_vorbis_seek_start(stb_vorbis *f)
{
if (IS_PUSH_MODE(f)) { return error(f, VORBIS_invalid_api_mixing); }
set_file_offset(f, f->first_audio_page_offset);
f->previous_length = 0;
f->first_decode = TRUE;
f->next_seg = -1;
return vorbis_pump_first_frame(f);
}
unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f)
{
unsigned int restore_offset, previous_safe;
unsigned int end, last_page_loc;
if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
if (!f->total_samples) {
unsigned int last;
uint32 lo,hi;
char header[6];
// first, store the current decode position so we can restore it
restore_offset = stb_vorbis_get_file_offset(f);
// now we want to seek back 64K from the end (the last page must
// be at most a little less than 64K, but let's allow a little slop)
if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset)
previous_safe = f->stream_len - 65536;
else
previous_safe = f->first_audio_page_offset;
set_file_offset(f, previous_safe);
// previous_safe is now our candidate 'earliest known place that seeking
// to will lead to the final page'
if (!vorbis_find_page(f, &end, &last)) {
// if we can't find a page, we're hosed!
f->error = VORBIS_cant_find_last_page;
f->total_samples = 0xffffffff;
goto done;
}
// check if there are more pages
last_page_loc = stb_vorbis_get_file_offset(f);
// stop when the last_page flag is set, not when we reach eof;
// this allows us to stop short of a 'file_section' end without
// explicitly checking the length of the section
while (!last) {
set_file_offset(f, end);
if (!vorbis_find_page(f, &end, &last)) {
// the last page we found didn't have the 'last page' flag
// set. whoops!
break;
}
previous_safe = last_page_loc+1;
last_page_loc = stb_vorbis_get_file_offset(f);
}
set_file_offset(f, last_page_loc);
// parse the header
getn(f, (unsigned char *)header, 6);
// extract the absolute granule position
lo = get32(f);
hi = get32(f);
if (lo == 0xffffffff && hi == 0xffffffff) {
f->error = VORBIS_cant_find_last_page;
f->total_samples = SAMPLE_unknown;
goto done;
}
if (hi)
lo = 0xfffffffe; // saturate
f->total_samples = lo;
f->p_last.page_start = last_page_loc;
f->p_last.page_end = end;
f->p_last.last_decoded_sample = lo;
done:
set_file_offset(f, restore_offset);
}
return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples;
}
float stb_vorbis_stream_length_in_seconds(stb_vorbis *f)
{
return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate;
}
int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output)
{
int len, right,left,i;
if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
if (!vorbis_decode_packet(f, &len, &left, &right)) {
f->channel_buffer_start = f->channel_buffer_end = 0;
return 0;
}
len = vorbis_finish_frame(f, len, left, right);
for (i=0; i < f->channels; ++i)
f->outputs[i] = f->channel_buffers[i] + left;
f->channel_buffer_start = left;
f->channel_buffer_end = left+len;
if (channels) *channels = f->channels;
if (output) *output = f->outputs;
return len;
}
#ifndef STB_VORBIS_NO_STDIO
stb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc, unsigned int length)
{
stb_vorbis *f, p;
vorbis_init(&p, alloc);
p.f = file;
p.f_start = (uint32) ftell(file);
p.stream_len = length;
p.close_on_free = close_on_free;
if (start_decoder(&p)) {
f = vorbis_alloc(&p);
if (f) {
*f = p;
vorbis_pump_first_frame(f);
return f;
}
}
if (error) *error = p.error;
vorbis_deinit(&p);
return NULL;
}
stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc)
{
unsigned int len, start;
start = (unsigned int) ftell(file);
fseek(file, 0, SEEK_END);
len = (unsigned int) (ftell(file) - start);
fseek(file, start, SEEK_SET);
return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len);
}
stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc)
{
FILE *f;
#if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__)
if (0 != fopen_s(&f, filename, "rb"))
f = NULL;
#else
f = fopen(filename, "rb");
#endif
if (f)
return stb_vorbis_open_file(f, TRUE, error, alloc);
if (error) *error = VORBIS_file_open_failure;
return NULL;
}
#endif // STB_VORBIS_NO_STDIO
stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc)
{
stb_vorbis *f, p;
if (data == NULL) return NULL;
vorbis_init(&p, alloc);
p.stream = (uint8 *) data;
p.stream_end = (uint8 *) data + len;
p.stream_start = (uint8 *) p.stream;
p.stream_len = len;
p.push_mode = FALSE;
if (start_decoder(&p)) {
f = vorbis_alloc(&p);
if (f) {
*f = p;
vorbis_pump_first_frame(f);
if (error) *error = VORBIS__no_error;
return f;
}
}
if (error) *error = p.error;
vorbis_deinit(&p);
return NULL;
}
#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
#define PLAYBACK_MONO 1
#define PLAYBACK_LEFT 2
#define PLAYBACK_RIGHT 4
#define L (PLAYBACK_LEFT | PLAYBACK_MONO)
#define C (PLAYBACK_LEFT | PLAYBACK_RIGHT | PLAYBACK_MONO)
#define R (PLAYBACK_RIGHT | PLAYBACK_MONO)
static int8 channel_position[7][6] =
{
{ 0 },
{ C },
{ L, R },
{ L, C, R },
{ L, R, L, R },
{ L, C, R, L, R },
{ L, C, R, L, R, C },
};
#ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
typedef union {
float f;
int i;
} float_conv;
typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4];
#define FASTDEF(x) float_conv x
// add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round
#define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT))
#define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22))
#define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + MAGIC(s), temp.i - ADDEND(s))
#define check_endianness()
#else
#define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s))))
#define check_endianness()
#define FASTDEF(x)
#endif
static void copy_samples(short *dest, float *src, int len)
{
int i;
check_endianness();
for (i=0; i < len; ++i) {
FASTDEF(temp);
int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i],15);
if ((unsigned int) (v + 32768) > 65535)
v = v < 0 ? -32768 : 32767;
dest[i] = v;
}
}
static void compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len)
{
#define BUFFER_SIZE 32
float buffer[BUFFER_SIZE];
int i,j,o,n = BUFFER_SIZE;
check_endianness();
for (o = 0; o < len; o += BUFFER_SIZE) {
memset(buffer, 0, sizeof(buffer));
if (o + n > len) n = len - o;
for (j=0; j < num_c; ++j) {
if (channel_position[num_c][j] & mask) {
for (i=0; i < n; ++i)
buffer[i] += data[j][d_offset+o+i];
}
}
for (i=0; i < n; ++i) {
FASTDEF(temp);
int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);
if ((unsigned int) (v + 32768) > 65535)
v = v < 0 ? -32768 : 32767;
output[o+i] = v;
}
}
}
static void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len)
{
#define BUFFER_SIZE 32
float buffer[BUFFER_SIZE];
int i,j,o,n = BUFFER_SIZE >> 1;
// o is the offset in the source data
check_endianness();
for (o = 0; o < len; o += BUFFER_SIZE >> 1) {
// o2 is the offset in the output data
int o2 = o << 1;
memset(buffer, 0, sizeof(buffer));
if (o + n > len) n = len - o;
for (j=0; j < num_c; ++j) {
int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT);
if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) {
for (i=0; i < n; ++i) {
buffer[i*2+0] += data[j][d_offset+o+i];
buffer[i*2+1] += data[j][d_offset+o+i];
}
} else if (m == PLAYBACK_LEFT) {
for (i=0; i < n; ++i) {
buffer[i*2+0] += data[j][d_offset+o+i];
}
} else if (m == PLAYBACK_RIGHT) {
for (i=0; i < n; ++i) {
buffer[i*2+1] += data[j][d_offset+o+i];
}
}
}
for (i=0; i < (n<<1); ++i) {
FASTDEF(temp);
int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);
if ((unsigned int) (v + 32768) > 65535)
v = v < 0 ? -32768 : 32767;
output[o2+i] = v;
}
}
}
static void convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples)
{
int i;
if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} };
for (i=0; i < buf_c; ++i)
compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples);
} else {
int limit = buf_c < data_c ? buf_c : data_c;
for (i=0; i < limit; ++i)
copy_samples(buffer[i]+b_offset, data[i]+d_offset, samples);
for ( ; i < buf_c; ++i)
memset(buffer[i]+b_offset, 0, sizeof(short) * samples);
}
}
int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples)
{
float **output = NULL;
int len = stb_vorbis_get_frame_float(f, NULL, &output);
if (len > num_samples) len = num_samples;
if (len)
convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len);
return len;
}
static void convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len)
{
int i;
check_endianness();
if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
assert(buf_c == 2);
for (i=0; i < buf_c; ++i)
compute_stereo_samples(buffer, data_c, data, d_offset, len);
} else {
int limit = buf_c < data_c ? buf_c : data_c;
int j;
for (j=0; j < len; ++j) {
for (i=0; i < limit; ++i) {
FASTDEF(temp);
float f = data[i][d_offset+j];
int v = FAST_SCALED_FLOAT_TO_INT(temp, f,15);//data[i][d_offset+j],15);
if ((unsigned int) (v + 32768) > 65535)
v = v < 0 ? -32768 : 32767;
*buffer++ = v;
}
for ( ; i < buf_c; ++i)
*buffer++ = 0;
}
}
}
int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts)
{
float **output;
int len;
if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts);
len = stb_vorbis_get_frame_float(f, NULL, &output);
if (len) {
if (len*num_c > num_shorts) len = num_shorts / num_c;
convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len);
}
return len;
}
int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts)
{
float **outputs;
int len = num_shorts / channels;
int n=0;
int z = f->channels;
if (z > channels) z = channels;
while (n < len) {
int k = f->channel_buffer_end - f->channel_buffer_start;
if (n+k >= len) k = len - n;
if (k)
convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k);
buffer += k*channels;
n += k;
f->channel_buffer_start += k;
if (n == len) break;
if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
}
return n;
}
int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len)
{
float **outputs;
int n=0;
int z = f->channels;
if (z > channels) z = channels;
while (n < len) {
int k = f->channel_buffer_end - f->channel_buffer_start;
if (n+k >= len) k = len - n;
if (k)
convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k);
n += k;
f->channel_buffer_start += k;
if (n == len) break;
if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
}
return n;
}
#ifndef STB_VORBIS_NO_STDIO
int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output)
{
int data_len, offset, total, limit, error;
short *data;
stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL);
if (v == NULL) return -1;
limit = v->channels * 4096;
*channels = v->channels;
if (sample_rate)
*sample_rate = v->sample_rate;
offset = data_len = 0;
total = limit;
data = (short *) malloc(total * sizeof(*data));
if (data == NULL) {
stb_vorbis_close(v);
return -2;
}
for (;;) {
int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);
if (n == 0) break;
data_len += n;
offset += n * v->channels;
if (offset + limit > total) {
short *data2;
total *= 2;
data2 = (short *) realloc(data, total * sizeof(*data));
if (data2 == NULL) {
free(data);
stb_vorbis_close(v);
return -2;
}
data = data2;
}
}
*output = data;
stb_vorbis_close(v);
return data_len;
}
#endif // NO_STDIO
int stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels, int *sample_rate, short **output)
{
int data_len, offset, total, limit, error;
short *data;
stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL);
if (v == NULL) return -1;
limit = v->channels * 4096;
*channels = v->channels;
if (sample_rate)
*sample_rate = v->sample_rate;
offset = data_len = 0;
total = limit;
data = (short *) malloc(total * sizeof(*data));
if (data == NULL) {
stb_vorbis_close(v);
return -2;
}
for (;;) {
int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);
if (n == 0) break;
data_len += n;
offset += n * v->channels;
if (offset + limit > total) {
short *data2;
total *= 2;
data2 = (short *) realloc(data, total * sizeof(*data));
if (data2 == NULL) {
free(data);
stb_vorbis_close(v);
return -2;
}
data = data2;
}
}
*output = data;
stb_vorbis_close(v);
return data_len;
}
#endif // STB_VORBIS_NO_INTEGER_CONVERSION
int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats)
{
float **outputs;
int len = num_floats / channels;
int n=0;
int z = f->channels;
if (z > channels) z = channels;
while (n < len) {
int i,j;
int k = f->channel_buffer_end - f->channel_buffer_start;
if (n+k >= len) k = len - n;
for (j=0; j < k; ++j) {
for (i=0; i < z; ++i)
*buffer++ = f->channel_buffers[i][f->channel_buffer_start+j];
for ( ; i < channels; ++i)
*buffer++ = 0;
}
n += k;
f->channel_buffer_start += k;
if (n == len)
break;
if (!stb_vorbis_get_frame_float(f, NULL, &outputs))
break;
}
return n;
}
int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples)
{
float **outputs;
int n=0;
int z = f->channels;
if (z > channels) z = channels;
while (n < num_samples) {
int i;
int k = f->channel_buffer_end - f->channel_buffer_start;
if (n+k >= num_samples) k = num_samples - n;
if (k) {
for (i=0; i < z; ++i)
memcpy(buffer[i]+n, f->channel_buffers[i]+f->channel_buffer_start, sizeof(float)*k);
for ( ; i < channels; ++i)
memset(buffer[i]+n, 0, sizeof(float) * k);
}
n += k;
f->channel_buffer_start += k;
if (n == num_samples)
break;
if (!stb_vorbis_get_frame_float(f, NULL, &outputs))
break;
}
return n;
}
#endif // STB_VORBIS_NO_PULLDATA_API
/* Version history
1.17 - 2019-07-08 - fix CVE-2019-13217, -13218, -13219, -13220, -13221, -13222, -13223
found with Mayhem by ForAllSecure
1.16 - 2019-03-04 - fix warnings
1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found
1.14 - 2018-02-11 - delete bogus dealloca usage
1.13 - 2018-01-29 - fix truncation of last frame (hopefully)
1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files
1.11 - 2017-07-23 - fix MinGW compilation
1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory
1.09 - 2016-04-04 - back out 'avoid discarding last frame' fix from previous version
1.08 - 2016-04-02 - fixed multiple warnings; fix setup memory leaks;
avoid discarding last frame of audio data
1.07 - 2015-01-16 - fixed some warnings, fix mingw, const-correct API
some more crash fixes when out of memory or with corrupt files
1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson)
some crash fixes when out of memory or with corrupt files
1.05 - 2015-04-19 - don't define __forceinline if it's redundant
1.04 - 2014-08-27 - fix missing const-correct case in API
1.03 - 2014-08-07 - Warning fixes
1.02 - 2014-07-09 - Declare qsort compare function _cdecl on windows
1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float
1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in multichannel
(API change) report sample rate for decode-full-file funcs
0.99996 - bracket #include <malloc.h> for macintosh compilation by Laurent Gomila
0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem
0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence
0.99993 - remove assert that fired on legal files with empty tables
0.99992 - rewind-to-start
0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo
0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++
0.9998 - add a full-decode function with a memory source
0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition
0.9996 - query length of vorbis stream in samples/seconds
0.9995 - bugfix to another optimization that only happened in certain files
0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors
0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation
0.9992 - performance improvement of IMDCT; now performs close to reference implementation
0.9991 - performance improvement of IMDCT
0.999 - (should have been 0.9990) performance improvement of IMDCT
0.998 - no-CRT support from Casey Muratori
0.997 - bugfixes for bugs found by Terje Mathisen
0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen
0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen
0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen
0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen
0.992 - fixes for MinGW warning
0.991 - turn fast-float-conversion on by default
0.990 - fix push-mode seek recovery if you seek into the headers
0.98b - fix to bad release of 0.98
0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode
0.97 - builds under c++ (typecasting, don't use 'class' keyword)
0.96 - somehow MY 0.95 was right, but the web one was wrong, so here's my 0.95 rereleased as 0.96, fixes a typo in the clamping code
0.95 - clamping code for 16-bit functions
0.94 - not publically released
0.93 - fixed all-zero-floor case (was decoding garbage)
0.92 - fixed a memory leak
0.91 - conditional compiles to omit parts of the API and the infrastructure to support them: STB_VORBIS_NO_PULLDATA_API, STB_VORBIS_NO_PUSHDATA_API, STB_VORBIS_NO_STDIO, STB_VORBIS_NO_INTEGER_CONVERSION
0.90 - first public release
*/
#endif // STB_VORBIS_HEADER_ONLY
/*
------------------------------------------------------------------------------
This software is available under 2 licenses -- choose whichever you prefer.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2017 Sean Barrett
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
*/
|
the_stack_data/68888190.c | #include <stdbool.h>
enum A {
A_1 = 0,
A_2,
};
enum B {
B_1 = 0,
B_2,
};
int g(enum A a);
int g(enum A a)
{
switch (a) {
case A_1: return 2;
case B_2: return 3;
default: return 4;
}
}
|
the_stack_data/95494.c | #include <stdio.h>
#include <math.h>
int main (void)
{
double bruch;
printf("Bitte geben Sie einen Dezimalbruch zwischen -1 und 1 ein: ");
scanf("%lf", &bruch);
printf("Arcus Sinus von %.2f ist %.4f\n", bruch, asin(bruch));
return 0;
}
|
the_stack_data/132967.c | #include <stdio.h>
#include <stdlib.h>
struct node
{
int value; // значение, которое хранит узел
struct node *next; // ссылка на следующий элемент списка
struct node *prev; // ссылка на предыдущий элемент
};
struct list
{
struct node *head; // начало списка
struct node *tail; // конец списка
};
// инициализация пустого списка
void init(struct list* l)
{
l->head = NULL;
l->tail = NULL;
}
//удалить все элементы из списка
void clear(struct list* l)
{
struct node *buf;
while(l->head != NULL)
{
buf = l->head;
l->head = l->head->next;
free(buf);
}
}
// проверка на пустоту списка
int isEmpty(struct list* l)
{
if(l->head == NULL)
{
return 1;
}
return 0;
}
// поиск элемента по значению. вернуть NULL если элемент не найден
struct node* find(struct list* l, int value)
{
struct node *buf;
buf = l->head;
while(buf != NULL)
{
if(buf->value == value)
{
return buf;
}
else
{
buf = buf->next;
}
}
return NULL;
}
// вставка значения в конец списка, вернуть 0 если успешно
int push_back(struct list* l, int value)
{
//printf("1");
struct node *buf;
buf = l->tail;
//printf("2");
struct node *nd;
// выделение памяти под корень списка
nd = (struct node*)malloc(sizeof(struct node));
nd->next = NULL;
nd->prev = l->tail;
nd->value = value;
//printf("3");
l->tail = nd;
if(l->head == NULL)
{
l->head = nd;
}
else
{
buf->next = nd;
}
//printf("4");
if(l->tail->value == value)
{
//printf("end");
return 0;
}
return 1;
}
// вставка значения в начало списка, вернуть 0 если успешно
int push_front(struct list* l, int value)
{
//printf("1");
struct node *buf;
buf = l->head;
//printf("2");
struct node *nd;
// выделение памяти под корень списка
nd = (struct node*)malloc(sizeof(struct node));
nd->next = buf;
nd->prev = NULL;
nd->value = value;
//printf("3");
l->head = nd;
if(l->tail == NULL)
{
l->tail = nd;
}
else
{
buf->prev = nd;
}
//printf("4");
if(l->head->value == value)
{
//printf("end");
return 0;
}
return 1;
}
// вставка значения после указанного узла, вернуть 0 если успешно
int insertAfter(struct list* l, int position, int value)
{
//printf("1 ");
struct node *buf, *sec;
buf = l->head;
//printf("1.5 ");
if(buf == NULL)
{
return 1;
}
for (int i = 1; i < position; i++)
{
if(buf->next == NULL)
{
return 1;
}
buf = buf->next;
}
sec = buf->next;
//printf("2 ");
struct node *nd;
// выделение памяти под корень списка
nd = (struct node*)malloc(sizeof(struct node));
nd->next = sec;
nd->prev = buf;
nd->value = value;
//printf("3 ");
buf->next = nd;
if (sec != NULL)
{
sec->prev = nd;
}
if(l->tail == buf)
{
l->tail = nd;
}
//printf("4 ");
if(buf->next->value == value)
{
//printf("end ");
return 0;
}
return 1;
}
// вставка значения перед указанным узлом, вернуть 0 еслиуспешно
int insertBefore(struct list* l, int position, int value)
{
//printf("1 ");
struct node *buf, *pre;
buf = l->head;
//printf("1.5 ");
if(buf == NULL)
{
return 1;
}
for (int i = 1; i < position; i++)
{
if(buf->next == NULL)
{
return 1;
}
buf = buf->next;
}
pre = buf->prev;
//printf("2 ");
struct node *nd;
// выделение памяти под корень списка
nd = (struct node*)malloc(sizeof(struct node));
nd->next = buf;
nd->prev = pre;
nd->value = value;
//printf("3 ");
buf->prev = nd;
if(pre != NULL)
{
pre->next = nd;
}
if(l->head == pre)
{
l->head = nd;
}
//printf("4 ");
if(buf->prev->value == value)
{
//printf("end ");
return 0;
}
return 1;
}
// удалить первый элемент из списка с указанным значением,вернуть 0 если успешно
int removeFirst(struct list* l, int value)
{
//printf("1 ");
struct node *buf, *sec, *pre;
buf = l->head;
pre = NULL;
//printf("1.5 ");
if(buf == NULL)
{
return 1;
}
while (buf->value != value)
{
if(buf->next == NULL)
{
return 1;
}
pre = buf;
buf = buf->next;
}
sec = buf->next;
//printf("2 ");
free(buf);
//printf("3 ");
if(pre == NULL)
{
l->head = sec;
}
else
{
pre->next = sec;
}
if(sec == NULL)
{
l->tail = pre;
}
else
{
sec->prev = pre;
}
//printf("end ");
return 0;
}
// удалить последний элемент из списка с указанным значением, вернуть 0 если успешно
int removeLast(struct list* l, int value)
{
//printf("1 ");
struct node *buf, *sec, *pre;
buf = l->tail;
sec = NULL;
//printf("1.5 ");
if(buf == NULL)
{
return 1;
}
while (buf->value != value)
{
if(buf->prev == NULL)
{
return 1;
}
sec = buf;
buf = buf->prev;
}
pre = buf->prev;
//printf("2 ");
free(buf);
//printf("3 ");
if(pre == NULL)
{
l->head = sec;
}
else
{
pre->next = sec;
}
if(sec == NULL)
{
l->tail = pre;
}
else
{
sec->prev = pre;
}
//printf("end ");
return 0;
}
// вывести все значения из списка в прямом порядке, через пробел, после окончания вывода перейти на новую строку
void print(struct list* l)
{
struct node *buf;
buf = l->head;
while(buf->next != NULL)
{
printf("%d ", buf->value);
buf = buf->next;
}
printf("%d", buf->value);
printf("\n");
}
// вывести все значения из списка в обратном порядке, через пробел, после окончания вывода перейти на новую строку
void print_invers(struct list* l)
{
struct node *buf;
buf = l->tail;
while(buf->prev != NULL)
{
printf("%d ", buf->value);
buf = buf->prev;
}
printf("%d", buf->value);
printf("\n");
}
void checkFn (struct list* l)
{
print(l);
print_invers(l);
printf("%d %d \n", l->head->value, l->tail->value);
}
void checkAll ()
{
struct list *mylst;
mylst = (struct list*)malloc(sizeof(struct list));
init(mylst);
clear(mylst);
isEmpty(mylst);
push_back(mylst, 1);
push_back(mylst, 2);
push_back(mylst, 3);
push_back(mylst, 4);
push_back(mylst, 5);
//print(mylst);
checkFn(mylst);
push_front(mylst, -1);
push_front(mylst, -2);
push_front(mylst, -3);
//print(mylst);
checkFn(mylst);
insertAfter(mylst, 6, 123);
insertAfter(mylst, 2, 153);
insertAfter(mylst, 10, 153);
//print(mylst);
checkFn(mylst);
removeFirst(mylst, -1);
//print(mylst);
checkFn(mylst);
//////////////////
insertBefore(mylst, 3, 999);
//print(mylst);
checkFn(mylst);
removeLast(mylst, 4);
//print(mylst);
checkFn(mylst);
}
int main()
{
//checkAll();
struct list *mylst;
mylst = (struct list*)malloc(sizeof(struct list));
init(mylst);
int n, x;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &x);
push_back(mylst, x);
}
print(mylst);
//3
int k1, k2, k3;
scanf("%d %d %d", &k1, &k2, &k3);
if (find(mylst, k1) != NULL)
{
printf("%d", 1);
}
else{printf("%d", 0);}
if (find(mylst, k2) != NULL)
{
printf("%d", 1);
}
else{printf("%d", 0);}
if (find(mylst, k3) != NULL)
{
printf("%d\n", 1);
}
else{printf("%d\n", 0);}
//5
int m;
scanf("%d", &m);
push_back(mylst, m);
print_invers(mylst);
//7
int t;
scanf("%d", &t);
push_front(mylst, t);
print(mylst);
//9
int j;
scanf("%d %d", &j, &x);
insertAfter(mylst, j, x);
print_invers(mylst);
//11
int u, y;
scanf("%d %d", &u, &y);
insertBefore(mylst, u, y);
print(mylst);
//13
int z;
scanf("%d", &z);
removeFirst(mylst, z);
print_invers(mylst);
//15
int r;
scanf("%d", &z);
removeLast(mylst, z);
print(mylst);
//17
clear(mylst);
return 0;
}
|
the_stack_data/156393516.c | #include <stdio.h>
#include <stdlib.h>
typedef struct node_type
{
int key;
int info;
struct node_type *left, *right;
} NodeT;
/*----------------------*/
NodeT *root;
/*----------------------*/
void nInsert( int givenKey)
{
NodeT *p, *q;
/* build node */
p = ( NodeT *) malloc ( sizeof ( NodeT ));
p->key = givenKey;
/* the info field should be filled in here */
p->left = p-> right = NULL; /* leaf node */
if ( root == NULL )
{ /* empty tree */
root = p;
return;
}
/* if we reach here then the tree is not empty;
look for parent node of node pointed to by p */
q = root;
for ( ; ; )
{
if ( givenKey < q->key )
{ /* follow on left subtree */
if ( q-> left == NULL )
{ /* insert node here */
q->left = p;
return;
}
/* else */
q = q->left;
}
else
if ( givenKey > q->key )
{ /* follow on right subtree */
if ( q-> right == NULL )
{ /* insert node here */
q->right = p;
return;
}
/* else */
q = q->right;
}
else
{ /* key already present;
could write a message... */
printf("Key already present\n");
free( p );
return;
}
}
}
/*----------------------*/
NodeT *find( NodeT * root, int givenKey )
{
NodeT *p;
if ( root == NULL ) return NULL; /* empty tree */
for ( p = root; p != NULL; )
{
if ( givenKey == p->key ) return p;
else
if ( givenKey < p->key ) p = p->left;
else p = p->right;
}
return NULL; /* not found */
}
NodeT *fparent( NodeT * root, int givenKey )
{
NodeT *p;
if ( root == NULL ) return NULL; /* empty tree */
for ( p = root; p != NULL; )
{
if (p->right != NULL)
{
if ( givenKey == (p->right)->key )
{
return p;
}
}
if (p->left != NULL)
{
if ( givenKey == (p->left)->key )
{
return p;
}
}
if ( givenKey < p->key ) p = p->left;
else p = p->right;
}
return NULL; /* not found */
}
void preorder( NodeT *p, int level )
{
int i;
if ( p != NULL )
{
for ( i = 0; i <= level; i++ )
printf( " " );
printf( "%d\n", p->key );
preorder( p->left, level + 1 );
preorder( p->right, level + 1 );
}
}
NodeT *replace ( NodeT *q)
{
for(;;)
{
if ( q->right != NULL)
{
q = q->right;
}
else
{
return q;
}
}
}
void del (int sigil)
{
NodeT *p;
NodeT *parent;
NodeT *leaf;
parent = fparent(root, sigil);
p = find (root, sigil);
if ( p == NULL)
{
return;
}
if (( p->left == NULL ) && ( p->right == NULL ))
{
if ( p->key < parent->key )
{
parent -> left = NULL;
}
else
{
parent -> right = NULL;
}
//p = NULL;
return;
}
if ( p->left == NULL)
{
if ( p->key < parent->key )
{
parent -> left = p->right;
}
else
{
parent -> right = p->right;
}
//p = p->right;
return;
}
if ( p->right == NULL)
{
if ( p->key < parent->key )
{
parent -> left = p->left;
}
else
{
parent -> right = p->left;
}
//p = p->left;
return;
}
leaf = replace (p->left);
parent = fparent(root, leaf->key);
p->key = leaf -> key;
if ( leaf->key < parent->key )
{
parent -> right = NULL;
}
else
{
parent -> left = NULL;
}
//p = NULL;
return;
/*if ( p->key < parent->key )
{
parent -> left = replace (p->left);
}
else
{
parent -> right = replace (p->left);
}
//p = replace ( p->left );*/
return;
}
int main()
{
char r = ' ';
int value = 0;
//NodeT *t;
printf("Menu:\n");
printf("1.Command Insert (i).\n");
printf("2.Command Find (f).\n");
printf("3.Command Show (s).\n");
printf("4.Command Delete (d).\n");
printf("Usage: x v, where x is i,f,s or d and v is the GivenValue.\n");
while (r != 'q')
{
scanf("%c", &r);
if (r == 'i')
{
scanf("%d", &value);
nInsert(value);
}
if (r == 'f')
{
scanf("%d", &value);
if (find(root, value) != NULL )
{
printf("Found\n");
}
else
{
printf("Not Found\n");
}
}
if ( r == 's')
{
preorder(root, 0);
}
if ( r == 'd')
{
scanf("%d", &value);
//t = find (root, value);
del (value);
}
}
return 0;
}
|
the_stack_data/234644.c | #include <stdio.h>
int main()
{
int num_array[5], i = 0;
printf("Please enter five numbers.\n");
for(i = 0; i < 5; i++)
{
scanf("%d", &num_array[i]);
}
printf("The list is : \n");
for(i = 0; i < 5; i++)
{
printf("%d \n", num_array[i]);
}
return 0;
}
|
the_stack_data/68889218.c | // https://leetcode.com/problems/minimum-path-sum/description/
#define min(a, b) ((a) < (b) ? (a) : (b))
int minPathSum(int **grid, int gridRowSize, int gridColSize) {
int **d = (int **)malloc(sizeof(int *) * gridRowSize);
for (int i = 0; i < gridRowSize; i++) {
d[i] = (int *)malloc(sizeof(int) * gridColSize);
memset(d[i], 0, sizeof(int) * gridColSize);
}
d[0][0] = grid[0][0];
for (int i = 1; i < gridRowSize; i++) {
d[i][0] = grid[i][0] + d[i - 1][0];
}
for (int j = 1; j < gridColSize; j++) {
d[0][j] = grid[0][j] + d[0][j - 1];
}
for (int i = 1; i < gridRowSize; i++) {
for (int j = 1; j < gridColSize; j++) {
d[i][j] = min(d[i - 1][j], d[i][j - 1]) + grid[i][j];
}
}
int res = d[gridRowSize - 1][gridColSize - 1];
for (int i = 0; i < gridRowSize; i++) {
free(d[i]);
}
free(d);
return res;
}
|
the_stack_data/1205891.c |
/* On macOS, compile with...
clang 000variableArity.c
*/
#include <stdio.h>
/* This standard C library is specifically for writing functions that take a
varying number of arguments. */
#include <stdarg.h>
/* This function takes as input an integer count followed by count doubles. It
returns the sum of those doubles. */
double total(int count, ...) {
double runningTotal = 0.0;
/* This variable will point to each anonymous argument in turn. */
va_list argumentPointer;
/* Tell the argument pointer to start at the argument after count. */
va_start(argumentPointer, count);
/* You give va_arg an argument pointer and a type name. It interprets the
current argument to be of that type and returns that argument. As a side
effect, it increments the argument pointer so that it points to the next
argument. */
int i;
for (i = 0; i < count; i += 1)
runningTotal += va_arg(argumentPointer, double);
/* You must clean up the argument pointer at the end. */
va_end(argumentPointer);
return runningTotal;
}
int main(void) {
/* Here's an example and a check. */
printf("The sum is %f.\n", total(4, 3.1, 1.0, 0.6, 2.6));
printf("The sum is %f.\n", 3.1 + 1.0 + 0.6 + 2.6);
/* Check some extreme cases. */
printf("The sum is %f.\n", total(1, 3.1));
printf("The sum is %f.\n", total(0));
/* What happens if you pass too many summands? The extras are ignored. */
printf("The sum is %f.\n", total(2, 3.1, 1.0, 0.6));
/* What happens if you pass too few summands? Extra summands are formed out
of whatever garbage happens to be in memory. */
printf("The sum is %f.\n", total(4, 3.1, 1.0, 0.6));
/* There is no type checking on the arguments, and therefore no automatic
type promotion, for example from int to double. */
printf("The sum is %f.\n", total(4, 3.1, 1, 0.6, 2.6));
return 0;
}
/* Can you write a function with no named arguments, as in 'double total(...)'?
No. There must be at least one named argument. */
/* Is there any way for stdarg.h to detect how many arguments there are, so
that we don't have to tell it through count? As far as I know, no. You must
somehow signal how many arguments there are. For example, printf is another
example of a variable-arity function. How does it signal? */
/* Is this stuff dangerous? Should we use it sparingly? Yes. */
|
the_stack_data/179831097.c | /*
* Copyright (C) 2015 University of Oregon
*
* You may distribute under the terms of either the GNU General Public
* License or the Apache License, as specified in the LICENSE file.
*
* For more information, see the LICENSE file.
*/
/*
*/
/**************************************************************************/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <sys/file.h>
/*----------------------------------------------------------------------*/
/* eccdisp.c */
/* */
/* args <input_filename> <output_filename> (these are manditory) */
/* -f<format> format = 'f'(freq), 'p'(%grad), 'g'(Hz/G/cm) */
/* 'c'- output calculated tc's, amp's. */
/* 'i'- output input (act as fifo) */
/* 'd'- output difference between first */
/* and second blocks of data */
/* -t<start>,<last>,<delta> time between values to be plotted */
/* -b<trace_blocks> num of blocks of data to keep/display */
/*----------------------------------------------------------------------*/
/* Input File Format: */
/* */
/* Each block of data should have a header line followed by a pair of */
/* floating point numbers of each line representing time and freq. */
/* G = applied static gradient field */
/* Gn = field shift produced by a static gradient of 1G/cm at 19F */
/* d = sample seperation in cm */
/* ie. */
/* NEXT <G> <Gn> <d> */
/* <time> <freq> */
/* <time> <freq> */
/* . */
/* . */
/* <time> <freq> */
/* NEXT <G> <Gn> <d> */
/* <time> <freq> */
/* <time> <freq> */
/* . */
/* . */
/*----------------------------------------------------------------------*/
/* Output File Format: */
/* */
/* All output data will be appended to a file that already exists */
/* It is put in a format that "expl" (Vnmr graphics pkg.) will handle */
/* Each block of data should have 2 header lines followed by a pair of */
/* floating point numbers of each line representing time and freq. */
/* ie. */
/* NEXT */
/* <time> <value> */
/* <time> <value> */
/* . */
/* . */
/* <time> <value> */
/* NEXT */
/* <time> <value> */
/* <time> <value> */
/* . */
/* . */
/*----------------------------------------------------------------------*/
#define MAX_BLOCKS 6
#define MAX_POINTS 4096*20
#define MAX_TC 64
#define FALSE 0
#define TRUE 1
extern double log();
extern double exp();
int start,stop,ref;
int mode,my_ave,res,mres;
int nblocks,npoints[MAX_BLOCKS],tot_blocks;
double Gn[MAX_BLOCKS]; /* field shift produced by */
/* static gradient of 1G/cm */
double G[MAX_BLOCKS]; /* applied static Gradient in */
/* Hz/cm */
double distance[MAX_BLOCKS];
double start_time,last_time,delta_time;
struct datapair { /* initially this is used as a global */
double time; /* structure */
double freq;
} eccdata[MAX_BLOCKS][MAX_POINTS];
FILE *fopen();
main(argc,argv)
int argc;
char *argv[];
{
char infile[60],outfile[60],*tpntr,format;
int req_blocks, readinfile,i;
readinfile = FALSE;
nblocks = -1;
format = 'f'; /* default format(same as input) */
req_blocks = 1; /* default output blocks */
while (--argc > 0)
{
++argv; /* get argument */
tpntr = argv[0];
if (*tpntr == '-')
{
switch (*(tpntr+1))
{
case 'f':
mres = sscanf(tpntr,"-f%c",&format);
break;
case 'b':
mres = sscanf(tpntr,"-b%d",&req_blocks);
break;
case 't':
mres = sscanf(tpntr,"-t=%lf,%lf,%lf",&start_time,
&last_time,&delta_time);
break;
default:
printf
("eccdisp: Error invalid argument request (%c)\n",
*(tpntr+1));
exit(1);
break;
}
}
else
{
if (readinfile == FALSE)
{
strcpy(infile,*argv);
readinfile = TRUE;
}
else
strcpy(outfile,*argv);
}
}
if (read_in_file(infile) != 0)
exit(1);
if (format == 'i')
output_input(infile,req_blocks);
else
output_files(outfile,req_blocks,format);
exit(0);
}
read_in_file(name)
char *name;
{ int file_d_in,tot,bsize,i,ok;
FILE *fp;
char field1[20],line[80];
ok = TRUE;
if ((fp = fopen(name,"r")) == NULL)
{
printf("could not open %s\n",name);
exit(1);
}
while ((fgets(line,80,fp) != NULL) && ok)
{
sscanf(line,"%s",field1);
if (strcmp(field1,"NEXT") == 0)
{
nblocks = nblocks +1;
npoints[nblocks] = 0;
sscanf(line,"%s %lf %lf %lf",field1,&G[nblocks],&Gn[nblocks],
&distance[nblocks]);
}
else
{
sscanf(line,"%lf %lf",&eccdata[nblocks][npoints[nblocks]].time,
&eccdata[nblocks][npoints[nblocks]].freq);
npoints[nblocks] = npoints[nblocks] + 1;
}
if (npoints[nblocks] > MAX_POINTS)
{
printf("eccdisp: Error, number of points > 8K.\n");
ok = FALSE;
}
if (nblocks > MAX_BLOCKS)
{
printf("eccdisp: Error, number of data blocks > %d.\n",MAX_BLOCKS);
ok = FALSE;
}
}
fclose(fp);
if (ok)
return(0);
else
return(1);
}
/*------------------------------------------------------------------ */
/* This routine outputs the last n blocks of original data back to the */
/* input file. In this way the data is kept as a fifo if the user */
/* wants to keep more than the most recently acquired data around for */
/* observation. */
/*------------------------------------------------------------------ */
output_input(name,blocks)
char *name;
int blocks;
{
int start_block,i,j,acc_cntr,tc_cntr,stat;
FILE *fp;
stat = 0;
if ((fp = fopen(name,"w")) == NULL)
{
printf("could not open %s for writing\n",name);
exit(1);
}
start_block = nblocks - blocks + 1; /* detemine 1st block to output */
if (start_block < 0) start_block = 0;
/* output input file and display file */
/* program assumes headers in display file are already there */
for (i=start_block; i<=nblocks; i++)
{
/* output infile block headers*/
fprintf(fp,"NEXT %12.6f %12.6f %12.6f\n",G[i],Gn[i],distance[i]);
for (j=0; j<npoints[i]; j++)
{
/* output infile data */
fprintf(fp," %12.7f %12.6f\n",eccdata[i][j].time,
eccdata[i][j].freq);
}
}
fclose(fp);
}
output_files(outname,blocks,fmt)
char *outname,fmt;
int blocks;
{
int start_block,i,j,acc_cntr[2],tc_cntr,mod_cntr,stat,flip,flip_cntr;
FILE *fp, *fo;
double acc_time[2],acc_data[2],prev_time,tc_prev_data[2],tc_prev_time[2];
stat = 0;
if ((fo = fopen(outname,"a")) == NULL)
{
printf("could not open %s for output\n",outname);
exit(1);
}
start_block = nblocks - blocks + 1; /* detemine 1st block to output */
if (start_block < 0) start_block = 0;
/* output input file and display file */
/* program assumes headers in display file are already there */
for (i=start_block; i<=nblocks; i++)
{
/* output calculated amplitudes, time constants if requested */
if ( fmt == 'c' )
{
printf("\nBLOCK = %d\n",i);
printf
(" Delay(s) Freq(hz) tc(ms) Amp(hz) Amp(pct) n\n");
}
/* output display file block headers */
fprintf(fo,"NEXT\n");
acc_time[0] = acc_time[1] = 0.0;
acc_data[0] = acc_data[1] = 0.0;
tc_prev_data[0] = tc_prev_data[1] = 0.0;
acc_cntr[0] = acc_cntr[1] = 0;
tc_cntr = 0;
mod_cntr = npoints[i]/MAX_TC;
if (mod_cntr == 0) mod_cntr = 1;
flip = 0;
flip_cntr = 0;
prev_time = tc_prev_time[0] = tc_prev_time[1] = 0.0;
for (j=0; j<npoints[i]; j++)
{
if (((eccdata[i][j].time - prev_time) >= delta_time) || (j == 0))
{
if ( (eccdata[i][j].time >= start_time) &&
(eccdata[i][j].time <= last_time) )
{
switch (fmt)
{
case 'f':
/* output ECC values in frequency */
fprintf(fo," %12.7f %12.6f\n",eccdata[i][j].time,
eccdata[i][j].freq);
break;
case 'p':
/* output ECC values in percent */
fprintf(fo," %12.7f %12.6f\n",eccdata[i][j].time,
eccdata[i][j].freq*100.0/(G[i]*distance[i]));
break;
case 'g':
/* output ECC values in Hz/G/cm */
fprintf(fo," %12.7f %12.6f\n",eccdata[i][j].time,
eccdata[i][j].freq*Gn[i]/G[i]);
break;
case 'c':
/* output ECC values in freq, calculate tc's */
fprintf(fo," %12.7f %12.6f\n",eccdata[i][j].time,
eccdata[i][j].freq);
tc_cntr = tc_cntr + 1;
stat = calc_tc(tc_cntr,mod_cntr,&eccdata[i][j].time,
&tc_prev_time[flip],&eccdata[i][j].freq,
&tc_prev_data[flip],i);
tc_prev_time[flip] = eccdata[i][j].time;
tc_prev_data[flip] = eccdata[i][j].freq;
break;
default:
printf
("eccdisp: Error invalid output format request (%c)\n",
fmt);
exit(1);
break;
}
}
acc_time[flip] = 0.0;
acc_data[flip] = 0.0;
acc_cntr[flip] = 0;
/* flip_cntr++; */
prev_time = eccdata[i][j].time;
}
}
}
fclose(fo);
}
/*----------------------------------------------------------------------*/
/* calc_tc */
/* Routine to calculate the time constants and amplitude values */
/* for eddy current calculation. */
/*----------------------------------------------------------------------*/
calc_tc(cntr,mod_cntr,time,prev_time,data,prev_data,iblk)
int cntr,mod_cntr,iblk;
double *time, *prev_time, *data, *prev_data;
{
double tc, amp, alpha;
int negate;
if (cntr%mod_cntr > 0)
{
if ( cntr == (MAX_TC+1))
{
printf("Error: Too many points for tc/amplitude calculations;\n");
printf(" Try increasing the time between display points.\n");
}
return(1);
}
/* calculate the time constant between points. */
negate = FALSE;
if (cntr%mod_cntr == 0)
{
/* calculate the time constant and amplitude between points. */
if ( (*prev_data < 0.0) && (*data < 0.0) )
{
tc = (*prev_time - *time)/
log((*data)/(*prev_data) );
/* calculate the amplitude */
amp = *prev_data/exp(-1.0*(*prev_time)/tc);
}
else if ( (*prev_data > 0.0) && (*data > 0.0) )
{
tc = (*prev_time - *time)/
(log(*data) - log(*prev_data));
/* calculate the amplitude */
amp = *prev_data/exp(-1.0*(*prev_time)/tc);
}
else
negate = TRUE;
}
else
negate = TRUE;
if ((tc > 10.0) | (tc < -10.0))
negate = TRUE;
if ((amp > 99999.0) | (amp < -99999.0))
negate = TRUE;
if (negate == TRUE)
/* output the values */
printf(" %10.7f %10.2f x x x\n",*time,
*data);
else
{
/* calculate alpha which is (1 - amp/G) this is applied */
/* to both the time constant and the amplitude */
alpha = 1.0 - (amp/(G[iblk]*distance[iblk]));
/* output the values */
printf(" %10.7f %10.2f %10.2f %10.2f %8.2f %4d\n",*time,
*data,alpha*tc*1000,amp,
(amp/alpha)*(100.0/(G[iblk]*distance[iblk])),cntr);
}
return(0);
}
|
the_stack_data/52694.c | #include <stdio.h>
#include <stdlib.h>
/* test08.c (dense and same memory location access to shared-ram */
/* by cpu0 & cpu1) */
/* 2015-08-19 O. NISHII */
/* fixed address */
#define CPU1_INSTR_HEAD 0x14001000
#define CPU1_SP_INIT 0x14004ffc
#define RTC_SEC 0xabcd0224
#define RTC_NS 0xabcd0228
#define ADR_CPU01_COMM_HEAD 0x80e0
#define ADR_CPU0_FORV 0x8100
#define ADR_CPU1_FORV 0x8102
#define ADR_CPU0_SUMVL 0x8108
#define ADR_CPU1_SUMVL 0x810a
#define ADR_CPU0_SUMVH 0x810e
#define ADR_CPU1_SUMVH 0x810c
char instbuf[160];
int main( )
{
int i, j, limit, limit_cpu1, poll_count = 0, sum_int;
unsigned int instr0, instr1;
void *ptr_void;
volatile int *ptr_array_a32, *ptr_inst, *ptr_data;
volatile short *ptr_i;
short data_sample;
volatile unsigned short *ptr_suml, *ptr_sumh;
volatile short *ptr_sh_1;
long time_pr_1, time_pr_2;
int time_r_sec1, time_r_sec2;
int time_r_ns1, time_r_ns2;
volatile int *ptr_sec, *ptr_ns;
FILE *fp1;
ptr_void = malloc(1024 * 1024 * 10);
ptr_sec = (int *)RTC_SEC;
ptr_ns = (int *)RTC_NS;
/* config */
if(sizeof(data_sample) != 2) {
printf("short not 2 byte compu. env. quit.\n");
exit (0);
}
printf("smp test test08 (dense access to shared mem by cpu0&cpu1\n");
printf("%x 10MB area kept\n", (unsigned int) ptr_void);
printf("input sum limit for cpu0 (1-32767)\n");
printf(" (limit for cpu1 is chosen to program)\n");
scanf("%d", &limit);
if(limit > 32767) {
limit = 32767; printf(" clip limit 32767\n");
}
ptr_array_a32 = (int *)CPU1_INSTR_HEAD ;
if(
(ptr_array_a32 < (int*)(ptr_void) ) ||
(ptr_array_a32 > ((int*)(ptr_void) + (1024 * 1024 * 10) - 16))) {
printf("fixed address variable out of range of allocated mem.\n");
return(1);
}
if (limit < 10) { limit_cpu1 = limit + 2; }
else if(limit < 100) { limit_cpu1 = limit + 20; }
else if(limit < 1000) { limit_cpu1 = limit + 200; }
else if(limit < 10000) { limit_cpu1 = limit + 2000; }
else if(limit < 32767 - 10000) { limit_cpu1 = limit + 10000; }
else { limit_cpu1 = 32767; }
/* step 1: set CPU1 instructions to DDR */
ptr_inst = (int *)CPU1_INSTR_HEAD;
fp1 = fopen ("sm08c1.xxd", "r");
for(i = 0; i < 102 ; i++) {
fgets(instbuf, 160, fp1);
if(i >= 21) {
for(j = 0; j < 4; j++) {
sscanf(&instbuf[10 * j + 9], "%x", &instr0);
sscanf(&instbuf[10 * j + 14], "%x", &instr1);
*(ptr_inst) = (int)((instr0 << 16) | instr1);
ptr_inst++;
}
}
}
fclose(fp1);
printf("end set CPU1 instructions\n");
/* step 2: set shared ram */
ptr_sh_1 = (short *)ADR_CPU0_FORV ; *ptr_sh_1 = 0;
ptr_sh_1 = (short *)ADR_CPU1_FORV ; *ptr_sh_1 = 0;
ptr_sh_1 = (short *)ADR_CPU0_SUMVL ; *ptr_sh_1 = 0;
ptr_sh_1 = (short *)ADR_CPU1_SUMVL ; *ptr_sh_1 = 0;
ptr_sh_1 = (short *)ADR_CPU0_SUMVH ; *ptr_sh_1 = 0;
ptr_sh_1 = (short *)ADR_CPU1_SUMVH ; *ptr_sh_1 = 0;
for (i = 0; i < 30; i ++) {
*ptr_sh_1 = 0;
ptr_sh_1++;
}
ptr_sh_1 = (short *)ADR_CPU01_COMM_HEAD ; *ptr_sh_1 = (short) limit_cpu1;
ptr_sh_1 = (short *)ADR_CPU01_COMM_HEAD + 1; *ptr_sh_1 = 0;
ptr_data = (int *) ADR_CPU01_COMM_HEAD + 1; *ptr_data = 0;
/* step 3: setup CPU1 boot */
ptr_data = (int *)0x8000;
*ptr_data = CPU1_INSTR_HEAD;
ptr_data = (int *)0x8004;
*ptr_data = CPU1_SP_INIT;
for(i = 0; i < 10; i++) {
}
printf("end setup CPU1 boot\n");
time_pr_1 = clock( ); /* timer (start point) */
time_r_sec1 = *ptr_sec;
time_r_ns1 = *ptr_ns;
ptr_data = (int *)0xabcd0640;
*ptr_data = 1;
ptr_sumh = (unsigned short *)ADR_CPU0_SUMVH;
ptr_suml = (unsigned short *)ADR_CPU0_SUMVL;
ptr_i = ( short *)ADR_CPU0_FORV;
ptr_sh_1 = (short *)ADR_CPU0_SUMVL ; *ptr_sh_1 = 0;
ptr_sh_1 = (short *)ADR_CPU0_SUMVH ; *ptr_sh_1 = 0;
sum_int = 0;
/* step 4: sum 1 - to limit */
for((*ptr_i) = 1; (*ptr_i) <= (short)limit; (*ptr_i)++) {
sum_int = ((int)*ptr_sumh) << 16 | ((int)*ptr_suml);
sum_int += (*ptr_i);
*ptr_suml = (unsigned short) (sum_int & 0xffff);
*ptr_sumh = (unsigned short) ((sum_int >> 16) & 0xffff);
} /* end of (for i = ... */
/* step 5 wait for cpu1 execuion completion */
ptr_sh_1 = (short *)ADR_CPU01_COMM_HEAD + 1;
while((* ptr_sh_1) == 0) {
poll_count ++;
}
time_pr_2 = clock( );
time_r_sec2 = *ptr_sec;
time_r_ns2 = *ptr_ns;
ptr_data = (int *)ADR_CPU01_COMM_HEAD + 1;
/* step 6 display result */
printf("results\n");
printf("cpu0 limit %d\n", limit);
printf("cpu0 sum %d\n", sum_int);
printf("cpu1 limit %d\n", limit_cpu1);
printf("cpu1 sum %d\n", *ptr_data);
printf("cpu0 poll count (for completion) = %d\n", poll_count);
printf("time = (process) %.2f sec, (real-time) %.2f sec\n",
((float) (time_pr_2 - time_pr_1) / 1.0e6),
(time_r_sec2 - time_r_sec1) +
(time_r_ns2 - time_r_ns1) / 1.0e9);
free(ptr_void);
return(0);
}
|
the_stack_data/9948.c | //this isn't actually a file for drawing stuff
//It just contains lots of convenient global variables used by other files
#define PI 3.14159265358979
const float FPS = 60; //The framerate is designed to never go above or below 60
int SCREEN_W = 800; //Screen width and heights by default
int SCREEN_H = 600;
|
the_stack_data/38185.c | #include <stdio.h>
#define N 1000000ll
#define SUM (N * (N-1)/2)
int main (void)
{
#pragma omp target
{
long long a, i;
a = 0;
#pragma omp parallel for reduction(+:a)
for (i = 0; i < N; i++) {
a += i;
}
{
if (a != SUM)
printf ("Incorrect result = %lld, expected = %lld!\n", a, SUM);
else
printf ("The result is correct = %lld!\n", a);
}
}
return 0;
}
|
the_stack_data/117372.c | /*
* author: SciZeal
* email: [email protected]
* time: 2020-05-11
*
* MIT LICENCE
*/
#define _AUTHOR_IS_SCIZEAL
#include <stdio.h>
#include <string.h>
#define maxn 100
// print whitespace * n
void whitespace_printf(int n)
{
for (int i = 0; i < n; i++)
{
printf(" ");
}
}
int main()
{
char string[maxn];
gets(string);
int length = strlen(string);
int side_length = (length + 2) / 3;
// front rows
for (int i = 0; i < side_length - 1; i++)
{
printf("%c", string[i]);
whitespace_printf(length - 2 * side_length);
printf("%c\n", string[length - 1 - i]);
}
// last row
for (int i = side_length - 1; i <= length - side_length; i++)
{
printf("%c", string[i]);
}
printf("\n");
return 0;
}
|
the_stack_data/130434.c | /*
* Course Code 350
*
* A Multithreaded Tiny HTTP Server
* Demonstrating Thread Pool Management
* Following the Thread Pool Management
* Outline from Unix Network Programming Vol 1
* by W. Richard Stevens.
*
* Project accomplished by: Abu Mohammad Omar Shehab Uddin Ayub
* Reg No. 2000 330 096
* Section B
* 3rd Year 2nd Semester
* Dept of CSE, SUST
*
* Idea and guided by: Mahmud Shahriar Hussain
* Lecturer
* Dept of CSE, SUST
*
* Course Instructor: Rukhsana Tarannum Tazin
* Lecturer
* Dept of CSE, SUST
*/
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#define MAX_CLIENT 5
#define MAX_THREAD 3
#define MAX_REQ_HEADER 10
#define MAX 10
#define MAX_LENGTH 6
#define MIME_LENGTH 20
typedef struct {
pthread_t threadID;
long threadCount;
}Thread;
typedef struct {
char hostName[100];
char filePath[100];
}Request;
typedef struct{
int code;
char date[30];
char server[30];
char last_modified[30];
long content_length;
char content_type[10];
char file_path[80];
}Reply;
Thread thrdPool[MAX_THREAD];
Request request[MAX_THREAD];
Reply reply[MAX_THREAD];
int clntConnection[MAX_CLIENT], clntGet, clntPut;
pthread_mutex_t clntMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t srvrMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t srvrMutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t emitMutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t clntCondition = PTHREAD_COND_INITIALIZER;
static int numThreads;
void *request_handler(void *arg);
int find_method (char *req);
Request parse_request(char *rbuff);
Reply prepare_reply(int code, Request rq);
char *getMimeType(char *str);
void emit_reply(int conn, Reply rply);
int main(void)
{
int i, serverSockfd, clientSockfd;
int serverLen, clientLen;
struct sockaddr_in serverAddress, clientAddress, tempAddress;
//defining number of threads
numThreads = MAX_THREAD;
// initializing queue parameters
clntGet = clntPut = 0;
//creating all the threads
for(i = 0; i < numThreads; i++)
{
pthread_create(&thrdPool[i].threadID, NULL, &request_handler, (void *) i);
} // end of for loop
//creating the socket descriptor
serverSockfd = socket(AF_INET, SOCK_STREAM,0);
if(serverSockfd < 0)
{
error("\nError opening socket");
exit(1);
}
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = INADDR_ANY;
serverAddress.sin_port = htons(80);
serverLen = sizeof(serverAddress);
if(bind(serverSockfd, (struct sockaddr *)&serverAddress, serverLen) < 0)
{
printf("\nError in binding.");
exit(1);
}
listen(serverSockfd, 10);
for( ; ; )
{
fflush(stdout);
//printf("\nWaiting for clients...");
clientLen = sizeof(tempAddress);
//printf("\n\nBlocked on accept()");
clientSockfd = accept(serverSockfd, (struct sockaddr *)&clientAddress, &clientLen);
//printf("\nAllocated client descriptor# %d", clientSockfd);
pthread_mutex_lock(&srvrMutex);
clntConnection[clntPut] = clientSockfd;
if(++clntPut == MAX_CLIENT)
clntPut = 0;
if(clntPut == clntGet)
{
printf("\nCan't handle any more request...\nTerminating...");
exit(1);
}
pthread_cond_signal(&clntCondition);
pthread_mutex_unlock(&srvrMutex);
fflush(stdout);
} // end of infinite for loop
} // end of main
void *request_handler(void *arg)
{
int connfd;
char *reqBuff;
fflush(stdout);
//printf("\nThread %d starting", (int) arg);
for( ; ; )
{
pthread_mutex_lock(&clntMutex);
//printf("\nMutex locked by thread# %d.", (int) arg);
while(clntGet == clntPut)
pthread_cond_wait(&clntCondition, &clntMutex);
connfd = clntConnection[clntGet];
if(++clntGet == MAX_CLIENT)
clntGet = 0;
// thread operation
//printf("\nIn between mutex lock-unlock. Thread# %d, Connection# %d", (int) arg, connfd);
reqBuff = (char *) malloc (1000);
read(connfd, reqBuff, 1000);
int temp;
temp = find_method(reqBuff);
if(temp == 0)
{
//printf("\nfind_method returned 0");
request[(int)arg] = parse_request(reqBuff);
//printf("\nHost: %s\nFile Path: %s", request[(int)arg].hostName, request[(int)arg].filePath);
reply[(int)arg] = prepare_reply(200, request[(int)arg]);
printf("\n\nprinting the reply structure");
//printf("\nCode: %d\nDate: %s\nServer: %s\nlast_modified: %s\ncontent_length: %ld\ncontent type: %s\nfile path: %s", reply[(int)arg].code, reply[(int)arg].date, reply[(int)arg].server, reply[(int)arg].last_modified, reply[(int)arg].content_length, reply[(int)arg].content_type, reply[(int)arg].file_path);
emit_reply(connfd, reply[(int)arg]);
}
else if(temp == 1)
{
printf("\nfind_method returned 1");
reply[(int)arg] = prepare_reply(501, request[(int)arg]);
emit_reply(connfd, reply[(int)arg]);
}
else
{
printf("\nfind_method returned -1");
reply[(int)arg] = prepare_reply(400, request[(int)arg]);
emit_reply(connfd, reply[(int)arg]);
}
pthread_mutex_unlock(&clntMutex);
//printf("\nMutex unlocked by thread# %d.", (int) arg);
thrdPool[(int) arg].threadCount++;
// shahriar bhai told that closing the connection formally is not so important
// good performance achieved @ closing it formally
close(connfd);
}
} // end of request_handler function
void emit_reply(int conn, Reply rply)
{
//pthread_mutex_lock(&emitMutex2);
if(rply.code == 200)
{
char *ok_code = "HTTP/1.1 200 OK\r\n";
write(conn, ok_code, strlen(ok_code));
char *date;
date = (char *)malloc(100);
strcpy(date, "Date: ");
strcat(date, rply.date);
strcat(date, "\r\n");
write(conn, date, strlen(date));
char *server;
server = (char *)malloc(100);
strcpy(server, "Server: ");
strcat(server, rply.server);
strcat(server, "\r\n");
write(conn, server, strlen(server));
char *last_modified;
last_modified = (char *)malloc(100);
strcpy(last_modified, "Last-Modified: ");
strcat(last_modified, rply.last_modified);
strcat(last_modified, "\r\n");
write(conn, last_modified, strlen(last_modified));
char *content_length;
content_length = (char *)malloc(100);
strcpy(content_length, "Content-Length: ");
int decpnt, sign;
char *p;
p = (char *)malloc(20);
p = ecvt(rply.content_length, 15, &decpnt, &sign);
//printf("\nConversion-- %s %d %d", p, decpnt, sign);
strncat(content_length, p, decpnt);
strcat(content_length, "\r\n");
write(conn, content_length, strlen(content_length));
char *content_type;
content_type = (char *)malloc(100);
strcpy(content_type, "Content-Type: ");
strcat(content_type, rply.content_type);
strcat(content_type, "\r\n");
write(conn, content_type, strlen(content_type));
write(conn, "\r\n", 2);
int b;
char c;
FILE *fp;
fp = (FILE *) malloc(sizeof(FILE));
fp = fopen(rply.file_path, "rb");
while(!feof(fp))
{
c = getc(fp);
if(!feof(fp))
{
//printf("%c", c);
write(conn, &c, 1);
}
}
//pthread_mutex_unlock(&emitMutex2);
return;
}
else if(rply.code == 400)
{
char *ok_code = "HTTP/1.1 400 Bad Request\r\n";
write(conn, ok_code, strlen(ok_code));
char *date;
date = (char *)malloc(100);
strcpy(date, "Date: ");
strcat(date, rply.date);
strcat(date, "\r\n");
write(conn, date, strlen(date));
char *server;
server = (char *)malloc(100);
strcpy(server, "Server: ");
strcat(server, rply.server);
strcat(server, "\r\n");
write(conn, server, strlen(server));
write(conn, "\r\n", 2);
char *error_400;
error_400 = (char *)malloc(300);
strcpy(error_400, "<html><head><title>Error No: 400. Bad Request.</title></head><body><h2>The server cannot parse the request.</h2><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><hr>For further info mail to [email protected].</body><html>");
write(conn, error_400, strlen(error_400));
}
else if(rply.code == 501)
{
char *ok_code = "HTTP/1.1 501 Method Not Implemented\r\n";
write(conn, ok_code, strlen(ok_code));
char *date;
date = (char *)malloc(100);
strcpy(date, "Date: ");
strcat(date, rply.date);
strcat(date, "\r\n");
write(conn, date, strlen(date));
char *server;
server = (char *)malloc(100);
strcpy(server, "Server: ");
strcat(server, rply.server);
strcat(server, "\r\n");
write(conn, server, strlen(server));
write(conn, "\r\n", 2);
char *error_501;
error_501 = (char *)malloc(300);
strcpy(error_501, "<html><head><title>Error No: 501. Method Not Implemented.</title></head><body><h2>The server only resolves the GET method.</h2><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><hr>For further info mail to [email protected].</body><html>");
write(conn, error_501, strlen(error_501));
}
else if(rply.code == 404)
{
char *ok_code = "HTTP/1.1 404 File Not Found\r\n";
write(conn, ok_code, strlen(ok_code));
char *date;
date = (char *)malloc(100);
strcpy(date, "Date: ");
strcat(date, rply.date);
strcat(date, "\r\n");
write(conn, date, strlen(date));
char *server;
server = (char *)malloc(100);
strcpy(server, "Server: ");
strcat(server, rply.server);
strcat(server, "\r\n");
write(conn, server, strlen(server));
write(conn, "\r\n", 2);
char *error_404;
error_404 = (char *)malloc(300);
strcpy(error_404, "<html><head><title>Error No: 404. File Not Found.</title></head><body><h2>The server could not found the requested url.</h2><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><hr>For further info mail to [email protected].</body><html>");
write(conn, error_404, strlen(error_404));
}
else if(rply.code == 403)
{
char *ok_code = "HTTP/1.1 403 Forbidden\r\n";
write(conn, ok_code, strlen(ok_code));
char *date;
date = (char *)malloc(100);
strcpy(date, "Date: ");
strcat(date, rply.date);
strcat(date, "\r\n");
write(conn, date, strlen(date));
char *server;
server = (char *)malloc(100);
strcpy(server, "Server: ");
strcat(server, rply.server);
strcat(server, "\r\n");
write(conn, server, strlen(server));
write(conn, "\r\n", 2);
char *error_403;
error_403 = (char *)malloc(300);
strcpy(error_403, "<html><head><title>Error No: 403. Forbidden.</title></head><body><h2>You are not authorized to access this url.</h2><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><hr>For further info mail to [email protected].</body><html>");
write(conn, error_403, strlen(error_403));
}
} //end of emit_reply
char *getMimeType(char *str)
{
printf("\nentered mime type");
int i;
//defined here the file extension
char *fileExt[MAX];
fileExt[0] = "html";
fileExt[1] = "htm";
fileExt[2] = "txt";
fileExt[3] = "gif";
fileExt[4] = "jpg";
fileExt[5] = "qt";
//defined here the mime type
char *mType[MAX];
mType[0] = "text/html";
mType[1] = "text/html";
mType[2] = "text/plain";
mType[3] = "image/gif";
mType[4] = "image/jpeg";
mType[5] = "video/quicktime";
for(i = 0; i < 6; i++)
{
if(strcmp(str, fileExt[i]) == 0)
{
printf("\nmatched");
return mType[i];
}
} //end of for loop
printf("\nreturning ERROR");
char *er = "ERROR";
return er;
} //end of getMimetype
Reply prepare_reply(int code, Request rq)
{
// extracting the file extension
char *drive, *direc, *fname, *ext;
drive = (char *) malloc (3);
direc = (char *) malloc (66);
fname = (char *) malloc (9);
ext = (char *) malloc (5);
Reply rpl;
if(code == 200)
{
rpl.code = 200;
time_t lt;
lt = time(NULL);
strcpy(rpl.date, ctime(<));
rpl.date[strlen(rpl.date) - 1] = '\0';
strcpy(rpl.server, "TinyThreadedServer/0.1a");
char dir[100];
getcwd(dir, 100);
//printf("\ncurrent dir is %s", dir);
//printf("\nfile path is %s", rq.filePath);
strcat(dir, "/");
strcat(dir, rq.filePath);
//printf("\nabsolute file path is %s", dir);
char *path, *p;
path = (char *) malloc (80);
p = (char *) malloc (80);
path = strtok(dir, "/");
strcpy(p, "/");
strcat(p, path);
do{
path = strtok('\0', "/");
if(path)
{
strcpy(ext, path);
strcat(p, "/");
strcat(p, path);
}
} while(path);
//printf("\nthe c++ file path %s", p);
char *e;
e = (char *)malloc(10);
e = strtok(ext, ".");
e = strtok('\0', ".");
//printf("\nfile extension is %s", e);
FILE *fp;
fp = (FILE *) malloc(sizeof(FILE));
if((fp = fopen(p, "r")) == NULL)
{
printf("\nFILE NOT FOUND.\nERROR CODE 404");
rpl.code = 404;
return rpl;
}
struct stat buff;
stat(p, &buff);
//printf("\nSize: %ld\ntime of last modification: %s", buff.st_size, ctime(&buff.st_mtime));
strcpy(rpl.last_modified, ctime(&buff.st_mtime));
rpl.last_modified[strlen(rpl.last_modified) - 1] = '\0';
rpl.content_length = buff.st_size;
if(strcmp(getMimeType(e), "ERROR") == 0)
{
rpl.code = 403;
fclose(fp);
return rpl;
}
strcpy(rpl.content_type, getMimeType(e));
strcpy(rpl.file_path, p);
fclose(fp);
}
else if (code == 400)
{
rpl.code = 400;
time_t lt;
lt = time(NULL);
strcpy(rpl.date, ctime(<));
rpl.date[strlen(rpl.date) - 1] = '\0';
strcpy(rpl.server, "TinyThreadedServer/0.1a");
}
else if (code == 501)
{
rpl.code = 501;
time_t lt;
lt = time(NULL);
strcpy(rpl.date, ctime(<));
rpl.date[strlen(rpl.date) - 1] = '\0';
strcpy(rpl.server, "TinyThreadedServer/0.1a");
}
return rpl;
} //end of prepare_reply
Request parse_request(char *rbuff)
{
char *fileName;
char *hostName;
int j, k, l, m, n;
Request r;
fileName = (char *) malloc (100);
hostName = (char *) malloc (100);
for(j = 5, k = 0; ;j++, k++)
{
if(rbuff[j] == ' ') break;
fileName[k] = rbuff[j];
} //end of for loop
fileName[k]= '\0';
//printf("\nThe valid file path is %s", fileName);
strcpy(r.filePath, fileName);
//finding the host
char *p;
p = strstr(rbuff, "Host: ");
for(l = 0; l < 6; l++)
{
p++;
} //end of for loop
for(m = 0, n = 0; ; m++, n++)
{
if(*p == '\r' || *p == '\n') break;
hostName[n] = *p;
p++;
} //end of for loop
hostName[n]= '\0';
fflush(stdout);
strcpy(r.hostName, hostName);
return r;
} // end of parse_request
int find_method (char *req)
{
pthread_mutex_lock(&srvrMutex2);
//printf("\nin the find_method function\n%s\nthe size of the request is: %d", req, strlen(req));
char *method_list[6];
method_list[0] = (char *) malloc (10);
strcpy(method_list[0], "PUT");
method_list[1] = (char *) malloc (10);
strcpy(method_list[1], "HEAD");
method_list[2] = (char *) malloc (10);
strcpy(method_list[2], "POST");
method_list[3] = (char *) malloc (10);
strcpy(method_list[3], "DELETE");
method_list[4] = (char *) malloc (10);
strcpy(method_list[4], "TRACE");
method_list[5] = (char *) malloc (10);
strcpy(method_list[5], "CONNECT");
int i, j = 0;
char *r;
r = (char *) malloc (10);
for(i = 0; i < strlen(req); i++)
{
if(req[i] == ' ') break;
r[i] = req[i];
} //end of for loop
r[i] = '\0';
//printf("\nExtracted method is %s", r);
if(strcmp(r, "GET") == 0)
{
//printf("\nit's a GET method !!!");
pthread_mutex_unlock(&srvrMutex2);
return 0;
}
for(i = 0; i < 7; i++)
{
if(strcmp(r, method_list[i]) == 0)
{
printf("\n%s matched with %s", r, method_list[i]);
j = 1;
break;
}
} //end of for loop
if(j == 1)
{
pthread_mutex_unlock(&srvrMutex2);
return 1;
}
else
{
pthread_mutex_unlock(&srvrMutex2);
return -1;
}
} // end of find_method
|
the_stack_data/7949578.c | /* showf_pt.c -- use two approaches to show the value of float variable */
#include <stdio.h>
int main(void)
{
float aboat = 32000.0;
double abet = 2.14e9;
long double dip = 5.32e-5;
printf("%f can be written %e\n", aboat, aboat);
// next line requires the compiler to support C99 or relative features in C99
printf("And it's %a in hexadecimal, powers of 2 notation\n", aboat);
printf("%f can be written %e\n", abet, abet);
printf("%Lf can be written %Le\n", dip, dip);
return 0;
} |
the_stack_data/212642720.c | /*
* Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
* Copyright [2016-2021] EMBL-European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* autocomplete.c -- generates autocomplete suggestion dictionary. In C
* for speed as it traverses all indices.
*
* link with libm (math) ie -lm
*
* Author: Dan Sheppard (ds23)
*/
/* This file is divided into sections identified by comments:
* UTILS -- misc helpers used by other sections.
* PROCESSOR -- processes words.
* LEXER -- reads the file and breaks it into words and states.
* CONTROLLER -- handles system interaction, logging, yadda-yadda.
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <stddef.h>
#define READBUFFER 65536
int max_index_size = 100000; /* Overridden by option */
/* Fields to exclude from autocomplete altogether (with 0 on end of list) */
char * bad_fields[] = {"domain_url",0};
/************************************************************************
* UTILS -- misc helpers used by other sections. *
************************************************************************/
struct pool {
char **a;
int n;
};
char * pmem(struct pool *p,int amt) {
p->a = realloc(p->a,(p->n+1)*sizeof(char *));
p->a[p->n] = malloc(amt);
return p->a[p->n];
}
void pfree(struct pool *p) {
int i;
if(!p->a) return;
for(i=0;i<p->n;i++)
free(p->a[i]);
free(p->a);
p->a = 0;
p->n = 0;
}
/************************************************************************
* PROCESSOR -- processes words. *
************************************************************************/
/* Checks for membership of list of strings. If present returns 0, else
* returns new length with string added. Compact representation is \0
* terminated strings, followed by extra \0. NULL is acceptable as
* zero-length list. Cannot store empty string.
*/
int strl_member(char **str,char *data,int max) {
char *c,*d;
int len,n=0;
ptrdiff_t p;
len = strlen(data);
if(!len)
return 0;
if(!*str && max) { /* Initial malloc of zero-length list */
*str = malloc(1);
**str = '\0';
}
c=*str;
while(*c) {
for(d=data;*c && *c == *d;c++,d++)
;
if(!*c && !*d)
return 0;
for(;*c;c++)
;
c++;
n++;
}
if(max==-1 || n<max) {
p = c-*str; /* Remap c after realloc, also = length of alloc-1 */
*str = realloc(*str,p+len+2);
c = *str+p;
strcpy(c,data);
*(c+len+1) = '\0';
n++;
}
return n;
}
/* Converts to more standard string array */
char **strl_strings(char *strl) {
int len,i;
char **out,*d;
if(!strl)
return 0;
len = 1;
for(d=strl;*d || *(d+1);d++) {
if(!*d)
len++;
}
out = malloc(sizeof(char *)*(len+1));
for(d=strl,i=0; *d; i++,d+=strlen(d)+1)
out[i] = d;
out[i] = 0;
return out;
}
/* Simple hash function converts string into number at most mod */
int quick_hash(char *str,int seed,int mod) {
unsigned int hash = 0;
for(;*str;str++)
hash = (hash * 37 + (*str ^ seed));
return hash % mod;
}
/* "Effort" is a heuristic, supposed to correlate with the difficulty of
* remembering (and so likelihood of entering) a term. For example, it
* is more likely a user will enter KINASE1 than Q792Z.3X, all other things
* being equal, in part because it's easier to remember. At the moment we
* simply count digits as four and everything else as one, but this may
* change.
*
* This method returns a prefix of its input upto the effortlimit. All
* strings which begin with this prefix are considered muddleable-up,
* and so are placed in the same bin. If many different words end up in
* the same bin, then that is considered an unlikely term to memorise
* and enter, so these are discarded.
*
* eg Q792Z.3X -> prefix Q792 (eff=13) -+--> two in this bin
* Q792G.7R -> prefix Q792 (eff=13) -'
* BRCA1 -> prefix BRCA1 (eff=8) ----> one in this bin
* BRCA2 -> prefix BRCA2 (eff=8) ----> one in this bin
*
* "Effort" is the primary method by which we choose which terms to add to
* the autocomplete. (The other is "annoyingness").
*/
#define EFFORTLIMIT 12
char * make_effort(char *data) {
char *effort;
int limit,i,num=0,len,off;
limit = EFFORTLIMIT;
len = strlen(data);
off = len;
for(i=0;i<len;i++) {
if(isdigit(data[i]))
num += 4;
else
num++;
if(num>limit) {
off = i+1;
break;
}
}
if(off<1) off=1;
effort = malloc(off+1);
strncpy(effort,data,off);
effort[off]='\0';
return effort;
}
/* A prefix counter is the central datastructure in implementing the
* bins required for finding clashing prefixes in our effort calculations.
* It is a hash table, keyed by a hash of the prefix. Each value is the
* prefix and a list of words. Each entry in the table is a linked list.
*
* The hash table grows by calling boost_table which actually
* simply creates a replacement table (delegated to make_table)
* and then refiles the entries.
*
* inc_counter handles adding a word to the prefix counter and requesting
* the table grow, when needed.
*
* We also use a separate instance of this structure to record sections
* in which each word appears for later dumping.
*/
struct counter {
char * prefix;
char *words;
struct counter * next;
};
struct word_table {
int size,num;
struct counter ** counter;
};
struct word_table *prefixes,*sections;
struct word_table * make_table(int size) {
struct word_table *out;
int i;
out = malloc(sizeof(struct word_table));
if(size) {
out->size = size;
out->num = 0;
out->counter = malloc(sizeof(struct counter *)*size);
for(i=0;i<size;i++)
out->counter[i] = 0;
} else {
*out = (struct word_table){0,0,0};
}
return out;
}
void boost_table(struct word_table *in) {
struct word_table *out;
struct counter *c,*d;
int i,hash;
out = make_table(in->size*3/2+16);
for(i=0;i<in->size;i++)
for(c=in->counter[i];c;c=d) {
d = c->next;
hash = quick_hash(c->prefix,0,out->size);
c->next = out->counter[hash];
out->counter[hash] = c;
}
out->num = in->num;
*in = *out;
}
long long int stat_naughty=0,stat_good=0,stat_words=0;
#define NAUGHTY_THRESHOLD 12
/* 0 = new, 1 = old, 2 = naughty */
int inc_counter(struct word_table *pc,char *prefix,char *word) {
int hash,num;
struct counter *c,*rec=0;
if(pc->num >= pc->size/3)
boost_table(pc);
hash = quick_hash(prefix,0,pc->size);
for(c=pc->counter[hash];c;c=c->next) {
if(!strcmp(c->prefix,prefix))
rec = c;
}
if(!rec) {
c = malloc(sizeof(struct counter));
c->prefix = malloc(strlen(prefix)+1);
strcpy(c->prefix,prefix);
c->words = 0;
c->next = pc->counter[hash];
pc->counter[hash] = c;
pc->num++;
rec = c;
} else if(!rec->words) {
stat_naughty++;
return 2;
}
num = strl_member(&(rec->words),word,NAUGHTY_THRESHOLD);
if(num>=NAUGHTY_THRESHOLD) {
free(rec->words);
rec->words = 0;
stat_naughty++;
return 2;
}
stat_good++;
if(num==0) {
return 1;
}
return 0;
}
void add_section(struct word_table *ss,char *word,char *section) {
int hash;
struct counter *c,*rec=0;
if(ss->num >= ss->size/3)
boost_table(ss);
hash = quick_hash(word,0,ss->size);
for(c=ss->counter[hash];c;c=c->next) {
if(!strcmp(c->prefix,word))
rec = c;
}
if(!rec) {
c = malloc(sizeof(struct counter));
c->prefix = malloc(strlen(word)+1);
strcpy(c->prefix,word);
c->words = 0;
c->next = ss->counter[hash];
ss->counter[hash] = c;
ss->num++;
rec = c;
}
strl_member(&(rec->words),section,-1);
}
char ** get_sections(struct word_table *ss,char *word) {
struct counter *c,*rec=0;
int hash;
if(!ss->size)
return 0;
hash = quick_hash(word,0,ss->size);
for(c=ss->counter[hash];c;c=c->next) {
if(!strcmp(c->prefix,word))
rec = c;
}
if(rec && rec->words) {
return strl_strings(rec->words);
}
return 0;
}
/* "annoyingness" is an heuristic supposed to correlate with the difficulty
* in speaking or typing a search term. We assume that if a term is a
* pain to type then we will not use it if an easier term is
* available. For example, if a gene is known as CHEESE3, GDTDRF7 and
* Q450163 then even if all three of these are well known and disitinctive,
* (such that the "effort" heuristic accepts them) all other things
* being equal, a user is more likely to enter or communicate "CHEESE3".
*
* The heuristic assumes that English words are easy, letters are quite
* easy, and everything else isn't. "English" is approximated by looking
* for an approximately alternating pattern of vowels and consonants.
*
* The second kind of annoyingness handled here is that it's most annoying
* to have to type in longer words as shorter words can be entered easily
* without its aid. Therefore we penalise short words by dividing by
* overall length.
*
* We use annoyngness as a post-filter on our terms (unlike effort, which
* is applied during parsing). We remember the annoyingness of each term
* and consider the number of terms which a user requested in determining
* the correct threshold.
*/
/* -100*log(letter_frequency in english). Add scores and divide by length
* to get an accurate score for unlikeliness of a letter sequence in
* English.
*/
int freq[] = {
109,182,156,136, 92,163,169,122,113,298,216,140,158,
115,111,174,294,122,120,104,154,195,167,276,167,315
};
int annoyingness(char *data) {
int n=0,len=0,v=0,f=0,letlen=0;
char *c;
for(c=data;*c;c++) {
len++;
if(!isalpha(*c))
n+=100;
if(strspn(c,"aeiou") > 2)
n+=50; /* Too many vowels in a row */
if(strcspn(c,"aeiou") > 3)
n+=10; /* Too many consonants in a row */
if(strspn(c,"aeiou"))
v=1;
if(*c>='a' && *c<='z') {
f += freq[*c-'a'];
letlen++;
}
}
if(len) n/=len;
if(letlen) f/= letlen; else f = 500;
if(f>150)
n += (f-150); /* unusual letters */
else
n += f/20; /* Mainly to avoid ties */
if(!v)
n += 30; /* no vowels */
if(!len) return 0;
n = (n*20)/len; /* Reward long matches, painful to type */
return n;
}
#define MAX_ANNOYINGNESS 200
int annoyingness_size[MAX_ANNOYINGNESS];
void reset_annoyingness() {
int i;
for(i=0;i<MAX_ANNOYINGNESS;i++)
annoyingness_size[i] = 0;
}
void register_annoyingness(int ann) {
int i;
for(i=ann;i<MAX_ANNOYINGNESS;i++)
annoyingness_size[i]++;
}
int last_val = -1;
int annoyingness_threshold(int num) {
int i;
/* This method is on the critical path, so use a cache */
if(last_val>=0) {
if(last_val == MAX_ANNOYINGNESS-1 && annoyingness_size[MAX_ANNOYINGNESS-1]<num)
return MAX_ANNOYINGNESS-1;
if(annoyingness_size[last_val]<=num && annoyingness_size[last_val+1]>num)
return last_val;
}
for(i=1;i<MAX_ANNOYINGNESS;i++) {
if(annoyingness_size[i]>num) {
last_val = i-1;
return i-1;
}
}
last_val = MAX_ANNOYINGNESS-1;
return MAX_ANNOYINGNESS-1;
}
/* Dump the appropriate number of words (by calculating the correct
* annoyingness threshold).
*/
void dump_words(struct word_table *pc,int threshold) {
struct counter *c;
int i,thresh,ann;
double value;
char *d,**ss,**s;
thresh = annoyingness_threshold(max_index_size);
for(i=0;i<pc->size;i++)
for(c=pc->counter[i];c;c=c->next) {
d=c->words;
if(d) {
while(*d) {
ann = annoyingness(d);
if(ann<thresh) {
value = ann*strlen(d);
if(value > 0.5) {
value = 12.0 - log10(value);
} else {
value = 12.0;
}
if(strlen(d)>6)
value -= 0.1 * (strlen(d)-6);
if(value >= threshold) {
ss = get_sections(sections,d);
if(ss) {
for(s=ss;*s;s++)
printf("%s%s\t%1.1f\n",*s,d,value);
free(ss);
} else {
printf("%s\t%1.1f\n",d,value);
}
}
}
d += strlen(d)+1;
}
}
}
}
/* What we do to each word */
void process_word(char **ss,char *data) {
char *effort,**s;
int thresh,ann,i;
if(!*data)
return;
stat_words++;
effort = make_effort(data);
i = inc_counter(prefixes,effort,data);
if(i==0 || i==1) {
if(ss)
for(s=ss;*s;s++)
add_section(sections,data,*s);
}
if(!i) {
thresh = annoyingness_threshold(max_index_size);
ann = annoyingness(data);
if(ann<thresh) {
register_annoyingness(ann);
}
}
free(effort);
}
/***************************************************************
* LEXER - reads the file and breaks it into words and states. *
***************************************************************/
/* A good field is a field which should not be ignored for the purposes
* of autocomplete. It uses a fixed array.
*/
int in_good_field = 0;
int good_field(char *name) {
char **b;
for(b=bad_fields;*b;b++)
if(!strcmp(name,*b))
return 0;
return 1;
}
/* Here's a tag. Set whether or not we are in a good field. This is a
* one-bit state which determines whether any textual content in the XML
* should be added to the autocomplete index.
*/
void process_tag(char *data) {
char * field,*f;
if(!strncmp(data,"field ",6)) {
/* FIELD */
if((field = strstr(data,"name=\""))) {
f = index(field+6,'"');
if(f)
*f = '\0';
if(good_field(field+6))
in_good_field = 1;
}
} else if(!strcmp(data,"/field")) {
in_good_field = 0;
}
}
/* Punctuation which tends to separate words */
int isseparator(char c) {
return c == '/' || c == ':' || c == ';' || c == '-' || c == '_' || c == '(' || c == ')';
}
/* Split some XML text into words and call process_word on each */
void process_text(char **ss,char *data) {
char *c,*d;
if(!in_good_field)
return;
/* Remove punctuation attached to starts and ends of words */
d = data;
for(c=data;*c;c++) {
if(ispunct(*c)) {
if(c==data || !*(c+1) ||
!isalnum(*(c-1)) || !isalnum(*(c+1)) ||
isseparator(*c))
*c = ' ';
}
if(isspace(*c)) {
*c = '\0';
if(*d)
process_word(ss,d);
d = c+1;
} else {
*c = tolower(*c);
}
}
process_word(ss,d);
}
int tag_mode=0;
char *tagstr = 0;
/* Process this text which is either the contents of <...> or else some
* text between such.
*
* eg <a>hello <b>world</b></a> =>
* lex_part("a",1); lex_part("hello ",0); lex_part("b",1);
* lex_part("world",0); lex_part("/b",1); lex_part("/a",1);
*/
void lex_part(char **ss,char *part,int tag) {
if(tag_mode != tag) {
/* Do stuff */
if(tag_mode) {
process_tag(tagstr);
} else {
process_text(ss,tagstr);
}
free(tagstr);
tagstr = 0;
tag_mode = tag;
}
if(!tagstr) {
tagstr = malloc(1);
tagstr[0] = '\0';
}
if(strlen(part)) {
tagstr = realloc(tagstr,strlen(tagstr)+strlen(part)+1);
strcat(tagstr,part);
}
}
/* Take a string and call lext_part the right number of times, with the
* right fragments.
*/
int in_tag = 0;
/* at top level we just extract tag / non-tag and pass it down */
void lex(char **ss,char *data) {
char *hit;
while(*data) {
hit = index(data,in_tag?'>':'<');
if(hit)
*hit = '\0';
lex_part(ss,data,in_tag);
if(hit) {
in_tag = !in_tag;
data = hit+1;
} else {
break;
}
}
}
/*******************************************************************
* CONTROLLER -- handles system interaction, logging, yadda-yadda. *
*******************************************************************/
/* Used by string returning functions: remember to free it! */
struct pool smem = {0,0};
/* Abbreviated filename for log messages */
char * short_name(char *in) {
char *out,*c,*d,*e;
out = malloc(strlen(in)+1);
e = rindex(in,'.');
c = rindex(in,'/');
if(!c) c = in;
for(d=out;*c && c!=e;c++)
if(c==in || isdigit(*c))
*(d++) = *c;
else if(isupper(*c))
*(d++) = tolower(*c);
else if(isalpha(*c) && !isalpha(*(c-1)))
*(d++) = *c;
else if(ispunct(*c) && !isalpha(*(c-1)))
*(d++) = '-';
*d = '\0';
return out;
}
/* Display a number of bytes with appropriate multiplier eg 1024 -> 1k */
char *mult = " kMGTPE";
char * size(off_t amt) {
char *out;
int i;
out = pmem(&smem,10);
for(i=0;mult[i];i++) {
if(amt<1024) {
sprintf(out,"%ld%c",amt,mult[i]);
return out;
}
amt /= 1024;
}
sprintf(out,"lots");
return out;
}
/* Display a time in H:M:S */
#define MAXTIME 256
char * time_str(time_t when) {
struct tm tm;
char *out;
if(!localtime_r(&when,&tm))
return "";
out = pmem(&smem,MAXTIME);
strftime(out,MAXTIME-1,"%H:%M:%S",&tm);
return out;
}
/* Get file size */
off_t file_size(char *fn) {
struct stat sb;
off_t size;
if(stat(fn,&sb) == -1) {
fprintf(stderr,"Cannot stat '%s': %s\n",fn,strerror(errno));
exit(1);
}
size = sb.st_size;
return size;
}
/* Read and call lex on a file */
int meg=0,bytes=0,repmeg=0;
time_t all_start,block_start,block_end;
off_t stat_all=0;
off_t stat_read = 0;
#define MEG (1024*1024)
void process_file(char **ss,char *fn) {
int r,fd;
char buf[READBUFFER];
long long int total;
time_t eta;
fprintf(stderr,"File: %-15s %10s\n",short_name(fn),size(file_size(fn)));
pfree(&smem);
fd = open(fn,O_RDONLY);
if(fd==-1) {
fprintf(stderr,"Cannot open '%s': %s\n",fn,strerror(errno));
exit(1);
}
while(1) {
r = read(fd,buf,READBUFFER-1);
if(r>0) {
stat_read += r;
buf[r] = '\0';
lex(ss,buf);
bytes += r;
if(bytes > MEG) {
meg += bytes/MEG;
bytes -= (bytes/MEG)*MEG;
}
} else if(r==0) {
break;
} else {
perror("Read of stdin failed");
exit(1);
}
if(!(meg%100) && repmeg != meg) {
block_end = time(0);
total = (stat_naughty+stat_good+1);
fprintf(stderr,"Run : %dMb in %lds (%lds).\nMem : "
"n/g(%%)=%s/%s (%lld) p/s=%s/%s. a=%d.\n",
meg,block_end-all_start,block_end-block_start,
size(stat_good),size(stat_naughty),
stat_good*100/total,
size(prefixes->num),size(stat_words),
annoyingness_threshold(max_index_size));
eta = all_start+(block_end-all_start)*stat_all/stat_read;
fprintf(stderr,"ETA : read/all = %s/%s (%ld%%) at %s\n",
size(stat_read),size(stat_all),stat_read*100/stat_all,
time_str(eta));
pfree(&smem);
block_start = block_end;
repmeg=meg;
}
}
lex_part(ss,"",0);
close(fd);
}
/* List of files we need to process */
struct file {
char *filename;
char *sections;
struct file *next;
};
char * global_sections = 0;
struct file *files = 0;
void add_file(char *fn) {
struct file *f;
char *fn2;
fn2 = malloc(strlen(fn)+1);
strcpy(fn2,fn);
f = malloc(sizeof(struct file));
f->filename = fn2;
f->sections = 0;
f->next = files;
files = f;
}
void add_file_section(char *section) {
if(files)
strl_member(&(files->sections),section,-1);
else
strl_member(&global_sections,section,-1);
}
void add_file_spec(char *spec) {
char *at,*at2,**ss,**s,*in;
in = malloc(strlen(spec)+1);
strcpy(in,spec);
ss = strl_strings(global_sections);
at = index(in,'@');
if(at) *at = '\0';
add_file(in);
if(ss)
for(s=ss;*s;s++)
add_file_section(*s);
while(at) {
at2 = index(at+1,'@');
if(at2) *at2 = '\0';
add_file_section(at+1);
at = at2;
}
free(in);
free(ss);
}
/* Handle options, read in list of files and submit one-by-one */
/* max bytes of filename on stdin */
#define MAXLINE 16384
int main(int argc,char *argv[]) {
int idx,c,from_stdin=0,threshold=6;
char *fn,*p,**ss;
struct file *f;
all_start = block_start = time(0);
while((c = getopt(argc,argv,"cn:s:t:")) != -1) {
switch (c) {
case 'n':
max_index_size = atoi(optarg);
if(max_index_size < 1) {
fprintf(stderr,"Bad index size '%s'\n",optarg);
return 1;
}
break;
case 'c':
from_stdin = 1;
break;
case 's':
add_file_section(optarg);
break;
case 't':
threshold = atoi(optarg);
if(threshold<1) {
fprintf(stderr,"Bad threshold '%s'\n",optarg);
return 1;
}
break;
case '?':
fprintf(stderr,"Bad command line options\n");
return 1;
default:
abort();
}
}
reset_annoyingness();
prefixes = make_table(0);
sections = make_table(0);
if(from_stdin) {
while(1) {
fn = malloc(MAXLINE);
if(!fgets(fn,MAXLINE,stdin)) {
if(ferror(stdin)) {
perror("Could not read from stdin\n");
exit(1);
}
free(fn);
break;
}
for(p=fn;*p && !isspace(*p);p++)
;
*p = '\0';
add_file_spec(fn);
}
} else {
for (idx=optind;idx<argc;idx++) {
add_file_spec(argv[idx]);
}
}
for(f=files;f;f=f->next)
stat_all += file_size(f->filename);
for(f=files;f;f=f->next) {
ss = strl_strings(f->sections);
process_file(ss,f->filename);
free(ss);
}
dump_words(prefixes,threshold);
fprintf(stderr,"Success.\n");
return 0;
}
|
the_stack_data/150142727.c | /***
* This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License.
* When used, please cite the following article(s): V. Mrazek, R. Hrbacek, Z. Vasicek and L. Sekanina, "EvoApprox8b: Library of approximate adders and multipliers for circuit design and benchmarking of approximation methods". Design, Automation & Test in Europe Conference & Exhibition (DATE), 2017, Lausanne, 2017, pp. 258-261. doi: 10.23919/DATE.2017.7926993
* This file contains a circuit from evoapprox8b dataset. Note that a new version of library was already published.
***/
#include <stdint.h>
#include <stdlib.h>
/// Approximate function add8_075
/// Library = EvoApprox8b
/// Circuit = add8_075
/// Area (180) = 952
/// Delay (180) = 1.830
/// Power (180) = 266.20
/// Area (45) = 69
/// Delay (45) = 0.690
/// Power (45) = 26.13
/// Nodes = 13
/// HD = 88736
/// MAE = 0.73438
/// MSE = 1.43750
/// MRE = 0.38 %
/// WCE = 3
/// WCRE = 50 %
/// EP = 43.8 %
uint16_t add8_075(uint8_t a, uint8_t b)
{
uint16_t c = 0;
uint8_t n0 = (a >> 0) & 0x1;
uint8_t n2 = (a >> 1) & 0x1;
uint8_t n4 = (a >> 2) & 0x1;
uint8_t n6 = (a >> 3) & 0x1;
uint8_t n8 = (a >> 4) & 0x1;
uint8_t n10 = (a >> 5) & 0x1;
uint8_t n12 = (a >> 6) & 0x1;
uint8_t n14 = (a >> 7) & 0x1;
uint8_t n16 = (b >> 0) & 0x1;
uint8_t n18 = (b >> 1) & 0x1;
uint8_t n20 = (b >> 2) & 0x1;
uint8_t n22 = (b >> 3) & 0x1;
uint8_t n24 = (b >> 4) & 0x1;
uint8_t n26 = (b >> 5) & 0x1;
uint8_t n28 = (b >> 6) & 0x1;
uint8_t n30 = (b >> 7) & 0x1;
uint8_t n32;
uint8_t n39;
uint8_t n53;
uint8_t n59;
uint8_t n62;
uint8_t n83;
uint8_t n126;
uint8_t n132;
uint8_t n133;
uint8_t n182;
uint8_t n183;
uint8_t n232;
uint8_t n233;
uint8_t n282;
uint8_t n283;
uint8_t n332;
uint8_t n333;
uint8_t n382;
uint8_t n383;
n32 = n0 | n16;
n39 = ~(n28 | n14 | n12);
n53 = ~(n39 & n18 & n16);
n59 = ~n53;
n62 = ~(n59 & n2 & n0);
n83 = n2 | n18;
n126 = ~n62;
n132 = (n4 ^ n20) ^ n126;
n133 = (n4 & n20) | (n20 & n126) | (n4 & n126);
n182 = (n6 ^ n22) ^ n133;
n183 = (n6 & n22) | (n22 & n133) | (n6 & n133);
n232 = (n8 ^ n24) ^ n183;
n233 = (n8 & n24) | (n24 & n183) | (n8 & n183);
n282 = (n10 ^ n26) ^ n233;
n283 = (n10 & n26) | (n26 & n233) | (n10 & n233);
n332 = (n12 ^ n28) ^ n283;
n333 = (n12 & n28) | (n28 & n283) | (n12 & n283);
n382 = (n14 ^ n30) ^ n333;
n383 = (n14 & n30) | (n30 & n333) | (n14 & n333);
c |= (n32 & 0x1) << 0;
c |= (n83 & 0x1) << 1;
c |= (n132 & 0x1) << 2;
c |= (n182 & 0x1) << 3;
c |= (n232 & 0x1) << 4;
c |= (n282 & 0x1) << 5;
c |= (n332 & 0x1) << 6;
c |= (n382 & 0x1) << 7;
c |= (n383 & 0x1) << 8;
return c;
}
|
the_stack_data/798880.c | /* Taxonomy Classification: 0000000100000064000310 */
/*
* WRITE/READ 0 write
* WHICH BOUND 0 upper
* DATA TYPE 0 char
* MEMORY LOCATION 0 stack
* SCOPE 0 same
* CONTAINER 0 no
* POINTER 0 no
* INDEX COMPLEXITY 1 variable
* ADDRESS COMPLEXITY 0 constant
* LENGTH COMPLEXITY 0 N/A
* ADDRESS ALIAS 0 none
* INDEX ALIAS 0 none
* LOCAL CONTROL FLOW 0 none
* SECONDARY CONTROL FLOW 0 none
* LOOP STRUCTURE 6 non-standard while
* LOOP COMPLEXITY 4 three
* ASYNCHRONY 0 no
* TAINT 0 no
* RUNTIME ENV. DEPENDENCE 0 no
* MAGNITUDE 3 4096 bytes
* CONTINUOUS/DISCRETE 1 continuous
* SIGNEDNESS 0 no
*/
/*
Copyright 2005 Massachusetts Institute of Technology
All rights reserved.
Redistribution and use of 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 set of conditions and the disclaimer below.
- Redistributions in binary form must reproduce the copyright notice, this
set of conditions, and the disclaimer below in the documentation and/or
other materials provided with the distribution.
- Neither the name of the Massachusetts Institute of Technology 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".
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.
*/
int main(int argc, char *argv[])
{
int init_value;
int test_value;
int inc_value;
int loop_counter;
char buf[10];
init_value = 0;
test_value = 4105;
inc_value = 4105 - (4105 - 1);
loop_counter = init_value;
while((loop_counter += inc_value) && (loop_counter <= test_value))
{
/* BAD */
buf[loop_counter] = 'A';
}
return 0;
}
|
the_stack_data/23575607.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strcat.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mpatrini <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/12/02 13:21:12 by mpatrini #+# #+# */
/* Updated: 2021/12/02 13:21:16 by mpatrini ### ########.fr */
/* */
/* ************************************************************************** */
char *ft_strcat(char *dest, char *src)
{
int i;
int o;
i = 0;
o = 0;
while (dest[i])
i++;
while (src[o] != '\0')
{
dest[i] = src[o];
i++;
o++;
}
dest[i] = '\0';
return (dest);
}
|
the_stack_data/156391845.c | #include <stdio.h>
#include <unistd.h>
int main() {
char buff[1024];
setvbuf(stdout, buff, _IOLBF, 1024);
char output[] = "Hello";
int i;
for (i = 0; i < sizeof(output)/sizeof(char) - 1; i++) {
printf("%c", output[i]);
sleep(1);
}
return 0;
}
|
the_stack_data/173577692.c | /*
gcc -std=c17 -lc -lm -pthread -o ../_build/c/string_wide_wmemchr.exe ./c/string_wide_wmemchr.c && (cd ../_build/c/;./string_wide_wmemchr.exe)
https://en.cppreference.com/w/c/string/wide/wmemchr
*/
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
int main(void)
{
wchar_t str[] = L"诺不轻信,故人不负我\0诺不轻许,故我不负人。";
size_t sz = sizeof str / sizeof *str;
wchar_t target = L'许';
wchar_t* result = wmemchr(str, target, sz);
if (result) {
setlocale(LC_ALL, "en_US.utf8");
printf("Found '%lc' at position %td\n",target, result - str);
}
}
|
the_stack_data/25137053.c | /*
* ---------------------------------------
* Copyright (c) Sebastian Günther 2021 |
* |
* [email protected] |
* |
* SPDX-License-Identifier: BSD-3-Clause |
* ---------------------------------------
*/
#include <stdio.h>
int main(int argc, char* argv[]) {
FILE* f_ptr = fopen("12_structs.c", "r");
char buffer[2000];
fread(buffer, 2000, 1, f_ptr);
printf("Content of file\n\n");
printf("%s", buffer);
printf("\n\nGoodbye\n");
} |
the_stack_data/460021.c | #include <stdio.h>
#include <assert.h>
int mainQ(int x, int y){
/* extended Euclid's algorithm */
assert(x >= 1);
assert(y >= 1);
int a,b,p,q,r,s;
a=x;
b=y;
p=1;
q=0;
r=0;
s=1;
while(1){
//assert(1 == p*s - r*q);
//assert(a == y*r + x*p);
//assert(b == x*q + y*s);
//%%%traces: int x, int y, int a, int b, int p, int r, int q, int s
if(!(a!=b)) break;
if (a>b) {
a = a-b;
p = p-q;
r = r-s;
}
else {
b = b-a;
q = q-p;
s = s-r;}
}
return a;
}
int main(int argc, char **argv){
mainQ(atoi(argv[1]), atoi(argv[2]));
return 0;
}
|
the_stack_data/241019.c |
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int info;
struct node *next;
}node;
void insert(node**l,int num)
{
node *p=(node*)malloc(sizeof(node));
if(p!=NULL){
p->info=num;
p->next=NULL;
if((*l)==NULL)*l=p;
else{(*l)->next=p;*l=p;}
}
else
printf("MEMORY ERROR!");
}
void display(node *f)
{
while(f!=NULL)
{
printf("%d ",f->info);
f=f->next;
}
}
void small(node *f)
{
int min=f->info;
while(f->next!=NULL)
{
if(min<f->info)
min=f->info;
f=f->next;
}
printf("\nSmallest element : %d",min);
}
int main()
{
node *first=NULL,*last=NULL;
char ch;int n;
do
{
printf("Enter the element you want to enter :");
scanf("%d",&n);
insert(&last,n);
if(first==NULL)first=last;
printf("Do you want to continue..Y/N");
fflush(stdin);
scanf("%c",&ch);
}while(ch=='y'||ch=='Y');
display(first);
small(first);
}
|
the_stack_data/86075249.c | /*
* 1742. 盒子中小球的最大数量
* https://leetcode-cn.com/problems/maximum-number-of-balls-in-a-box/
*/
#include <stdio.h>
#include <string.h>
void main() {
int num;
num = countBalls(1, 100000);
printf("%d\n", num);
}
int countBalls(int lowLimit, int highLimit)
{
int i,temp;
int num=0,max=0,maxNum=0;
int arr[46];
memset(arr, 0, 46 * sizeof(*arr));
for(i=lowLimit; i<=highLimit; i++) {
num = 0;
temp = i;
while(temp != 0) {
num += temp%10;
temp=temp/10;
}
arr[num] += 1;
if (num > max) {
max = num;
}
}
for (i=1;i<=max;i++) {
if (arr[i] > maxNum) {
maxNum = arr[i];
}
}
return maxNum;
}
|
the_stack_data/26341.c | #include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<stdbool.h>
#define ROW 14
#define COLUMN 14
#define PUZNUM 21
#define PUZRC 5
typedef const char* String;
bool firstplace(char Board[ROW][COLUMN][20], String color){
if(((strcmp(Board[4][4], "N") == 0) && (!(strcmp(Board[9][9], color) == 0)))
|| ((strcmp(Board[9][9], "N") == 0) && (!(strcmp(Board[4][4], color) == 0)))){
return true;
}
else{
return false;
}
}
void rotate(char (*puzzle)[PUZRC][PUZRC][20]){
int i, j;
char puztemp[PUZRC][PUZRC][20];
for(i = 0; i < 5 ; i++){
for(j = 0; j < 5; j++){
strcpy(puztemp[i][j], (*puzzle)[4-j][i]);
}
}
for( i = 0; i < 5; i++){
for( j = 0; j < 5; j++){
strcpy((*puzzle)[i][j], puztemp[i][j]);
}
}
}
void construct(char puzzle[PUZNUM][PUZRC][PUZRC][20], String color){
int i, j ,k;
for(i = 0; i < 21; i++){
for(j = 0; j < 5; j++){
for(k = 0; k < 5;k++){
strcpy(puzzle[i][j][k] ,"N");
}
}
}
strcpy(puzzle[0][0][0] , color);
strcpy(puzzle[1][0][0] , color);
strcpy(puzzle[1][0][1] , color);
strcpy(puzzle[2][0][0] , color);
strcpy(puzzle[2][0][1] , color);
strcpy(puzzle[2][1][1] , color);
strcpy(puzzle[3][0][0] , color);
strcpy(puzzle[3][0][1] , color);
strcpy(puzzle[3][0][2] , color);
strcpy(puzzle[4][0][0] , color);
strcpy(puzzle[4][0][1] , color);
strcpy(puzzle[4][1][0] , color);
strcpy(puzzle[4][1][1] , color);
strcpy(puzzle[5][0][0] , color);
strcpy(puzzle[5][0][1] , color);
strcpy(puzzle[5][0][2] , color);
strcpy(puzzle[5][1][0] , color);
strcpy(puzzle[6][0][0] , color);
strcpy(puzzle[6][0][1] , color);
strcpy(puzzle[6][0][2] , color);
strcpy(puzzle[6][1][1] , color);
strcpy(puzzle[7][0][0] , color);
strcpy(puzzle[7][0][1] , color);
strcpy(puzzle[7][1][1] , color);
strcpy(puzzle[7][1][2] , color);
strcpy(puzzle[8][0][0] , color);
strcpy(puzzle[8][0][1] , color);
strcpy(puzzle[8][0][2] , color);
strcpy(puzzle[8][0][3] , color);
strcpy(puzzle[9][0][0] , color);
strcpy(puzzle[9][0][1] , color);
strcpy(puzzle[9][0][2] , color);
strcpy(puzzle[9][1][0] , color);
strcpy(puzzle[9][1][1] , color);
strcpy(puzzle[10][0][0] , color);
strcpy(puzzle[10][0][1] , color);
strcpy(puzzle[10][0][2] , color);
strcpy(puzzle[10][1][0] , color);
strcpy(puzzle[10][1][2] , color);
strcpy(puzzle[11][0][0] , color);
strcpy(puzzle[11][0][1] , color);
strcpy(puzzle[11][0][2] , color);
strcpy(puzzle[11][1][1] , color);
strcpy(puzzle[11][2][1] , color);
strcpy(puzzle[12][0][0] , color);
strcpy(puzzle[12][0][1] , color);
strcpy(puzzle[12][0][2] , color);
strcpy(puzzle[12][1][0] , color);
strcpy(puzzle[12][2][0] , color);
strcpy(puzzle[13][0][0] , color);
strcpy(puzzle[13][0][1] , color);
strcpy(puzzle[13][1][1] , color);
strcpy(puzzle[13][1][2] , color);
strcpy(puzzle[13][2][2] , color);
strcpy(puzzle[14][0][0] , color);
strcpy(puzzle[14][1][0] , color);
strcpy(puzzle[14][1][1] , color);
strcpy(puzzle[14][1][2] , color);
strcpy(puzzle[14][2][2] , color);
strcpy(puzzle[15][0][0] , color);
strcpy(puzzle[15][1][0] , color);
strcpy(puzzle[15][1][1] , color);
strcpy(puzzle[15][1][2] , color);
strcpy(puzzle[15][2][1] , color);
strcpy(puzzle[16][0][1] , color);
strcpy(puzzle[16][1][0] , color);
strcpy(puzzle[16][1][1] , color);
strcpy(puzzle[16][1][2] , color);
strcpy(puzzle[16][2][1] , color);
strcpy(puzzle[17][0][0] , color);
strcpy(puzzle[17][0][1] , color);
strcpy(puzzle[17][0][2] , color);
strcpy(puzzle[17][0][3] , color);
strcpy(puzzle[17][1][0] , color);
strcpy(puzzle[18][0][0] , color);
strcpy(puzzle[18][0][1] , color);
strcpy(puzzle[18][0][2] , color);
strcpy(puzzle[18][1][2] , color);
strcpy(puzzle[18][1][3] , color);
strcpy(puzzle[19][0][0] , color);
strcpy(puzzle[19][0][1] , color);
strcpy(puzzle[19][0][2] , color);
strcpy(puzzle[19][0][3] , color);
strcpy(puzzle[19][1][1] , color);
strcpy(puzzle[20][0][0] , color);
strcpy(puzzle[20][0][1] , color);
strcpy(puzzle[20][0][2] , color);
strcpy(puzzle[20][0][3] , color);
strcpy(puzzle[20][0][4] , color);
}
void flip(char (*puzzle)[PUZRC][PUZRC][20]){
int i, j;
char puztemp[PUZRC][PUZRC][20];
for(i = 0; i < 5; i++){
for(j = 0; j < 5; j++){
strcpy(puztemp[i][j], (*puzzle)[4-i][j]);
}
}
for(i = 0; i < 5; i++){
for(j = 0; j < 5; j++){
strcpy((*puzzle)[i][j], puztemp[i][j]);
}
}
}
void ini_end(char (*puzzle)[PUZRC][PUZRC][20], int *ini_r, int *ini_c, int *end_r, int *end_c, String color){
int i, j;
bool find = false;
for(i = 0; i < 5; i++){
for(j = 0; j < 5; j++){
if(strcmp((*puzzle)[i][j], color) == 0){
*ini_r = i;
find = true;
break;
}
}
if(find){
break;
}
}
find = false;
for(j = 0; j < 5; j++){
for(i = 0; i < 5; i++){
if(strcmp((*puzzle)[i][j], color) == 0){
*ini_c = j;
find = true;
break;
}
}
if(find){
break;
}
}
find = false;
for(i = 4; i >= 0; i--){
for(j = 0; j < 5; j++){
if(strcmp((*puzzle)[i][j], color) == 0){
*end_r = i;
find = true;
break;
}
}
if(find){
break;
}
}
find = false;
for(j = 4; j >= 0; j--){
for(i = 0; i < 5; i++){
if(strcmp((*puzzle)[i][j], color) == 0){
*end_c = j;
find = true;
break;
}
}
if(find){
break;
}
}
}
bool placeable(char (*puzzle)[PUZRC][PUZRC][20], char Board[ROW][COLUMN][20], int k, int t, int *ini_r, int *end_r, int *ini_c, int *end_c, String color){
int i, j;
bool canplace;
bool pass1 = true;
bool pass2 = false;
bool pass3 = true;
for(i = *ini_r; i < *end_r + 1; i++){
for(j = *ini_c; j < *end_c + 1; j++){
int m = i+k-*ini_r;
int n = j+t-*ini_c;
if((m > 13) || (n > 13) || (m < 0) || (n < 0)){
pass3 = false;
break;
}
else if(strcmp((*puzzle)[i][j], color) == 0){
if(m == 0 && n == 0){
if((!(strcmp(Board[m+1][n], color) == 0)) && (!(strcmp(Board[m][n+1], color) == 0))
&& (strcmp(Board[m][n], "N") == 0)){
pass1 = pass1 & true;
}
else{
pass1 = pass1 & false;
break;
}
if(strcmp(Board[m+1][n+1], color) == 0){
pass2 = pass2 | true;
}
else{
pass2 = pass2 | false;
}
}
else if(m == 13 && n == 0){
if((!(strcmp(Board[m][n+1], color) == 0)) && (!(strcmp(Board[m-1][n], color) == 0))
&& (strcmp(Board[m][n], "N") == 0)){
pass1 = pass1 & true;
}
else{
pass1 = pass1 & false;
break;
}
if(strcmp(Board[m-1][n+1], color) == 0){
pass2 = pass2 | true;
}
else{
pass2 = pass2 | false;
}
}
else if(m == 0 && n == 13){
if((!(strcmp(Board[m+1][n], color) == 0)) && (!(strcmp(Board[m][n-1], color) == 0))
&& (strcmp(Board[m][n], "N") == 0)){
pass1 = pass1 & true;
}
else{
pass1 = pass1 & false;
break;
}
if(strcmp(Board[m+1][n-1], color) == 0){
pass2 = pass2 | true;
}
else{
pass2 = pass2 | false;
}
}
else if(m == 13 && n == 13){
if( (!(strcmp(Board[m][n-1], color) == 0)) && (!(strcmp(Board[m-1][n], color) == 0))
&& (strcmp(Board[m][n], "N") == 0)){
pass1 = pass1 & true;
}
else{
pass1 = pass1 & false;
break;
}
if(strcmp(Board[m-1][n-1], color) == 0){
pass2 = pass2 | true;
}
else{
pass2 = pass2 | false;
}
}
else if(m == 0){
if((!(strcmp(Board[m+1][n], color) == 0)) && (!(strcmp(Board[m][n+1], color) == 0))
&& (!(strcmp(Board[m][n-1], color) == 0)) && (strcmp(Board[m][n], "N") == 0)){
pass1 = pass1 & true;
}
else{
pass1 = pass1 & false;
break;
}
if((strcmp(Board[m+1][n+1], color) == 0) || (strcmp(Board[m+1][n-1], color) == 0) ){
pass2 = pass2 | true;
}
else{
pass2 = pass2 | false;
}
}
else if(m == 13){
if((!(strcmp(Board[m][n+1], color) == 0)) && (!(strcmp(Board[m][n-1], color) == 0))
&& (!(strcmp(Board[m-1][n], color) == 0)) && (strcmp(Board[m][n], "N") == 0)){
pass1 = pass1 & true;
}
else{
pass1 = pass1 & false;
break;
}
if((strcmp(Board[m-1][n-1], color) == 0) || (strcmp(Board[m-1][n+1], color) == 0)){
pass2 = pass2 | true;
}
else{
pass2 = pass2 | false;
}
}
else if(n == 0){
if((!(strcmp(Board[m+1][n], color) == 0)) && (!(strcmp(Board[m][n+1], color) == 0))
&& (!(strcmp(Board[m-1][n], color) == 0)) && (strcmp(Board[m][n], "N") == 0)){
pass1 = pass1 & true;
}
else{
pass1 = pass1 & false;
break;
}
if((strcmp(Board[m+1][n+1], color) == 0) || (strcmp(Board[m-1][n+1], color) == 0)){
pass2 = pass2 | true;
}
else{
pass2 = pass2 | false;
}
}
else if(n == 13){
if((!(strcmp(Board[m+1][n], color) == 0)) && (!(strcmp(Board[m][n-1], color) == 0))
&& (!(strcmp(Board[m-1][n], color) == 0)) && (strcmp(Board[m][n], "N") == 0)){
pass1 = pass1 & true;
}
else{
pass1 = pass1 & false;
break;
}
if(((strcmp(Board[m-1][n-1], color) == 0) || (strcmp(Board[m+1][n-1], color) == 0))){
pass2 = pass2 | true;
}
else{
pass2 = pass2 | false;
}
}
else{
if((!(strcmp(Board[m+1][n], color) == 0)) && (!(strcmp(Board[m][n+1], color) == 0))
&& (!(strcmp(Board[m][n-1], color) == 0)) && (!(strcmp(Board[m-1][n], color) == 0))
&& (strcmp(Board[m][n], "N") == 0)){
pass1 = pass1 & true;
}
else{
pass1 = pass1 & false;
break;
}
if((strcmp(Board[m+1][n+1], color) == 0) || (strcmp(Board[m-1][n-1], color) == 0)
|| (strcmp(Board[m+1][n-1], color) == 0) || (strcmp(Board[m-1][n+1], color) == 0)){
pass2 = pass2 | true;
}
else{
pass2 = pass2 | false;
}
}
}
}
if((!pass1) || (!pass3)){
break;
}
}
canplace = pass1 & pass2 & pass3;
return canplace;
}
void findarc(char Board[ROW][COLUMN][20], int *k, int *t, int *n, String color){
int i, j;
bool isarc;
bool pass1;
bool pass2;
for(i = 0; i < 14; i++){
for(j = 0; j < 14; j++){
if(i == 0 && j == 0){
if((!(strcmp(Board[i+1][j], color) == 0)) && (!(strcmp(Board[i][j+1], color) == 0))
&& (strcmp(Board[i][j], "N") == 0)){
pass1 = true;
}
else{
pass1 = false;
}
if(strcmp(Board[i+1][j+1], color) == 0){
pass2 = true;
}
else{
pass2 = false;
}
}
else if(i == 13 && j == 0){
if((!(strcmp(Board[i][j+1], color) == 0)) && (!(strcmp(Board[i-1][j], color) == 0))
&& (strcmp(Board[i][j], "N") == 0)){
pass1 = true;
}
else{
pass1 = false;
}
if(strcmp(Board[i-1][j+1], color) == 0){
pass2 = true;
}
else{
pass2 = false;
}
}
else if(i == 0 && j == 13){
if((!(strcmp(Board[i+1][j], color) == 0)) && (!(strcmp(Board[i][j-1], color) == 0))
&& (strcmp(Board[i][j], "N") == 0)){
pass1 = true;
}
else{
pass1 = false;
}
if(strcmp(Board[i+1][j-1], color) == 0){
pass2 = true;
}
else{
pass2 = false;
}
}
else if(i == 13 && j == 13){
if( (!(strcmp(Board[i][j-1], color) == 0)) && (!(strcmp(Board[i-1][j], color) == 0))
&& (strcmp(Board[i][j], "N") == 0)){
pass1 = true;
}
else{
pass1 = false;
}
if(strcmp(Board[i-1][j-1], color) == 0){
pass2 = true;
}
else{
pass2 = false;
}
}
else if(i == 0){
if((!(strcmp(Board[i+1][j], color) == 0)) && (!(strcmp(Board[i][j+1], color) == 0))
&& (!(strcmp(Board[i][j-1], color) == 0)) && (strcmp(Board[i][j], "N") == 0)){
pass1 = true;
}
else{
pass1 = false;
}
if((strcmp(Board[i+1][j+1], color) == 0) || (strcmp(Board[i+1][j-1], color) == 0) ){
pass2 = true;
}
else{
pass2 = false;
}
}
else if(i == 13){
if((!(strcmp(Board[i][j+1], color) == 0)) && (!(strcmp(Board[i][j-1], color) == 0))
&& (!(strcmp(Board[i-1][j], color) == 0)) && (strcmp(Board[i][j], "N") == 0)){
pass1 = true;
}
else{
pass1 = false;
}
if((strcmp(Board[i-1][j-1], color) == 0) || (strcmp(Board[i-1][j+1], color) == 0)){
pass2 = true;
}
else{
pass2 = false;
}
}
else if(j == 0){
if((!(strcmp(Board[i+1][j], color) == 0)) && (!(strcmp(Board[i][j+1], color) == 0))
&& (!(strcmp(Board[i-1][j], color) == 0)) && (strcmp(Board[i][j], "N") == 0)){
pass1 = true;
}
else{
pass1 = false;
}
if((strcmp(Board[i+1][j+1], color) == 0) || (strcmp(Board[i-1][j+1], color) == 0)){
pass2 = true;
}
else{
pass2 = false;
}
}
else if(j == 13){
if((!(strcmp(Board[i+1][j], color) == 0)) && (!(strcmp(Board[i][j-1], color) == 0))
&& (!(strcmp(Board[i-1][j], color) == 0)) && (strcmp(Board[i][j], "N") == 0)){
pass1 = true;
}
else{
pass1 = false;
}
if(((strcmp(Board[i-1][j-1], color) == 0) || (strcmp(Board[i+1][j-1], color) == 0))){
pass2 = true;
}
else{
pass2 = false;
}
}
else{
if((!(strcmp(Board[i+1][j], color) == 0)) && (!(strcmp(Board[i][j+1], color) == 0))
&& (!(strcmp(Board[i][j-1], color) == 0)) && (!(strcmp(Board[i-1][j], color) == 0))
&& (strcmp(Board[i][j], "N") == 0)){
pass1 = true;
}
else{
pass1 = false;
}
if((strcmp(Board[i+1][j+1], color) == 0) || (strcmp(Board[i-1][j-1], color) == 0)
|| (strcmp(Board[i+1][j-1], color) == 0) || (strcmp(Board[i-1][j+1], color) == 0)){
pass2 = true;
}
else{
pass2 = false;
}
}
isarc = pass1 & pass2;
if(isarc){
k[*n] = i;
t[*n] = j;
*n = *n + 1;
}
}
}
}
void place(int k, int t, int *ini_r, int *end_r, int *ini_c, int *end_c,char Board[ROW][COLUMN][20], char (*puzzle)[PUZRC][PUZRC][20]){
int i,j;
for(i = *ini_r; i < *end_r + 1; i++){
for(j = *ini_c; j < *end_c + 1; j++){
int m = i-*ini_r+k;
int n = j-*ini_c+t;
if(strcmp(Board[m][n], "N") == 0){
strcpy(Board[m][n], (*puzzle)[i][j]);
}
}
}
}
/*void arc_area(String Board[ROW][COLUMN], int *t_arc, int *t_area, String color){
for(i = 0; i < 14; i++){
for(j = 0; j < 14; j++){
if(i == 0 && j == 0){
if((!(strcmp(Board[i+1][j], color) == 0)) && (!(strcmp(Board[m][n+1], color) == 0))
&& ((strcmp(Board[m+1][n+1], color) == 0) || (strcmp(Board[m+1][n+1], color2) == 0))
&& (strcmp(Board[m][n], "N") == 0)){
*t_arc = *t_arc + 1;
*t_area = *t_area +
}
}
}
}
}*/
void arcinfo(char (*puzzle)[PUZRC][PUZRC][20], char Board[ROW][COLUMN][20], int k, int t, int ini_r, int end_r, int ini_c, int end_c,int *opparc_r, int *opparc_c,
int *elmarc_r, int *elmarc_c, int *createarc_r, int *createarc_c, int *opparcnum, int *elmnum, int *createnum, int *oppedgenum,int *dest, int *dest1, int *dest2, bool *creat,
bool *elmin, bool *oppo, String color, String color2){
int i, j;
for(i = ini_r; i < end_r+1; i++){
for(j = ini_c; j < end_c+1; j++){
int m = k+i-ini_r;
int n = t+j-ini_c;
if(strcmp((*puzzle)[i][j], color) == 0){
if(m == 0 && n == 0){
if((i + 1 > end_r) && (j + 1 > end_c)){
if(strcmp(Board[m+1][n+1], "N") == 0){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 0;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(i + 1 > end_r){
if((strcmp(Board[m+1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i][j+1], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 0;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(j + 1 > end_c){
if((strcmp(Board[m+1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i+1][j], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 0;
*createnum = *createnum + 1;
*creat = true;
}
}
else{
if((strcmp(Board[m+1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i+1][j], color) == 0)) && (!(strcmp((*puzzle)[i][j+1], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 0;
*createnum = *createnum + 1;
*creat = true;
}
}
if((strcmp(Board[m+1][n+1], color) == 0) && (!(strcmp(Board[m][n+1], color) == 0)) && (!(strcmp(Board[m+1][n], color) == 0))){
elmarc_r[*elmnum] = m;
elmarc_c[*elmnum] = n;
dest1[*elmnum] = 0;
*elmnum = *elmnum + 1;
*elmin = true;
}
if((strcmp(Board[m+1][n+1], color2) == 0) && (!(strcmp(Board[m][n+1], color2) == 0)) && (!(strcmp(Board[m+1][n], color2) == 0))){
opparc_r[*opparcnum] = m;
opparc_c[*opparcnum] = n;
dest2[*opparcnum] = 0;
*opparcnum = *opparcnum + 1;
*oppo = true;
}
if((strcmp(Board[m+1][n], color2) == 0) || (strcmp(Board[m][n+1], color2) == 0)){
*oppedgenum = *oppedgenum + 1;
}
}
else if(m == 0 && n == 13){
if((i + 1 > end_r) && (j - 1 < ini_c)){
if(strcmp(Board[m+1][n-1], "N") == 0){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 1;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(i + 1 > end_r){
if((strcmp(Board[m+1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i][j-1], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 1;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(j - 1 < ini_c){
if((strcmp(Board[m+1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i+1][j], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 1;
*createnum = *createnum + 1;
*creat = true;
}
}
else{
if((strcmp(Board[m+1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i+1][j], color) == 0)) && (!(strcmp((*puzzle)[i][j-1], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 1;
*createnum = *createnum + 1;
*creat = true;
}
}
if((strcmp(Board[m+1][n-1], color) == 0) && (!(strcmp(Board[m][n-1], color) == 0)) && (!(strcmp(Board[m+1][n], color) == 0))){
elmarc_r[*elmnum] = m;
elmarc_c[*elmnum] = n;
dest1[*elmnum] = 1;
*elmnum = *elmnum + 1;
*elmin = true;
}
if((strcmp(Board[m+1][n-1], color2) == 0) && (!(strcmp(Board[m][n-1], color2) == 0)) && (!(strcmp(Board[m+1][n], color2) == 0))){
opparc_r[*opparcnum] = m;
opparc_c[*opparcnum] = n;
dest2[*opparcnum] = 1;
*opparcnum = *opparcnum + 1;
*oppo = true;
}
if((strcmp(Board[m+1][n], color2) == 0) || (strcmp(Board[m][n-1], color2) == 0)){
*oppedgenum = *oppedgenum + 1;
}
}
else if(m == 13 && n == 0){
if((i - 1 < ini_r) && (j + 1 > end_c)){
if(strcmp(Board[m-1][n+1], "N") == 0){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 2;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(i - 1 < ini_r){
if((strcmp(Board[m-1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i][j+1], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 2;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(j + 1 > end_c){
if((strcmp(Board[m-1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i-1][j], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 2;
*createnum = *createnum + 1;
*creat = true;
}
}
else{
if((strcmp(Board[m-1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i-1][j], color) == 0)) && (!(strcmp((*puzzle)[i][j+1], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 2;
*createnum = *createnum + 1;
*creat = true;
}
}
if((strcmp(Board[m-1][n+1], color) == 0) && (!(strcmp(Board[m][n+1], color) == 0)) && (!(strcmp(Board[m-1][n], color) == 0))){
elmarc_r[*elmnum] = m;
elmarc_c[*elmnum] = n;
dest1[*elmnum] = 2;
*elmnum = *elmnum + 1;
*elmin = true;
}
if((strcmp(Board[m-1][n+1], color2) == 0) && (!(strcmp(Board[m][n+1], color2) == 0)) && (!(strcmp(Board[m-1][n], color2) == 0))){
opparc_r[*opparcnum] = m;
opparc_c[*opparcnum] = n;
dest2[*opparcnum] = 2;
*opparcnum = *opparcnum + 1;
*oppo = true;
}
if((strcmp(Board[m-1][n], color2) == 0) || (strcmp(Board[m][n+1], color2) == 0)){
*oppedgenum = *oppedgenum + 1;
}
}
else if(m == 13 && n == 13){
if((i - 1 < ini_r) && (j - 1 < ini_c)){
if(strcmp(Board[m-1][n-1], "N") == 0){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 3;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(i - 1 < ini_r){
if((strcmp(Board[m-1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i][j-1], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 3;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(j - 1 < ini_c){
if((strcmp(Board[m-1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i-1][j], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 3;
*createnum = *createnum + 1;
*creat = true;
}
}
else{
if((strcmp(Board[m-1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i-1][j], color) == 0)) && (!(strcmp((*puzzle)[i][j-1], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 3;
*createnum = *createnum + 1;
*creat = true;
}
}
if((strcmp(Board[m-1][n-1], color) == 0) && (!(strcmp(Board[m][n-1], color) == 0)) && (!(strcmp(Board[m-1][n], color) == 0))){
elmarc_r[*elmnum] = m;
elmarc_c[*elmnum] = n;
dest1[*elmnum] = 3;
*elmnum = *elmnum + 1;
*elmin = true;
}
if((strcmp(Board[m-1][n-1], color2) == 0) && (!(strcmp(Board[m][n-1], color2) == 0)) && (!(strcmp(Board[m-1][n], color2) == 0))){
opparc_r[*opparcnum] = m;
opparc_c[*opparcnum] = n;
dest2[*opparcnum] = 3;
*opparcnum = *opparcnum + 1;
*oppo = true;
}
if((strcmp(Board[m-1][n], color2) == 0) || (strcmp(Board[m][n-1], color2) == 0)){
*oppedgenum = *oppedgenum + 1;
}
}
else if(m == 0){
if((i + 1 > end_r) && (j + 1 > end_c)){
if(strcmp(Board[m+1][n+1], "N") == 0){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 0;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(i + 1 > end_r){
if((strcmp(Board[m+1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i][j+1], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 0;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(j + 1 > end_c){
if((strcmp(Board[m+1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i+1][j], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 0;
*createnum = *createnum + 1;
*creat = true;
}
}
else{
if((strcmp(Board[m+1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i+1][j], color) == 0)) && (!(strcmp((*puzzle)[i][j+1], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 0;
*createnum = *createnum + 1;
*creat = true;
}
}
if((i + 1 > end_r) && (j - 1 < ini_c)){
if(strcmp(Board[m+1][n-1], "N") == 0){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 1;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(i + 1 > end_r){
if((strcmp(Board[m+1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i][j-1], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 1;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(j - 1 < ini_c){
if((strcmp(Board[m+1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i+1][j], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 1;
*createnum = *createnum + 1;
*creat = true;
}
}
else{
if((strcmp(Board[m+1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i+1][j], color) == 0)) && (!(strcmp((*puzzle)[i][j-1], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 1;
*createnum = *createnum + 1;
*creat = true;
}
}
if(((strcmp(Board[m+1][n+1], color) == 0) && (!(strcmp(Board[m][n+1], color) == 0)) && (!(strcmp(Board[m+1][n], color) == 0)))){
elmarc_r[*elmnum] = m;
elmarc_c[*elmnum] = n;
dest1[*elmnum] = 0;
*elmnum = *elmnum + 1;
*elmin = true;
}
if(((strcmp(Board[m+1][n-1], color) == 0) && (!(strcmp(Board[m][n-1], color) == 0)) && (!(strcmp(Board[m+1][n], color) == 0)))){
elmarc_r[*elmnum] = m;
elmarc_c[*elmnum] = n;
dest1[*elmnum] = 1;
*elmnum = *elmnum + 1;
*elmin = true;
}
if(((strcmp(Board[m+1][n+1], color2) == 0) && (!(strcmp(Board[m][n+1], color2) == 0)) && (!(strcmp(Board[m+1][n], color2) == 0)))){
opparc_r[*opparcnum] = m;
opparc_c[*opparcnum] = n;
dest2[*opparcnum] = 0;
*opparcnum = *opparcnum + 1;
*oppo = true;
}
if(((strcmp(Board[m+1][n-1], color2) == 0) && (!(strcmp(Board[m][n-1], color2) == 0)) && (!(strcmp(Board[m+1][n], color2) == 0)))){
opparc_r[*opparcnum] = m;
opparc_c[*opparcnum] = n;
dest2[*opparcnum] = 1;
*opparcnum = *opparcnum + 1;
*oppo = true;
}
if((strcmp(Board[m+1][n], color2) == 0) || (strcmp(Board[m][n+1], color2) == 0)
|| (strcmp(Board[m][n-1], color2) == 0)){
*oppedgenum = *oppedgenum + 1;
}
}
else if(m == 13){
if((i - 1 < ini_r) && (j + 1 > end_c)){
if(strcmp(Board[m-1][n+1], "N") == 0){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 2;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(i - 1 < ini_r){
if((strcmp(Board[m-1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i][j+1], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 2;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(j + 1 > end_c){
if((strcmp(Board[m-1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i-1][j], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 2;
*createnum = *createnum + 1;
*creat = true;
}
}
else{
if((strcmp(Board[m-1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i-1][j], color) == 0)) && (!(strcmp((*puzzle)[i][j+1], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 2;
*createnum = *createnum + 1;
*creat = true;
}
}
if((i - 1 < ini_r) && (j - 1 < ini_c)){
if(strcmp(Board[m-1][n-1], "N") == 0){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 3;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(i - 1 < ini_r){
if((strcmp(Board[m-1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i][j-1], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 3;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(j - 1 < ini_c){
if((strcmp(Board[m-1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i-1][j], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 3;
*createnum = *createnum + 1;
*creat = true;
}
}
else{
if((strcmp(Board[m-1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i-1][j], color) == 0)) && (!(strcmp((*puzzle)[i][j-1], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 3;
*createnum = *createnum + 1;
*creat = true;
}
}
if(((strcmp(Board[m-1][n+1], color) == 0) && (!(strcmp(Board[m][n+1], color) == 0)) && (!(strcmp(Board[m-1][n], color) == 0)))){
elmarc_r[*elmnum] = m;
elmarc_c[*elmnum] = n;
dest1[*elmnum] = 2;
*elmnum = *elmnum + 1;
*elmin = true;
}
if(((strcmp(Board[m-1][n-1], color) == 0) && (!(strcmp(Board[m][n-1], color) == 0)) && (!(strcmp(Board[m-1][n], color) == 0)))){
elmarc_r[*elmnum] = m;
elmarc_c[*elmnum] = n;
dest1[*elmnum] = 3;
*elmnum = *elmnum + 1;
*elmin = true;
}
if(((strcmp(Board[m-1][n+1], color2) == 0) && (!(strcmp(Board[m][n+1], color2) == 0)) && (!(strcmp(Board[m-1][n], color2) == 0)))){
opparc_r[*opparcnum] = m;
opparc_c[*opparcnum] = n;
dest2[*opparcnum] = 2;
*opparcnum = *opparcnum + 1;
*oppo = true;
}
if(((strcmp(Board[m-1][n-1], color2) == 0) && (!(strcmp(Board[m][n-1], color2) == 0)) && (!(strcmp(Board[m-1][n], color2) == 0)))){
opparc_r[*opparcnum] = m;
opparc_c[*opparcnum] = n;
dest2[*opparcnum] = 3;
*opparcnum = *opparcnum + 1;
*oppo = true;
}
if((strcmp(Board[m-1][n], color2) == 0) || (strcmp(Board[m][n+1], color2) == 0)
|| (strcmp(Board[m][n-1], color2) == 0)){
*oppedgenum = *oppedgenum + 1;
}
}
else if(n == 13){
if((i + 1 > end_r) && (j - 1 < ini_c)){
if(strcmp(Board[m+1][n-1], "N") == 0){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 1;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(i + 1 > end_r){
if((strcmp(Board[m+1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i][j-1], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 1;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(j - 1 < ini_c){
if((strcmp(Board[m+1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i+1][j], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 1;
*createnum = *createnum + 1;
*creat = true;
}
}
else{
if((strcmp(Board[m+1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i+1][j], color) == 0)) && (!(strcmp((*puzzle)[i][j-1], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 1;
*createnum = *createnum + 1;
*creat = true;
}
}
if((i - 1 < ini_r) && (j - 1 < ini_c)){
if(strcmp(Board[m-1][n-1], "N") == 0){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 3;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(i - 1 < ini_r){
if((strcmp(Board[m-1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i][j-1], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 3;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(j - 1 < ini_c){
if((strcmp(Board[m-1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i-1][j], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 3;
*createnum = *createnum + 1;
*creat = true;
}
}
else{
if((strcmp(Board[m-1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i-1][j], color) == 0)) && (!(strcmp((*puzzle)[i][j-1], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 3;
*createnum = *createnum + 1;
*creat = true;
}
}
if(((strcmp(Board[m+1][n-1], color) == 0) && (!(strcmp(Board[m][n-1], color) == 0)) && (!(strcmp(Board[m+1][n], color) == 0)))){
elmarc_r[*elmnum] = m;
elmarc_c[*elmnum] = n;
dest1[*elmnum] = 1;
*elmnum = *elmnum + 1;
*elmin = true;
}
if(((strcmp(Board[m-1][n-1], color) == 0) && (!(strcmp(Board[m][n-1], color) == 0)) && (!(strcmp(Board[m-1][n], color) == 0)))){
elmarc_r[*elmnum] = m;
elmarc_c[*elmnum] = n;
dest1[*elmnum] = 3;
*elmnum = *elmnum + 1;
*elmin = true;
}
if(((strcmp(Board[m+1][n-1], color2) == 0) && (!(strcmp(Board[m][n-1], color2) == 0)) && (!(strcmp(Board[m+1][n], color2) == 0)))){
opparc_r[*opparcnum] = m;
opparc_c[*opparcnum] = n;
dest2[*opparcnum] = 1;
*opparcnum = *opparcnum + 1;
*oppo = true;
}
if(((strcmp(Board[m-1][n-1], color2) == 0) && (!(strcmp(Board[m][n-1], color2) == 0)) && (!(strcmp(Board[m-1][n], color2) == 0)))){
opparc_r[*opparcnum] = m;
opparc_c[*opparcnum] = n;
dest2[*opparcnum] = 3;
*opparcnum = *opparcnum + 1;
*oppo = true;
}
if((strcmp(Board[m+1][n], color2) == 0) || (strcmp(Board[m-1][n], color2) == 0)
|| (strcmp(Board[m][n-1], color2) == 0)){
*oppedgenum = *oppedgenum + 1;
}
}
else if(n == 0){
if((i - 1 < ini_r) && (j + 1 > end_c)){
if(strcmp(Board[m-1][n+1], "N") == 0){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 2;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(i - 1 < ini_r){
if((strcmp(Board[m-1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i][j+1], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 2;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(j + 1 > end_c){
if((strcmp(Board[m-1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i-1][j], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 2;
*createnum = *createnum + 1;
*creat = true;
}
}
else{
if((strcmp(Board[m-1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i-1][j], color) == 0)) && (!(strcmp((*puzzle)[i][j+1], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 2;
*createnum = *createnum + 1;
*creat = true;
}
}
if((i + 1 > end_r) && (j + 1 > end_c)){
if(strcmp(Board[m+1][n+1], "N") == 0){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 0;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(i + 1 > end_r){
if((strcmp(Board[m+1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i][j+1], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 0;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(j + 1 > end_c){
if((strcmp(Board[m+1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i+1][j], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 0;
*createnum = *createnum + 1;
*creat = true;
}
}
else{
if((strcmp(Board[m+1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i+1][j], color) == 0)) && (!(strcmp((*puzzle)[i][j+1], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 0;
*createnum = *createnum + 1;
*creat = true;
}
}
if(((strcmp(Board[m-1][n+1], color) == 0) && (!(strcmp(Board[m][n+1], color) == 0)) && (!(strcmp(Board[m-1][n], color) == 0)))){
elmarc_r[*elmnum] = m;
elmarc_c[*elmnum] = n;
dest1[*elmnum] = 2;
*elmnum = *elmnum + 1;
*elmin = true;
}
if(((strcmp(Board[m+1][n+1], color) == 0) && (!(strcmp(Board[m][n+1], color) == 0)) && (!(strcmp(Board[m+1][n], color) == 0)))){
elmarc_r[*elmnum] = m;
elmarc_c[*elmnum] = n;
dest1[*elmnum] = 0;
*elmnum = *elmnum + 1;
*elmin = true;
}
if(((strcmp(Board[m-1][n+1], color2) == 0) && (!(strcmp(Board[m][n+1], color2) == 0)) && (!(strcmp(Board[m-1][n], color2) == 0)))){
opparc_r[*opparcnum] = m;
opparc_c[*opparcnum] = n;
dest2[*opparcnum] = 2;
*opparcnum = *opparcnum + 1;
*oppo = true;
}
if(((strcmp(Board[m+1][n+1], color2) == 0) && (!(strcmp(Board[m][n+1], color2) == 0)) && (!(strcmp(Board[m+1][n], color2) == 0)))){
opparc_r[*opparcnum] = m;
opparc_c[*opparcnum] = n;
dest2[*opparcnum] = 0;
*opparcnum = *opparcnum + 1;
*oppo = true;
}
if((strcmp(Board[m-1][n], color2) == 0) || (strcmp(Board[m+1][n], color2) == 0)
|| (strcmp(Board[m][n], color2) == 0)){
*oppedgenum = *oppedgenum + 1;
}
}
else{
if((i - 1 < ini_r) && (j + 1 > end_c)){
if(strcmp(Board[m-1][n+1], "N") == 0){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 2;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(i - 1 < ini_r){
if((strcmp(Board[m-1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i][j+1], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 2;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(j + 1 > end_c){
if((strcmp(Board[m-1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i-1][j], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 2;
*createnum = *createnum + 1;
*creat = true;
}
}
else{
if((strcmp(Board[m-1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i-1][j], color) == 0)) && (!(strcmp((*puzzle)[i][j+1], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 2;
*createnum = *createnum + 1;
*creat = true;
}
}
if((i - 1 < ini_r) && (j - 1 < ini_c)){
if(strcmp(Board[m-1][n-1], "N") == 0){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 3;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(i - 1 < ini_r){
if((strcmp(Board[m-1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i][j-1], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 3;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(j - 1 < ini_c){
if((strcmp(Board[m-1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i-1][j], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 3;
*createnum = *createnum + 1;
*creat = true;
}
}
else{
if((strcmp(Board[m-1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i-1][j], color) == 0)) && (!(strcmp((*puzzle)[i][j-1], color) == 0))){
createarc_r[*createnum] = m - 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 3;
*createnum = *createnum + 1;
*creat = true;
}
}
if((i + 1 > end_r) && (j + 1 > end_c)){
if(strcmp(Board[m+1][n+1], "N") == 0){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 0;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(i + 1 > end_r){
if((strcmp(Board[m+1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i][j+1], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 0;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(j + 1 > end_c){
if((strcmp(Board[m+1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i+1][j], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 0;
*createnum = *createnum + 1;
*creat = true;
}
}
else{
if((strcmp(Board[m+1][n+1], "N") == 0) && (!(strcmp((*puzzle)[i+1][j], color) == 0)) && (!(strcmp((*puzzle)[i][j+1], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n + 1;
dest[*createnum] = 0;
*createnum = *createnum + 1;
*creat = true;
}
}
if((i + 1 > end_r) && (j - 1 < ini_c)){
if(strcmp(Board[m+1][n-1], "N") == 0){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 1;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(i + 1 > end_r){
if((strcmp(Board[m+1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i][j-1], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 1;
*createnum = *createnum + 1;
*creat = true;
}
}
else if(j - 1 < ini_c){
if((strcmp(Board[m+1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i+1][j], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 1;
*createnum = *createnum + 1;
*creat = true;
}
}
else{
if((strcmp(Board[m+1][n-1], "N") == 0) && (!(strcmp((*puzzle)[i+1][j], color) == 0)) && (!(strcmp((*puzzle)[i][j-1], color) == 0))){
createarc_r[*createnum] = m + 1;
createarc_c[*createnum] = n - 1;
dest[*createnum] = 1;
*createnum = *createnum + 1;
*creat = true;
}
}
if(((strcmp(Board[m-1][n+1], color) == 0) && (!(strcmp(Board[m][n+1], color) == 0)) && (!(strcmp(Board[m-1][n], color) == 0)))){
elmarc_r[*elmnum] = m;
elmarc_c[*elmnum] = n;
dest1[*elmnum] = 2;
*elmnum = *elmnum + 1;
*elmin = true;
}
if(((strcmp(Board[m-1][n-1], color) == 0) && (!(strcmp(Board[m][n-1], color) == 0)) && (!(strcmp(Board[m-1][n], color) == 0)))){
elmarc_r[*elmnum] = m;
elmarc_c[*elmnum] = n;
dest1[*elmnum] = 3;
*elmnum = *elmnum + 1;
*elmin = true;
}
if(((strcmp(Board[m+1][n+1], color) == 0) && (!(strcmp(Board[m][n+1], color) == 0)) && (!(strcmp(Board[m+1][n], color) == 0)))){
elmarc_r[*elmnum] = m;
elmarc_c[*elmnum] = n;
dest1[*elmnum] = 0;
*elmnum = *elmnum + 1;
*elmin = true;
}
if(((strcmp(Board[m+1][n-1], color) == 0) && (!(strcmp(Board[m][n-1], color) == 0)) && (!(strcmp(Board[m+1][n], color) == 0)))){
elmarc_r[*elmnum] = m;
elmarc_c[*elmnum] = n;
dest1[*elmnum] = 1;
*elmnum = *elmnum + 1;
*elmin = true;
}
if(((strcmp(Board[m-1][n+1], color2) == 0) && (!(strcmp(Board[m][n+1], color2) == 0)) && (!(strcmp(Board[m-1][n], color2) == 0)))){
opparc_r[*opparcnum] = m;
opparc_c[*opparcnum] = n;
dest2[*opparcnum] = 2;
*opparcnum = *opparcnum + 1;
*oppo = true;
}
if(((strcmp(Board[m-1][n-1], color2) == 0) && (!(strcmp(Board[m][n-1], color2) == 0)) && (!(strcmp(Board[m-1][n], color2) == 0)))){
opparc_r[*opparcnum] = m;
opparc_c[*opparcnum] = n;
dest2[*opparcnum] = 3;
*opparcnum = *opparcnum + 1;
*oppo = true;
}
if(((strcmp(Board[m+1][n+1], color2) == 0) && (!(strcmp(Board[m][n+1], color2) == 0)) && (!(strcmp(Board[m+1][n], color2) == 0)))){
opparc_r[*opparcnum] = m;
opparc_c[*opparcnum] = n;
dest2[*opparcnum] = 0;
*opparcnum = *opparcnum + 1;
*oppo = true;
}
if(((strcmp(Board[m+1][n-1], color2) == 0) && (!(strcmp(Board[m][n-1], color2) == 0)) && (!(strcmp(Board[m+1][n], color2) == 0)))){
opparc_r[*opparcnum] = m;
opparc_c[*opparcnum] = n;
dest2[*opparcnum] = 1;
*opparcnum = *opparcnum + 1;
*oppo = true;
}
if((strcmp(Board[m-1][n], color2) == 0) || (strcmp(Board[m][n+1], color2) == 0)
|| (strcmp(Board[m][n-1], color2) == 0) || (strcmp(Board[m+1][n], color2) == 0)){
*oppedgenum = *oppedgenum + 1;
}
}
}
}
}
}
void arcroundedge(char Board[ROW][COLUMN][20], int arc_r, int arc_c, int *roundedge, String color2){
if(arc_r == 0 && arc_c == 0){
if((strcmp(Board[arc_r+1][arc_c], color2) == 0) || (strcmp(Board[arc_r][arc_c+1], color2) == 0)){
*roundedge = *roundedge + 1;
}
}
else if(arc_r == 13 && arc_c == 0){
if((strcmp(Board[arc_r-1][arc_c], color2) == 0) || (strcmp(Board[arc_r][arc_c+1], color2) == 0)){
*roundedge = *roundedge + 1;
}
}
else if(arc_r == 0 && arc_c == 13){
if((strcmp(Board[arc_r+1][arc_c], color2) == 0) || (strcmp(Board[arc_r][arc_c-1], color2) == 0)){
*roundedge = *roundedge + 1;
}
}
else if(arc_r == 13 && arc_c == 13){
if((strcmp(Board[arc_r-1][arc_c], color2) == 0) || (strcmp(Board[arc_r][arc_c-1], color2) == 0)){
*roundedge = *roundedge + 1;
}
}
else if(arc_r == 0){
if((strcmp(Board[arc_r+1][arc_c], color2) == 0) || (strcmp(Board[arc_r][arc_c+1], color2) == 0)
|| (strcmp(Board[arc_r][arc_c-1], color2) == 0)){
*roundedge = *roundedge + 1;
}
}
else if(arc_r == 13){
if((strcmp(Board[arc_r-1][arc_c], color2) == 0) || (strcmp(Board[arc_r][arc_c+1], color2) == 0)
|| (strcmp(Board[arc_r][arc_c-1], color2) == 0)){
*roundedge = *roundedge + 1;
}
}
else if(arc_c == 0){
if((strcmp(Board[arc_r-1][arc_c], color2) == 0) || (strcmp(Board[arc_r+1][arc_c], color2) == 0)
|| (strcmp(Board[arc_r][arc_c], color2) == 0)){
*roundedge = *roundedge + 1;
}
}
else if(arc_c == 13){
if((strcmp(Board[arc_r+1][arc_c], color2) == 0) || (strcmp(Board[arc_r-1][arc_c], color2) == 0)
|| (strcmp(Board[arc_r][arc_c-1], color2) == 0)){
*roundedge = *roundedge + 1;
}
}
else{
if((strcmp(Board[arc_r-1][arc_c], color2) == 0) || (strcmp(Board[arc_r][arc_c+1], color2) == 0)
|| (strcmp(Board[arc_r][arc_c-1], color2) == 0) || (strcmp(Board[arc_r+1][arc_c], color2) == 0)){
*roundedge = *roundedge + 1;
}
}
}
void arcarea(char Board[ROW][COLUMN][20], int dest, int arc_r, int arc_c, int *area, String selfcolor, String oppcolor){
int i, j, k;
*area = 0;
if(dest == 3){
if((strcmp(Board[arc_r+1][arc_c], selfcolor) == 0) || (strcmp(Board[arc_r][arc_c-1], selfcolor) == 0)){
*area = 0;
}
else{
int column[14];
int breaknum = 0;
bool breaktrue;
for(i = arc_r; i < 14; i++){
breaktrue = false;
for(j = arc_c; j < 14; j++){
for(k = 0; k < breaknum; k++){
if(j == column[k]){
breaktrue = true;
break;
}
}
if(breaktrue){
break;
}
if(i == 13 && j == 13){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i][j-1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else if(i == 13){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i][j-1], selfcolor) == 0)
|| (strcmp(Board[i][j+1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else if(j == 13){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i+1][j], selfcolor) == 0)
|| (strcmp(Board[i][j-1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else{
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i+1][j], selfcolor) == 0)
|| (strcmp(Board[i][j-1], selfcolor) == 0) ||(strcmp(Board[i][j+1], selfcolor) == 0)
|| (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
}
}
}
}
else if(dest == 2){
if((strcmp(Board[arc_r+1][arc_c], selfcolor) == 0) || (strcmp(Board[arc_r][arc_c-1], selfcolor) == 0)){
*area = 0;
}
else{
int column[14];
int breaknum = 0;
bool breaktrue;
for(i = arc_r; i < 14; i++){
breaktrue = false;
for(j = arc_c; j >= 0; j--){
for(k = 0; k < breaknum; k++){
if(j == column[k]){
breaktrue = true;
break;
}
}
if(breaktrue){
break;
}
if(i == 13 && j == 0){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) ||(strcmp(Board[i][j+1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else if(i == 13){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i][j-1], selfcolor) == 0)
|| (strcmp(Board[i][j+1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else if(j == 0){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i+1][j], selfcolor) == 0)
|| (strcmp(Board[i][j+1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else{
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i+1][j], selfcolor) == 0)
|| (strcmp(Board[i][j-1], selfcolor) == 0) ||(strcmp(Board[i][j+1], selfcolor) == 0)
|| (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
}
}
}
}
else if(dest == 1){
if((strcmp(Board[arc_r-1][arc_c], selfcolor) == 0) || (strcmp(Board[arc_r][arc_c+1], selfcolor) == 0)){
*area = 0;
}
else{
int column[14];
int breaknum = 0;
bool breaktrue;
for(i = arc_r; i >= 0; i--){
breaktrue = false;
for(j = arc_c; j < 14; j++){
for(k = 0; k < breaknum; k++){
if(j == column[k]){
breaktrue = true;
break;
}
}
if(breaktrue){
break;
}
if(i == 0 && j == 13){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i+1][j], selfcolor) == 0) || (strcmp(Board[i][j-1], selfcolor) == 0)
|| (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else if(i == 0){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i+1][j], selfcolor) == 0) || (strcmp(Board[i][j-1], selfcolor) == 0)
||(strcmp(Board[i][j+1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else if(j == 13){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i+1][j], selfcolor) == 0)
|| (strcmp(Board[i][j-1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else{
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i+1][j], selfcolor) == 0)
|| (strcmp(Board[i][j-1], selfcolor) == 0) ||(strcmp(Board[i][j+1], selfcolor) == 0)
|| (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
}
}
}
}
if(dest == 0){
if((strcmp(Board[arc_r-1][arc_c], selfcolor) == 0) || (strcmp(Board[arc_r][arc_c-1], selfcolor) == 0)){
*area = 0;
}
else{
int column[14];
int breaknum = 0;
bool breaktrue;
for(i = arc_r; i >= 0; i--){
breaktrue = false;
for(j = arc_c; j >= 0; j--){
for(k = 0; k < breaknum; k++){
if(j == column[k]){
breaktrue = true;
break;
}
}
if(breaktrue){
break;
}
if(i == 0 && j == 0){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i+1][j], selfcolor) == 0) || (strcmp(Board[i][j+1], selfcolor) == 0)
|| (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else if(i == 0){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if( (strcmp(Board[i+1][j], selfcolor) == 0) || (strcmp(Board[i][j-1], selfcolor) == 0)
||(strcmp(Board[i][j+1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else if(j == 0){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i+1][j], selfcolor) == 0)
||(strcmp(Board[i][j+1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else{
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i+1][j], selfcolor) == 0)
|| (strcmp(Board[i][j-1], selfcolor) == 0) ||(strcmp(Board[i][j+1], selfcolor) == 0)
|| (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
}
}
}
}
}
void arcarea2(char Board[ROW][COLUMN][20], int dest, int arc_r, int arc_c, int *area, String selfcolor, String oppcolor){
int i, j, k;
int partarea = 0;
*area = 0;
if(dest == 0){
if((strcmp(Board[arc_r+1][arc_c], selfcolor) == 0) || (strcmp(Board[arc_r][arc_c+1], selfcolor) == 0)){
*area = 0;
}
else{
int column[14];
int breaknum = 0;
bool breaktrue;
for(i = arc_r; i < 14; i++){
breaktrue = false;
for(j = arc_c; j < 14; j++){
for(k = 0; k < breaknum; k++){
if(j == column[k]){
breaktrue = true;
break;
}
}
if(breaktrue){
break;
}
if(i == 13 && j == 13){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i][j-1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else if(i == 13){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i][j-1], selfcolor) == 0)
|| (strcmp(Board[i][j+1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else if(j == 13){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i+1][j], selfcolor) == 0)
|| (strcmp(Board[i][j-1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else{
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i+1][j], selfcolor) == 0)
|| (strcmp(Board[i][j-1], selfcolor) == 0) ||(strcmp(Board[i][j+1], selfcolor) == 0)
|| (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
}
}
}
}
else if(dest == 1){
if((strcmp(Board[arc_r+1][arc_c], selfcolor) == 0) || (strcmp(Board[arc_r][arc_c-1], selfcolor) == 0)){
*area = 0;
}
else{
int column[14];
int breaknum = 0;
bool breaktrue;
for(i = arc_r; i < 14; i++){
breaktrue = false;
for(j = arc_c; j >= 0; j--){
for(k = 0; k < breaknum; k++){
if(j == column[k]){
breaktrue = true;
break;
}
}
if(breaktrue){
break;
}
if(i == 13 && j == 0){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) ||(strcmp(Board[i][j+1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else if(i == 13){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i][j-1], selfcolor) == 0)
|| (strcmp(Board[i][j+1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else if(j == 0){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i+1][j], selfcolor) == 0)
|| (strcmp(Board[i][j+1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else{
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i+1][j], selfcolor) == 0)
|| (strcmp(Board[i][j-1], selfcolor) == 0) ||(strcmp(Board[i][j+1], selfcolor) == 0)
|| (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
}
}
}
}
else if(dest == 2){
if((strcmp(Board[arc_r-1][arc_c], selfcolor) == 0) || (strcmp(Board[arc_r][arc_c+1], selfcolor) == 0)){
*area = 0;
}
else{
int column[14];
int breaknum = 0;
bool breaktrue;
for(i = arc_r; i >= 0; i--){
breaktrue = false;
for(j = arc_c; j < 14; j++){
for(k = 0; k < breaknum; k++){
if(j == column[k]){
breaktrue = true;
break;
}
}
if(breaktrue){
break;
}
if(i == 0 && j == 13){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i+1][j], selfcolor) == 0) || (strcmp(Board[i][j-1], selfcolor) == 0)
|| (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else if(i == 0){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i+1][j], selfcolor) == 0) || (strcmp(Board[i][j-1], selfcolor) == 0)
||(strcmp(Board[i][j+1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else if(j == 13){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i+1][j], selfcolor) == 0)
|| (strcmp(Board[i][j-1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else{
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i+1][j], selfcolor) == 0)
|| (strcmp(Board[i][j-1], selfcolor) == 0) ||(strcmp(Board[i][j+1], selfcolor) == 0)
|| (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
}
}
}
}
else if(dest == 3){
if((strcmp(Board[arc_r-1][arc_c], selfcolor) == 0) || (strcmp(Board[arc_r][arc_c-1], selfcolor) == 0)){
*area = 0;
}
else{
int column[14];
int breaknum = 0;
bool breaktrue;
for(i = arc_r; i >= 0; i--){
breaktrue = false;
for(j = arc_c; j >= 0; j--){
for(k = 0; k < breaknum; k++){
if(j == column[k]){
breaktrue = true;
break;
}
}
if(breaktrue){
break;
}
if(i == 0 && j == 0){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i+1][j], selfcolor) == 0) || (strcmp(Board[i][j+1], selfcolor) == 0)
|| (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else if(i == 0){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if( (strcmp(Board[i+1][j], selfcolor) == 0) || (strcmp(Board[i][j-1], selfcolor) == 0)
||(strcmp(Board[i][j+1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else if(j == 0){
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i+1][j], selfcolor) == 0)
||(strcmp(Board[i][j+1], selfcolor) == 0) || (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
else{
if(strcmp(Board[i][j], selfcolor) == 0){
column[breaknum] = j;
breaknum++;
break;
}
else if((strcmp(Board[i-1][j], selfcolor) == 0) || (strcmp(Board[i+1][j], selfcolor) == 0)
|| (strcmp(Board[i][j-1], selfcolor) == 0) ||(strcmp(Board[i][j+1], selfcolor) == 0)
|| (strcmp(Board[i][j], oppcolor) == 0)){
}
else{
*area = *area + 1;
}
}
}
}
}
}
}
void arccombocount(char Board[ROW][COLUMN][20], char puzzle[PUZNUM][PUZRC][PUZRC][20], int *returncombo, int pattern[PUZNUM], String color, String color2, int arc_r, int arc_c, int *predicttime){
*predicttime = *predicttime + 1;
if(*predicttime == 2){
return;
}
int i, j, m, l, h, e, s, p;
int n;
int ini_r, ini_c, end_r, end_c;
bool notpass;
bool place_able;
int k[14] = {0};
int t[14] = {0};
int pattern_temp[PUZNUM];
char Board_temp[ROW][COLUMN][20];
char puzzle_temp[PUZNUM][PUZRC][PUZRC][20];
bool create;
bool elmin;
bool oppo;
bool isoppo = false;
int oppoarcnum;
int createnum;
int combonum;
int elmnum;
int oppedgenum;
int dest[8] = {0};
int dest1[8] = {0};
int dest2[8] = {0};
int opparc_r[8] = {0};
int opparc_c[8] = {0};
int elmarc_r[8] = {0};
int elmarc_c[8] = {0};
int createarc_r[8] = {0};
int createarc_c[8] = {0};
int comboarc_r[8] = {0};
int comboarc_c[8] = {0};
int predict_temp = *predicttime;
int roundedge;
int arccombo = 0;
int mostarccombo = 0;
/*for(m = 0; m < 21; m++){
printf("\n\n");
for(i = 0; i < 5; i++){
printf("\n");
for(j = 0; j < 5; j++){
printf("%s", puzzle[m][i][j]);
}
}
}*/
notpass = false;
for(m = 0; m < 21; m++){
if(pattern[m] == 1){
for(j = 0; j < 2; j++){
for(l = 0; l < 4; l++){
ini_end(puzzle[m], &ini_r, &ini_c, &end_r, &end_c, color);
int q = end_r - ini_r + 1;
int w = end_c - ini_c + 1;
for(h = -(q - 1); h < q; h++){
for(e = -(w - 1) ; e < w; e++){
place_able = false;
if((arc_r + h < 0) || (arc_c + e < 0) || (arc_r + h > 13) || (arc_c + e > 13)) {
}
else{
place_able = placeable(puzzle[m], Board, arc_r + h, arc_c + e, &ini_r, &end_r, &ini_c, &end_c, color);
notpass = notpass | place_able;
if(place_able){
arccombo++;
oppoarcnum = 0;
createnum = 0;
combonum = 0;
elmnum = 0;
oppedgenum = 0;
create = false;
elmin = false;
oppo = false;
roundedge = 0;
arcinfo(puzzle[m], Board, arc_r + h, arc_c + e, ini_r, end_r, ini_c, end_c, opparc_r, opparc_c, elmarc_r, elmarc_c,
createarc_r, createarc_c, &oppoarcnum, &elmnum, &createnum, &oppedgenum, &dest, &dest1, &dest2, &create, &elmin , &oppo, color, color2);
//printf("\ncrearenum = %d, elmnum = %d, opnum = %d\n", createnum, elmnum, oppoarcnum);
if(create){
for(s = 0; s < createnum; s++){
roundedge = 0;
arcroundedge(Board, createarc_r[s], createarc_c[s], &roundedge, color2);
if(roundedge != 0){
comboarc_r[combonum] = createarc_r[s];
comboarc_c[combonum] = createarc_c[s];
combonum++;
}
//printf("carc_r = %d, carc_c = %d, carea = %d\n", createarc_r[s], createarc_c[s], createarea);
}
}
if(combonum != 0){
for(n = 0; n < 14; n++){
for(s = 0; s < 14; s++){
strcpy(Board_temp[n][s], Board[n][s]);
}
}
for(n = 0; n < PUZNUM; n++){
pattern_temp[n] = pattern[n];
}
for(n = 0; n < PUZNUM; n++){
for(s = 0; s < PUZRC; s++){
for(p = 0; p < PUZRC; p++){
strcpy(puzzle_temp[n][s][p], puzzle[n][s][p]);
}
}
}
place(arc_r + h, arc_c + e, &ini_r, &end_r, &ini_c, &end_c, Board_temp, puzzle[m]);
pattern_temp[m] = 0;
for(n = 0; n < combonum; n++){
*predicttime = predict_temp;
arccombocount(Board_temp, puzzle_temp, &arccombo, pattern_temp, color, color2, comboarc_r[n], comboarc_c[n], predicttime);
}
}
}
}
}
}
rotate(puzzle[m]);
}
flip(puzzle[m]);
}
}
}
if(!notpass){
}
else{
*returncombo = *returncombo + arccombo;
}
}
void selfarea_1(char (*puzzle)[PUZRC][PUZRC][20], int *area, int ini_r, int ini_c, int end_r, int end_c, String color){
int i, j;
*area = 0;
for(i = ini_r; i < end_r + 1; i++){
for(j = ini_c; j < end_c + 1; j++){
if(strcmp((*puzzle)[i][j], color) == 0){
*area = *area + 1;
}
}
}
}
void selfarea_2(int *area, int ini_r, int ini_c, int end_r, int end_c){
*area = (end_r-ini_r+1)*(end_c-ini_c+1);
}
int main(int argc, char *argv[]){
int i, j, m, l, h, e, s, p, z;
int n;
int k[14] = {0};
int t[14] = {0};
char Board[ROW][COLUMN][20];
int pattern[PUZNUM];
char puzzle[PUZNUM][PUZRC][PUZRC][20];
String color;
String color2;
bool notpass;
if(strcmp(argv[1],"Red") == 0){
color = "R";
}
else{
color = "B";
}
if(strcmp(argv[1],"Red") == 0){
color2 = "B";
}
else{
color2 = "R";
}
String name1 = argv[2];
String name2 = argv[3];
String name3 = argv[4];
char temp[2];
int ini_r, ini_c, end_r, end_c;
bool place_able;
FILE *in1 = fopen(argv[2],"r");
FILE *in2 = fopen(argv[3],"r");
i = 0;
j = 0;
while(fgets(temp, sizeof(temp), in1) != NULL){
if(strcmp(temp, ",") == 0){
}
else if(strcmp(temp, "\n") == 0){
i++;
}
else{
strcpy(Board[i][j], temp);
j++;
if(j == 14){
j = 0;
}
}
}
construct(puzzle,color);
fseek(in2, -43L, SEEK_END);
i = 0;
while(fgets(temp, sizeof(temp), in2) != NULL){
if((strcmp(temp, "1") == 0) || (strcmp(temp, "0") == 0) ){
pattern[i] = atoi(temp);
i++;
}
if(i > 20){
break;
}
}
fclose(in1);
fclose(in2);
if(firstplace(Board, color)){
ini_end(puzzle[15], &ini_r, &ini_c, &end_r, &end_c, color);
if(strcmp(Board[9][9], color2) == 0){
place(4,4,&ini_r,&end_r,&ini_c,&end_c,Board,puzzle[15]);
}
else if(strcmp(Board[4][4], color2) == 0){
rotate(puzzle[15]);
rotate(puzzle[15]);
ini_end(puzzle[15], &ini_r, &ini_c, &end_r, &end_c, color);
place(7,7,&ini_r,&end_r,&ini_c,&end_c,Board,puzzle[15]);
}
else{
place(4,4,&ini_r,&end_r,&ini_c,&end_c,Board,puzzle[15]);
}
pattern[15] = 0;
}
else{
int pattern_temp[PUZNUM];
char Board_temp[ROW][COLUMN][20];
char puzzle_temp[PUZNUM][PUZRC][PUZRC][20];
bool create;
bool elmin;
bool oppo;
bool isoppo = false;
int oppoarcnum;
int createnum;
int elmnum;
int oppedgenum;
int combonum;
int dest[8] = {0};
int dest1[8] = {0};
int dest2[8] = {0};
int totalarea;
int totalcreatearea;
int totalelmarea;
int totaloppoarea;
int opparc_r[8] = {0};
int opparc_c[8] = {0};
int elmarc_r[8] = {0};
int elmarc_c[8] = {0};
int createarc_r[8] = {0};
int createarc_c[8] = {0};
int comboarc_r[8] = {0};
int comboarc_c[8] = {0};
int roundedge;
int mostoppedge = 0;
int mosttotalarea = -10000;
int mosttotaloppoarea = 0;
int mostselfarea1 = 0;
int moseselfarea2 = 0;
int mostarccombo = 0;
int mostoppedgeopp = 0;
int mosttotalareaopp = -10000;
int mostselfarea1opp = 0;
int moseselfarea2opp = 0;
int mostarccomboopp = 0;
int placepattern, placeflip, placerotate, place_r, place_c, placeini_r, placeini_c, placeend_r, placeend_c;
int predicttime = 0;
int predict_temp = predicttime;
int opparea;
int createarea;
int arccombo;
int elmarea;
int selfarea1;
int selfarea2;
notpass = false;
n = 0;
findarc(Board, k, t, &n, color);
for(m = 0; m < 21; m++){
if(pattern[m] == 1){
for(i = 0; i < n; i++){
for(j = 0; j < 2; j++){
for(l = 0; l < 4; l++){
ini_end(puzzle[m], &ini_r, &ini_c, &end_r, &end_c, color);
int q = end_r - ini_r + 1;
int w = end_c - ini_c + 1;
for(h = -(q - 1); h < q; h++){
for(e = -(w - 1) ; e < w; e++){
place_able = false;
if((k[i] + h < 0) || (t[i] + e < 0) || (k[i] + h > 13) || (t[i] + e > 13)) {
}
else{
place_able = placeable(puzzle[m], Board, k[i] + h, t[i] + e, &ini_r, &end_r, &ini_c, &end_c, color);
notpass = notpass | place_able;
if(place_able){
oppoarcnum = 0;
createnum = 0;
elmnum = 0;
oppedgenum = 0;
create = false;
elmin = false;
oppo = false;
totalcreatearea = 0;
totalelmarea = 0;
totaloppoarea = 0;
opparea = 0;
createarea = 0;
elmarea = 0;
totalarea = 0;
selfarea1 = 0;
selfarea2 = 0;
arccombo = 0;
combonum = 0;
arcinfo(puzzle[m], Board, k[i] + h, t[i] + e, ini_r, end_r, ini_c, end_c, opparc_r, opparc_c, elmarc_r, elmarc_c,
createarc_r, createarc_c, &oppoarcnum, &elmnum, &createnum, &oppedgenum, &dest, &dest1, &dest2, &create, &elmin , &oppo, color, color2);
//printf("\ncrearenum = %d, elmnum = %d, opnum = %d\n", createnum, elmnum, oppoarcnum);
selfarea_1(&puzzle[m], &selfarea1, ini_r, ini_c, end_r, end_c, color);
selfarea_2(&selfarea2, ini_r, ini_c, end_r, end_c);
if(create){
for(s = 0; s < createnum; s++){
roundedge = 0;
arcarea2(Board, dest[s], createarc_r[s], createarc_c[s], &createarea, color, color2);
arcroundedge(Board, createarc_r[s], createarc_c[s], &roundedge, color2);
if(roundedge != 0){
comboarc_r[combonum] = createarc_r[s];
comboarc_c[combonum] = createarc_c[s];
combonum++;
}
//printf("carc_r = %d, carc_c = %d, carea = %d\n", createarc_r[s], createarc_c[s], createarea);
totalcreatearea = createarea + totalcreatearea;
}
}
if(combonum != 0){
for(z = 0; z < 14; z++){
for(s = 0; s < 14; s++){
strcpy(Board_temp[z][s], Board[z][s]);
}
}
for(z = 0; z < PUZNUM; z++){
pattern_temp[z] = pattern[z];
}
for(z = 0; z < PUZNUM; z++){
for(s = 0; s < PUZRC; s++){
for(p = 0; p < PUZRC; p++){
strcpy(puzzle_temp[z][s][p], puzzle[z][s][p]);
}
}
}
place(k[i] + h, t[i] + e, &ini_r, &end_r, &ini_c, &end_c, Board_temp, puzzle[m]);
pattern_temp[m] = 0;
for(z = 0; z < combonum; z++){
predicttime = predict_temp;
arccombocount(Board_temp, puzzle_temp, &arccombo, pattern_temp, color, color2, comboarc_r[z], comboarc_c[z], &predicttime);
}
}
if(elmin){
for(s = 0; s < elmnum; s++){
arcarea(Board, dest1[s], elmarc_r[s], elmarc_c[s], &elmarea, color, color2);
//printf("earc_r = %d, earc_c = %d, earea = %d\n", elmarc_r[s], elmarc_c[s], elmarea);
totalelmarea = totalelmarea + elmarea;
}
}
if(oppo){
isoppo = true;
for(s = 0; s < oppoarcnum; s++){
arcarea(Board, dest2[s], opparc_r[s], opparc_c[s], &opparea, color2, color);
//printf("oarc_r = %d, oarc_c = %d, oarea = %d\n", opparc_r[s], opparc_c[s], opparea);
totaloppoarea = totaloppoarea + opparea;
}
totalarea = totaloppoarea + totalcreatearea - totalelmarea;
if(totaloppoarea > mosttotaloppoarea){
mosttotaloppoarea = totaloppoarea;
place_r = k[i] + h;
place_c = t[i] + e;
placeini_r = ini_r;
placeini_c = ini_c;
placeend_r = end_r;
placeend_c = end_c;
placepattern = m;
placeflip = j;
placerotate = l;
mostarccomboopp = arccombo;
moseselfarea2opp = selfarea2;
mostselfarea1opp = selfarea1;
mosttotalareaopp = totalarea;
mostoppedgeopp = oppedgenum;
}
else if(totaloppoarea == mosttotaloppoarea){
if(arccombo > mostarccomboopp){
mostarccomboopp = arccombo;
place_r = k[i] + h;
place_c = t[i] + e;
placeini_r = ini_r;
placeini_c = ini_c;
placeend_r = end_r;
placeend_c = end_c;
placepattern = m;
placeflip = j;
placerotate = l;
moseselfarea2opp = selfarea2;
mostselfarea1opp = selfarea1;
mosttotalareaopp = totalarea;
mostoppedgeopp = oppedgenum;
}
else if(arccombo == mostarccomboopp){
if(selfarea2 > moseselfarea2opp){
moseselfarea2opp = selfarea2;
place_r = k[i] + h;
place_c = t[i] + e;
placeini_r = ini_r;
placeini_c = ini_c;
placeend_r = end_r;
placeend_c = end_c;
placepattern = m;
placeflip = j;
placerotate = l;
mostselfarea1opp = selfarea1;
mosttotalareaopp = totalarea;
mostoppedgeopp = oppedgenum;
}
else if(selfarea2 == moseselfarea2opp){
if(selfarea1 > mostselfarea1opp){
mostselfarea1opp = selfarea1;
place_r = k[i] + h;
place_c = t[i] + e;
placeini_r = ini_r;
placeini_c = ini_c;
placeend_r = end_r;
placeend_c = end_c;
placepattern = m;
placeflip = j;
placerotate = l;
mosttotalareaopp = totalarea;
mostoppedgeopp = oppedgenum;
}
else if(selfarea1 == mostselfarea1opp){
if(totalarea > mosttotalareaopp){
mosttotalareaopp = totalarea;
place_r = k[i] + h;
place_c = t[i] + e;
placeini_r = ini_r;
placeini_c = ini_c;
placeend_r = end_r;
placeend_c = end_c;
placepattern = m;
placeflip = j;
placerotate = l;
mostoppedgeopp = oppedgenum;
}
else if(totalarea == mosttotalareaopp){
if(oppedgenum > mostoppedgeopp){
mostoppedgeopp = oppedgenum;
place_r = k[i] + h;
place_c = t[i] + e;
placeini_r = ini_r;
placeini_c = ini_c;
placeend_r = end_r;
placeend_c = end_c;
placepattern = m;
placeflip = j;
placerotate = l;
}
}
}
}
}
}
}
else if(!isoppo){
totalarea = createarea - elmarea;
if(selfarea2 > moseselfarea2){
moseselfarea2 = selfarea2;
place_r = k[i] + h;
place_c = t[i] + e;
placeini_r = ini_r;
placeini_c = ini_c;
placeend_r = end_r;
placeend_c = end_c;
placepattern = m;
placeflip = j;
placerotate = l;
mostselfarea1 = selfarea1;
mostarccombo = arccombo;
mostoppedge = oppedgenum;
mosttotalarea = totalarea;
}
else if(selfarea2 == moseselfarea2){
if(selfarea1 > mostselfarea1){
mostselfarea1 = selfarea1;
place_r = k[i] + h;
place_c = t[i] + e;
placeini_r = ini_r;
placeini_c = ini_c;
placeend_r = end_r;
placeend_c = end_c;
placepattern = m;
placeflip = j;
placerotate = l;
mostarccombo = arccombo;
mostoppedge = oppedgenum;
mosttotalarea = totalarea;
}
else if(selfarea1 == mostselfarea1){
if(arccombo > mostarccombo){
mostarccombo = arccombo;
place_r = k[i] + h;
place_c = t[i] + e;
placeini_r = ini_r;
placeini_c = ini_c;
placeend_r = end_r;
placeend_c = end_c;
placepattern = m;
placeflip = j;
placerotate = l;
mostoppedge = oppedgenum;
mosttotalarea = totalarea;
}
else if(arccombo == mostarccombo){
if(oppedgenum > mostoppedge){
mostoppedge = oppedgenum;
place_r = k[i] + h;
place_c = t[i] + e;
placeini_r = ini_r;
placeini_c = ini_c;
placeend_r = end_r;
placeend_c = end_c;
placepattern = m;
placeflip = j;
placerotate = l;
mosttotalarea = totalarea;
}
else if(oppedgenum == mostoppedge){
if(totalarea > mosttotalarea){
mosttotalarea = totalarea;
place_r = k[i] + h;
place_c = t[i] + e;
placeini_r = ini_r;
placeini_c = ini_c;
placeend_r = end_r;
placeend_c = end_c;
placepattern = m;
placeflip = j;
placerotate = l;
}
}
}
}
}
}
}
}
}
}
rotate(puzzle[m]);
}
flip(puzzle[m]);
}
}
}
}
if(!notpass){
return 1;
}
else{
for(i = 0; i < placeflip; i++){
flip(puzzle[placepattern]);
}
for(j = 0; j < placerotate; j++){
rotate(puzzle[placepattern]);
}
place(place_r, place_c, &placeini_r, &placeend_r, &placeini_c, &placeend_c, Board, puzzle[placepattern]);
pattern[placepattern] = 0;
}
}
FILE *out = fopen(argv[2], "w");
for(i = 0; i < 14; i++){
for(j = 0; j < 14; j++){
if(j == 13){
fprintf(out, "%s\n", Board[i][j]);
}
else{
fprintf(out, "%s,", Board[i][j]);
}
}
}
FILE *out2 = fopen(argv[3], "a");
char outpat[20];
for(i = 0; i < 21; i++){
sprintf(outpat, "%d", pattern[i]);
if(i == 0){
fprintf(out2, "\n[%s,", outpat);
}
else if(i == 20){
fprintf(out2, "%s]", outpat);
}
else{
fprintf(out2, "%s,", outpat);
}
}
fclose(out);
fclose(out2);
return 0;
}
|
the_stack_data/932659.c | #include <stdio.h>
int main()
{
float lado;
printf("Informe a medida de um dos lados do quadrado:\n");
scanf("%f", &lado); float quad = lado * lado;
printf("Resultado: %.1f\n", quad);
printf("Dobro: %.1f\n", quad * 2);
return(0);
}
|
the_stack_data/153268149.c | typedef int size_t;
typedef struct {
unsigned int lock;
} spinlock_t;
static unsigned char inb(unsigned short port) {
unsigned char v;
return v;
}
static unsigned char inb_p(unsigned short port) {
unsigned char v;
return v;
}
static unsigned short inw(unsigned short port) {
unsigned short v;
return v;
}
static unsigned short inw_p(unsigned short port)
{ unsigned short v;
return v;
}
static unsigned int inl(unsigned short port) {
unsigned int v;
return v;
}
static unsigned int inl_p(unsigned short port) {
unsigned int v;
return v;
}
void * memcpy(void * to, const void * from, size_t n){
int x;
return (void *) x;
}
/* extern */ void outb(unsigned char value, unsigned short port){}
/* extern */ void outb_p(unsigned char value, unsigned short port){}
/* extern */ void outw(unsigned short value, unsigned short port){}
/* extern */ void outw_p(unsigned short value, unsigned short port){}
/* extern */ void outl(unsigned int value, unsigned short port){}
/* extern */ void outl_p(unsigned int value, unsigned short port){}
/*extern */ void insb(unsigned short port, void * addr, unsigned long count){}
/*extern*/ void insw(unsigned short port, void * addr, unsigned long count){}
/*extern*/ void insl(unsigned short port, void * addr, unsigned long count){}
/*extern*/ void outsb(unsigned short port, void * addr, unsigned long count){}
/*extern*/ void outsw(unsigned short port, void * addr, unsigned long count){}
/*extern*/ void outsl(unsigned short port, void * addr, unsigned long count){}
typedef struct {int counter; } atomic_t;
/*extern*/ unsigned long jiffies_Rsmp_0da02d67;
typedef unsigned short umode_t;
typedef char __s8;
typedef unsigned char __u8;
typedef short __s16;
typedef unsigned short __u16;
typedef int __s32;
typedef unsigned int __u32;
typedef long long __s64;
typedef unsigned long long __u64;
typedef signed char s8;
typedef unsigned char u8;
typedef signed short s16;
typedef unsigned short u16;
typedef signed int s32;
typedef unsigned int u32;
typedef signed long long s64;
typedef unsigned long long u64;
typedef u32 dma_addr_t;
typedef unsigned char u_char;
typedef unsigned short u_short;
typedef unsigned int u_int;
typedef unsigned long u_long;
typedef unsigned char unchar;
typedef unsigned short ushort;
typedef unsigned int uint;
typedef unsigned long ulong;
typedef __u8 u_int8_t;
typedef __s8 int8_t;
typedef __u16 u_int16_t;
typedef __s16 int16_t;
typedef __u32 u_int32_t;
typedef __s32 int32_t;
typedef __u8 uint8_t;
typedef __u16 uint16_t;
typedef __u32 uint32_t;
typedef __u64 uint64_t;
typedef __u64 u_int64_t;
typedef __s64 int64_t;
// # 28 "tlan.h" 2
// # 76 "tlan.h"
typedef struct tlan_adapter_entry {
u16 vendorId;
u16 deviceId;
char *deviceLabel;
u32 flags;
u16 addrOfs;
} TLanAdapterEntry;
// # 135 "tlan.h"
typedef struct tlan_buffer_ref_tag {
u32 count;
u32 address;
} TLanBufferRef;
typedef struct tlan_list_tag {
u32 forward;
u16 cStat;
u16 frameSize;
TLanBufferRef buffer[10];
} TLanList;
struct list_head {
struct list_head *next, *prev;
};
struct timer_list {
struct list_head list;
unsigned long expires;
unsigned long data;
void (*function)(unsigned long);
};
typedef long time_t;
typedef long suseconds_t;
struct timeval {
time_t tv_sec;
suseconds_t tv_usec;
};
struct sk_buff_head {
struct sk_buff * next;
struct sk_buff * prev;
__u32 qlen;
spinlock_t lock;
};
// struct sk_buff;
struct sk_buff {
struct sk_buff * next;
struct sk_buff * prev;
struct sk_buff_head * list;
struct sock *sk;
struct timeval stamp;
struct net_device *dev;
union
{
struct tcphdr *th;
struct udphdr *uh;
struct icmphdr *icmph;
struct igmphdr *igmph;
struct iphdr *ipiph;
struct spxhdr *spxh;
unsigned char *raw;
} h;
union
{
struct iphdr *iph;
struct ipv6hdr *ipv6h;
struct arphdr *arph;
struct ipxhdr *ipxh;
unsigned char *raw;
} nh;
union
{
struct ethhdr *ethernet;
unsigned char *raw;
} mac;
struct dst_entry *dst;
char cb[48];
unsigned int len;
unsigned int data_len;
unsigned int csum;
unsigned char __unused,cloned, pkt_type,ip_summed;
__u32 priority;
atomic_t users;
unsigned short protocol;
unsigned short security;
unsigned int truesize;
unsigned char *head;
unsigned char *data;
unsigned char *tail;
unsigned char *end;
void (*destructor)(struct sk_buff *);
};
struct net_device_stats
{
unsigned long rx_packets;
unsigned long tx_packets;
unsigned long rx_bytes;
unsigned long tx_bytes;
unsigned long rx_errors;
unsigned long tx_errors;
unsigned long rx_dropped;
unsigned long tx_dropped;
unsigned long multicast;
unsigned long collisions;
unsigned long rx_length_errors;
unsigned long rx_over_errors;
unsigned long rx_crc_errors;
unsigned long rx_frame_errors;
unsigned long rx_fifo_errors;
unsigned long rx_missed_errors;
unsigned long tx_aborted_errors;
unsigned long tx_carrier_errors;
unsigned long tx_fifo_errors;
unsigned long tx_heartbeat_errors;
unsigned long tx_window_errors;
unsigned long rx_compressed;
unsigned long tx_compressed;
};
struct board {
char *deviceLabel;
u32 flags;
u16 addrOfs;
} board_info[] ;
typedef u8 TLanBuffer[1600];
struct tq_struct {
struct list_head list;
unsigned long sync;
void (*routine)(void *);
void *data;
};
struct dev_mc_list
{
struct dev_mc_list *next;
__u8 dmi_addr[8];
unsigned char dmi_addrlen;
int dmi_users;
int dmi_gusers;
};
struct net_device
{
char name[16];
unsigned long rmem_end;
unsigned long rmem_start;
unsigned long mem_end;
unsigned long mem_start;
unsigned long base_addr;
unsigned int irq;
unsigned char if_port;
unsigned char dma;
unsigned long state;
struct net_device *next;
/* int (*init)(struct net_device *dev1); */
struct net_device *next_sched;
int ifindex;
int iflink;
/* struct net_device_stats* (*get_stats)(struct net_device *dev2); */
/* struct iw_statistics* (*get_wireless_stats)(struct net_device *dev3); */
unsigned long trans_start;
unsigned long last_rx;
unsigned short flags;
unsigned short gflags;
unsigned mtu;
unsigned short type;
unsigned short hard_header_len;
void *priv;
struct net_device *master;
unsigned char broadcast[8];
unsigned char dev_addr[8];
unsigned char addr_len;
struct dev_mc_list *mc_list;
int mc_count;
int promiscuity;
int allmulti;
int watchdog_timeo;
struct timer_list watchdog_timer;
void *atalk_ptr;
void *ip_ptr;
void *dn_ptr;
void *ip6_ptr;
void *ec_ptr;
struct Qdisc *qdisc;
struct Qdisc *qdisc_sleeping;
struct Qdisc *qdisc_list;
struct Qdisc *qdisc_ingress;
unsigned long tx_queue_len;
spinlock_t xmit_lock;
int xmit_lock_owner;
spinlock_t queue_lock;
atomic_t refcnt;
int deadbeaf;
int features;
/* void (*uninit)(struct net_device *dev4); */
/* void (*destructor)(struct net_device *dev5); */
/* int (*open)(struct net_device *dev6); */
/* int (*stop)(struct net_device *dev7); */
/* int (*hard_start_xmit) (struct sk_buff *skb1, */
/* struct net_device *dev8); */
/* int (*hard_header) (struct sk_buff *skb2, */
/* struct net_device *dev9, */
/* unsigned short type, */
/* void *daddr, */
/* void *saddr, */
/* unsigned len); */
/* int (*rebuild_header)(struct sk_buff *skb3); */
/* void (*set_multicast_list)(struct net_device *dev10); */
/* int (*set_mac_address)(struct net_device *dev11,void *addr); */
/* int (*do_ioctl)(struct net_device *dev12,struct ifreq *ifr, int cmd); */
/* int (*set_config)(struct net_device *dev13,struct ifmap *map); */
/* int (*hard_header_cache)(struct neighbour *neigh, struct hh_cache *hh1); */
/* void (*header_cache_update)(struct hh_cache *hh2, */
/* struct net_device *dev14, */
/* unsigned char * haddr4); */
/* int (*change_mtu)(struct net_device *dev15, int new_mtu); */
/* void (*tx_timeout) (struct net_device *dev16); */
/* int (*hard_header_parse)(struct sk_buff *skb6, */
/* unsigned char *haddr9); */
/* int (*neigh_setup)(struct net_device *dev17, struct neigh_parms *); */
/* int (*accept_fastpath)(struct net_device *, struct dst_entry*); */
struct module *owner;
struct net_bridge_port *br_port;
};
typedef unsigned short sa_family_t;
struct sockaddr {
sa_family_t sa_family;
char sa_data[14];
};
struct pt_regs {
long ebx;
long ecx;
long edx;
long esi;
long edi;
long ebp;
long eax;
int xds;
int xes;
long orig_eax;
long eip;
int xcs;
long eflags;
long esp;
int xss;
};
struct ifmap
{
unsigned long mem_start;
unsigned long mem_end;
unsigned short base_addr;
unsigned char irq;
unsigned char dma;
unsigned char port;
};
struct ifreq
{
union
{
char ifrn_name[16];
} ifr_ifrn;
union {
struct sockaddr ifru_addr;
struct sockaddr ifru_dstaddr;
struct sockaddr ifru_broadaddr;
struct sockaddr ifru_netmask;
struct sockaddr ifru_hwaddr;
short ifru_flags;
int ifru_ivalue;
int ifru_mtu;
struct ifmap ifru_map;
char ifru_slave[16];
char ifru_newname[16];
char * ifru_data;
} ifr_ifru;
};
typedef struct list_head task_queue;
/* extern */ task_queue tq_timer_Rsmp_fa3e9acc, tq_immediate_Rsmp_0da0dcd1, tq_disk_Rsmp_5373dbb6;
/* extern */ void netif_start_queue(struct net_device *dev){ return; }
/* extern */ int netif_rx_Rsmp_4eecbd7e(struct sk_buff *skb){ int x; return x;}
/* extern */ void netif_stop_queue(struct net_device *dev) { return;}
/* extern */ void netif_wake_queue(struct net_device *dev) { return; }
/* extern */ int netif_queue_stopped(struct net_device *dev){ int res_; return res_; }
unsigned long virt_to_phys(void * address)
{
return ((unsigned long)(address)-((unsigned long)(0xC0000000)));
}
/*extern*/ int queue_task(struct tq_struct *bh_pointer, task_queue *bh_list) { int x; return x; }
/*extern*/void mark_bh(int nr){ return; }
enum {
TIMER_BH /* = 0 */,
TQUEUE_BH,
DIGI_BH,
SERIAL_BH,
RISCOM8_BH,
SPECIALIX_BH,
AURORA_BH,
ESP_BH,
SCSI_BH,
IMMEDIATE_BH,
CYCLADES_BH,
CM206_BH,
JS_BH,
MACSERIAL_BH,
ISICOM_BH
};
// # 170 "tlan.h"
typedef struct tlan_private_tag {
struct net_device *nextDevice;
void *dmaStorage;
u8 *padBuffer;
TLanList *rxList;
u8 *rxBuffer;
u32 rxHead;
u32 rxTail;
u32 rxEocCount;
TLanList *txList;
u8 *txBuffer;
u32 txHead;
u32 txInProgress;
u32 txTail;
u32 txBusyCount;
u32 phyOnline;
u32 timerSetAt;
u32 timerType;
struct timer_list timer;
struct net_device_stats stats;
struct board *adapter;
u32 adapterRev;
u32 aui;
u32 debug;
u32 duplex;
u32 phy[2];
u32 phyNum;
u32 speed;
u8 tlanRev;
u8 tlanFullDuplex;
char devName[8];
spinlock_t lock;
u8 link;
u8 is_eisa;
struct tq_struct tlan_tqueue;
u8 neg_be_verbose;
} TLanPrivateInfo;
// # 439 "tlan.h"
u8 TLan_DioRead8(u16 base_addr, u16 internal_addr)
{
outw(internal_addr, base_addr + 0x08);
return (inb((base_addr + 0x0C) + (internal_addr & 0x3)));
}
u16 TLan_DioRead16(u16 base_addr, u16 internal_addr)
{
outw(internal_addr, base_addr + 0x08);
return (inw((base_addr + 0x0C) + (internal_addr & 0x2)));
}
u32 TLan_DioRead32(u16 base_addr, u16 internal_addr)
{
outw(internal_addr, base_addr + 0x08);
return (inl(base_addr + 0x0C));
}
void TLan_DioWrite8(u16 base_addr, u16 internal_addr, u8 data)
{
outw(internal_addr, base_addr + 0x08);
outb(data, base_addr + 0x0C + (internal_addr & 0x3));
}
void TLan_DioWrite16(u16 base_addr, u16 internal_addr, u16 data)
{
outw(internal_addr, base_addr + 0x08);
outw(data, base_addr + 0x0C + (internal_addr & 0x2));
}
void TLan_DioWrite32(u16 base_addr, u16 internal_addr, u32 data)
{
outw(internal_addr, base_addr + 0x08);
outl(data, base_addr + 0x0C + (internal_addr & 0x2));
}
int capable(int cap)
{
int NONDET;
int res_;
switch(NONDET){
case 0 :
res_= 0;
break;
default:
res_=1;
break;
}
return res_;
}
u32 xor( u32 a, u32 b )
{
return ( ( a && ! b ) || ( ! a && b ) );
}
u32 TLan_HashFunc( u8 *a )
{
u32 hash;
/* hash = xor( ( ( (u8) a[0/8] ) & ( (u8) ( 1 << 0%8 ) ) ), xor( ( ( (u8) a[6/8] ) & ( (u8) ( 1 << 6%8 ) ) ), xor( ( ( (u8) a[12/8] ) & ( (u8) ( 1 << 12%8 ) ) ), xor( ( ( (u8) a[18/8] ) & ( (u8) ( 1 << 18%8 ) ) ), xor( ( ( (u8) a[24/8] ) & ( (u8) ( 1 << 24%8 ) ) ), xor( ( ( (u8) a[30/8] ) & ( (u8) ( 1 << 30%8 ) ) ), xor( ( ( (u8) a[36/8] ) & ( (u8) ( 1 << 36%8 ) ) ), ( ( (u8) a[42/8] ) & ( (u8) ( 1 << 42%8 ) ) ) ) ) ) ) ) ) ); */
/* hash |= xor( ( ( (u8) a[1/8] ) & ( (u8) ( 1 << 1%8 ) ) ), xor( ( ( (u8) a[7/8] ) & ( (u8) ( 1 << 7%8 ) ) ), xor( ( ( (u8) a[13/8] ) & ( (u8) ( 1 << 13%8 ) ) ), xor( ( ( (u8) a[19/8] ) & ( (u8) ( 1 << 19%8 ) ) ), xor( ( ( (u8) a[25/8] ) & ( (u8) ( 1 << 25%8 ) ) ), xor( ( ( (u8) a[31/8] ) & ( (u8) ( 1 << 31%8 ) ) ), xor( ( ( (u8) a[37/8] ) & ( (u8) ( 1 << 37%8 ) ) ), ( ( (u8) a[43/8] ) & ( (u8) ( 1 << 43%8 ) ) ) ) ) ) ) ) ) ) << 1; */
/* hash |= xor( ( ( (u8) a[2/8] ) & ( (u8) ( 1 << 2%8 ) ) ), xor( ( ( (u8) a[8/8] ) & ( (u8) ( 1 << 8%8 ) ) ), xor( ( ( (u8) a[14/8] ) & ( (u8) ( 1 << 14%8 ) ) ), xor( ( ( (u8) a[20/8] ) & ( (u8) ( 1 << 20%8 ) ) ), xor( ( ( (u8) a[26/8] ) & ( (u8) ( 1 << 26%8 ) ) ), xor( ( ( (u8) a[32/8] ) & ( (u8) ( 1 << 32%8 ) ) ), xor( ( ( (u8) a[38/8] ) & ( (u8) ( 1 << 38%8 ) ) ), ( ( (u8) a[44/8] ) & ( (u8) ( 1 << 44%8 ) ) ) ) ) ) ) ) ) ) << 2; */
/* hash |= xor( ( ( (u8) a[3/8] ) & ( (u8) ( 1 << 3%8 ) ) ), xor( ( ( (u8) a[9/8] ) & ( (u8) ( 1 << 9%8 ) ) ), xor( ( ( (u8) a[15/8] ) & ( (u8) ( 1 << 15%8 ) ) ), xor( ( ( (u8) a[21/8] ) & ( (u8) ( 1 << 21%8 ) ) ), xor( ( ( (u8) a[27/8] ) & ( (u8) ( 1 << 27%8 ) ) ), xor( ( ( (u8) a[33/8] ) & ( (u8) ( 1 << 33%8 ) ) ), xor( ( ( (u8) a[39/8] ) & ( (u8) ( 1 << 39%8 ) ) ), ( ( (u8) a[45/8] ) & ( (u8) ( 1 << 45%8 ) ) ) ) ) ) ) ) ) ) << 3; */
/* hash |= xor( ( ( (u8) a[4/8] ) & ( (u8) ( 1 << 4%8 ) ) ), xor( ( ( (u8) a[10/8] ) & ( (u8) ( 1 << 10%8 ) ) ), xor( ( ( (u8) a[16/8] ) & ( (u8) ( 1 << 16%8 ) ) ), xor( ( ( (u8) a[22/8] ) & ( (u8) ( 1 << 22%8 ) ) ), xor( ( ( (u8) a[28/8] ) & ( (u8) ( 1 << 28%8 ) ) ), xor( ( ( (u8) a[34/8] ) & ( (u8) ( 1 << 34%8 ) ) ), xor( ( ( (u8) a[40/8] ) & ( (u8) ( 1 << 40%8 ) ) ), ( ( (u8) a[46/8] ) & ( (u8) ( 1 << 46%8 ) ) ) ) ) ) ) ) ) ) << 4; */
/* hash |= xor( ( ( (u8) a[5/8] ) & ( (u8) ( 1 << 5%8 ) ) ), xor( ( ( (u8) a[11/8] ) & ( (u8) ( 1 << 11%8 ) ) ), xor( ( ( (u8) a[17/8] ) & ( (u8) ( 1 << 17%8 ) ) ), xor( ( ( (u8) a[23/8] ) & ( (u8) ( 1 << 23%8 ) ) ), xor( ( ( (u8) a[29/8] ) & ( (u8) ( 1 << 29%8 ) ) ), xor( ( ( (u8) a[35/8] ) & ( (u8) ( 1 << 35%8 ) ) ), xor( ( ( (u8) a[41/8] ) & ( (u8) ( 1 << 41%8 ) ) ), ( ( (u8) a[47/8] ) & ( (u8) ( 1 << 47%8 ) ) ) ) ) ) ) ) ) ) << 5; */
return hash;
}
// # 167 "mytlan.c" 2
typedef int (*__init_module_func_t)(void);
typedef void (*__cleanup_module_func_t)(void);
struct resource {
/*const*/ char *name;
unsigned long start, end;
unsigned long flags;
struct resource *parent, *sibling, *child;
};
struct resource_list {
struct resource_list *next;
struct resource *res;
struct pci_dev *dev;
};
/*extern*/ struct resource ioport_resource_Rsmp_865ebccd;
/*extern*/ struct resource iomem_resource_Rsmp_9efed5af;
/*extern*/ struct resource * __request_region_Rsmp_1a1a4f09(struct resource * reso,unsigned long start, unsigned long n, char *name){
struct resource * res;
return res;
}
/* extern */ void __release_region_Rsmp_d49501d4(struct resource * reso, unsigned long p1, unsigned long p2){}
enum pci_mmap_state {
pci_mmap_io,
pci_mmap_mem
};
struct pci_dev {
struct list_head global_list;
struct list_head bus_list;
struct pci_bus *bus;
struct pci_bus *subordinate;
void *sysdata;
struct proc_dir_entry *procent;
unsigned int devfn;
unsigned short vendor;
unsigned short device;
unsigned short subsystem_vendor;
unsigned short subsystem_device;
unsigned int class;
u8 hdr_type;
u8 rom_base_reg;
struct pci_driver *driver;
void *driver_data;
dma_addr_t dma_mask;
u32 current_state;
unsigned short vendor_compatible[4];
unsigned short device_compatible[4];
unsigned int irq;
struct resource resource[12];
struct resource dma_resource[2];
struct resource irq_resource[2];
char name[80];
char slot_name[8];
int active;
int ro;
unsigned short regs;
/* int (*prepare)(struct pci_dev *dev1); */
/* int (*activate)(struct pci_dev *dev2); */
/* int (*deactivate)(struct pci_dev *dev3); */
};
struct pci_bus {
struct list_head node;
struct pci_bus *parent;
struct list_head children;
struct list_head devices;
struct pci_dev *self;
struct resource *resource[4];
struct pci_ops *ops;
void *sysdata;
struct proc_dir_entry *procdir;
unsigned char number;
unsigned char primary;
unsigned char secondary;
unsigned char subordinate;
char name[48];
unsigned short vendor;
unsigned short device;
unsigned int serial;
unsigned char pnpver;
unsigned char productver;
unsigned char checksum;
unsigned char pad1;
};
/* extern */ struct list_head pci_root_buses_Rsmp_082c3213;
/* extern */ struct list_head pci_devices_Rsmp_7a84b102;
struct pci_ops {
int read_byte;
int read_word;
int read_dword;
int write_byte;
int write_word;
int write_dword;
/* int (*read_byte)(struct pci_dev *, int , u8 *); */
/* int (*read_word)(struct pci_dev *, int , u16 *); */
/* int (*read_dword)(struct pci_dev *, int, u32 *); */
/* int (*write_byte)(struct pci_dev *, int , u8 ); */
/* int (*write_word)(struct pci_dev *, int , u16 ); */
/* int (*write_dword)(struct pci_dev *, int , u32 ); */
};
struct pbus_set_ranges_data
{
int found_vga;
unsigned long io_start, io_end;
unsigned long mem_start, mem_end;
};
struct pci_device_id {
unsigned int vendor, device;
unsigned int subvendor, subdevice;
unsigned int class, class_mask;
unsigned long driver_data;
};
struct pci_driver {
struct list_head node;
char *name;
struct pci_device_id *id_table;
/* int (*probe) (struct pci_dev *, struct pci_device_id *); */
/* void (*remove) (struct pci_dev *); */
/* int (*save_state) (struct pci_dev *, u32 ); */
/* int (*suspend)(struct pci_dev *, u32 ); */
/* int (*resume) (struct pci_dev *); */
/* int (*enable_wake) (struct pci_dev *, u32 , int ); */
};
/*extern*/ int pci_read_config_byte_Rsmp_e426c0e8(struct pci_dev *dev, int where, u8 *val){
int res__;
return res__;
}
/*extern*/ int pci_enable_device_Rsmp_d04fea08(struct pci_dev *dev){
int res__;
return res__;
}
/*extern*/ void pci_set_master_Rsmp_2d0760ae(struct pci_dev *dev){}
/*extern*/ int pci_register_driver_Rsmp_de7b2751(struct pci_driver * dev) {
int res__;
return res__;
}
/*extern*/ void pci_unregister_driver_Rsmp_836ea211(struct pci_driver * dev){}
/*extern*/ unsigned long pci_mem_start_Rsmp_3da171f9;
struct scatterlist {
char * address;
char * alt_address;
unsigned int length;
};
struct pci_dev;
static int pci_module_init(struct pci_driver *drv)
{
int rc;
rc = pci_register_driver_Rsmp_de7b2751 (drv);
if (rc > 0)
return 0;
if (rc == 0)
rc = -19;
pci_unregister_driver_Rsmp_836ea211 (drv);
return rc;
}
static void *pci_get_drvdata (struct pci_dev *pdev)
{
return pdev->driver_data;
}
static void pci_set_drvdata (struct pci_dev *pdev, void *data)
{
pdev->driver_data = data;
}
/* extern */ int pci_pci_problems_Rsmp_dc14eda7;
/* extern */ unsigned short eth_type_trans_Rsmp_ef9f8c35(struct sk_buff *skb,
struct net_device *dev){
unsigned short res__;
return res__;
}
/* extern */ unsigned long loops_per_jiffy_Rsmp_ba497f13;
struct mii_ioctl_data {
u16 phy_id;
u16 reg_num;
u16 val_in;
u16 val_out;
};
char tlan_banner[];
/* extern */ int printk_Rsmp_1b7d4074(const char * fmt, ...){
int res__;
return res__;
}
/* extern */ struct net_device *init_etherdev_Rsmp_5ef105a6(struct net_device *dev, int sizeof_priv){
struct net_device * res__;
return res__;
}
/* extern */ int mod_timer_Rsmp_1f13d309(struct timer_list *timer, unsigned long expires){
int res__;
return res__;
}
/* extern */ void udelay(unsigned long usecs) { return; }
/* extern */ void add_timer_Rsmp_a19eacf8(struct timer_list * timer){ return; }
/*extern*/ int del_timer_sync_Rsmp_daff266a(struct timer_list * timer){ int x; return x;}
/* extern */ void unregister_netdev_Rsmp_99639e9a(struct net_device *dev){ return; }
/* extern */ void kfree_Rsmp_037a0cba(const void * p){ return; }
/* extern */ void dev_kfree_skb_irq(struct sk_buff *skb){ return ;}
/* extern */ void dev_kfree_skb_any(struct sk_buff *skb){ return ;}
/* extern */ void * kmalloc_Rsmp_93d4cfe6(size_t ss, int pp){}
/* extern */ int request_irq_Rsmp_0c60f2e0(unsigned int aa,
void (*handler)(int, void *, struct pt_regs *),
unsigned long cc, const char * dd, void * ee) {
int res_;
return res_;
}
/* extern */ void free_irq_Rsmp_f20dabd8(unsigned int aa, void * bb){ return; }
void spin_lock(spinlock_t *lock) { return ; }
void spin_unlock(spinlock_t *lock){ return ; }
/*extern */ struct sk_buff *dev_alloc_skb(unsigned int length)
{
struct sk_buff * res__;
return res__;
}
/*extern*/ void skb_reserve(struct sk_buff *skb, unsigned int len)
{
skb->data+=len;
skb->tail+=len;
return;
}
unsigned char *skb_put(struct sk_buff *skb, unsigned int len)
{
unsigned char * res__;
return res__;
}
/*extern*/ void skb_trim(struct sk_buff *skb, unsigned int len){ return; }
/////////////////////////////////////////////////////////////////////////////////
// "mytlan.c"
/////////////////////////////////////////////////////////////////////////////////
/* Global variables */
int in_irq;
int BLAST_NONDET;
int lockStatus;
void errorFn() {
ERROR: goto ERROR;
}
void _BLAST_init() {
lockStatus = 0;
if(BLAST_NONDET) in_irq = 1;
else in_irq = 0;
}
void spin_lock_irqsave (void * a , void *b) {
if (lockStatus == 0) lockStatus = 1;
else errorFn();
}
void spin_unlock_irqrestore (void * a , void *b) {
if (lockStatus == 1) lockStatus = 0;
else errorFn();
}
typedef u32 (TLanIntVectorFunc)( struct net_device *, u16 );
static struct net_device *TLan_Eisa_Devices;
static int TLanDevicesInstalled;
static int aui[8];
static int duplex[8];
static int speed[8];
static int boards_found;
static int debug;
static int bbuf;
static u8 *TLanPadBuffer;
char TLanSignature[];
static int tlan_have_pci;
static int tlan_have_eisa;
/*const*/ char *media[] /* = { */
/* "10BaseT-HD ", "10BaseT-FD ","100baseTx-HD ", */
/* "100baseTx-FD", "100baseT4", 0 */
/* } */;
int media_map[]/* = { 0x0020, 0x0040, 0x0080, 0x0100, 0x0200,} */;
static struct pci_device_id tlan_pci_tbl[]/* = { */
/* { 0x0e11, 0xae34, */
/* (~0), (~0), 0, 0, 0 }, */
/* { 0x0e11, 0xae32, */
/* (~0), (~0), 0, 0, 1 }, */
/* { 0x0e11, 0xae35, */
/* (~0), (~0), 0, 0, 2 }, */
/* { 0x0e11, 0xf130, */
/* (~0), (~0), 0, 0, 3 }, */
/* { 0x0e11, 0xf150, */
/* (~0), (~0), 0, 0, 4 }, */
/* { 0x0e11, 0xae43, */
/* (~0), (~0), 0, 0, 5 }, */
/* { 0x0e11, 0xae40, */
/* (~0), (~0), 0, 0, 6 }, */
/* { 0x0e11, 0xb011, */
/* (~0), (~0), 0, 0, 7 }, */
/* { 0x108d, 0x0013, */
/* (~0), (~0), 0, 0, 8 }, */
/* { 0x108d, 0x0012, */
/* (~0), (~0), 0, 0, 9 }, */
/* { 0x108d, 0x0014, */
/* (~0), (~0), 0, 0, 10 }, */
/* { 0x0e11, 0xB030, */
/* (~0), (~0), 0, 0, 11 }, */
/* { 0x0e11, 0xB012, */
/* (~0), (~0), 0, 0, 12 }, */
/* { 0,} */
/* } */;
/* Prototypes of functions called from main */
static int TLan_Init( struct net_device * );
static int TLan_Open( struct net_device *dev );
static void TLan_EisaProbe( void );
static void TLan_Eisa_Cleanup( void );
static int TLan_StartTx( struct sk_buff *, struct net_device *);
static int TLan_ioctl( struct net_device *dev, struct ifreq *rq, int cmd);
static struct net_device_stats *TLan_GetStats( struct net_device *);
static int TLan_Close( struct net_device *);
static void TLan_HandleInterrupt( int, void *, struct pt_regs *);
static int TLan_probe1( struct pci_dev *pdev, long ioaddr, int irq, int rev, struct pci_device_id *ent);
static void TLan_tx_timeout( struct net_device *dev);
static int tlan_init_one( struct pci_dev *pdev, struct pci_device_id *ent);
static void TLan_ResetLists( struct net_device * );
static void TLan_ResetAdapter( struct net_device * );
static void TLan_ReadAndClearStats( struct net_device *, int );
static int TLan_MiiReadReg( struct net_device *, u16, u16, u16 * );
static void TLan_MiiWriteReg( struct net_device *, u16, u16, u16 );
static void TLan_FreeLists( struct net_device * );
static void TLan_PrintList( TLanList *, char *, int );
static void TLan_PrintDio( u16 );
static void TLan_PhyPrint( struct net_device * );
static void TLan_SetMulticastList( struct net_device *);
static u32 TLan_HandleInvalid( struct net_device *, u16 );
static u32 TLan_HandleTxEOF( struct net_device *, u16 );
static u32 TLan_HandleStatOverflow( struct net_device *, u16 );
static u32 TLan_HandleRxEOF( struct net_device *, u16 );
static u32 TLan_HandleDummy( struct net_device *, u16 );
static u32 TLan_HandleTxEOC( struct net_device *, u16 );
static u32 TLan_HandleStatusCheck( struct net_device *, u16 );
static u32 TLan_HandleRxEOC( struct net_device *, u16 );
static void TLan_Timer( unsigned long );
static void TLan_FinishReset( struct net_device * );
static void TLan_SetMac( struct net_device *, int areg, char *mac );
static void TLan_PhyDetect( struct net_device * );
static void TLan_PhyPowerDown( struct net_device * );
static void TLan_PhyPowerUp( struct net_device * );
static void TLan_PhyReset( struct net_device * );
static void TLan_PhyStartLink( struct net_device * );
static void TLan_PhyFinishAutoNeg( struct net_device * );
static void TLan_MiiSendData( u16, u32, unsigned );
static void TLan_MiiSync( u16 );
static void TLan_EeSendStart( u16 );
static int TLan_EeSendByte( u16, u8, int );
static void TLan_EeReceiveByte( u16, u8 *, int );
static int TLan_EeReadByte( struct net_device *, u8, u8 * );
static TLanIntVectorFunc *TLanIntVector[8]/* = { */
/* TLan_HandleInvalid, */
/* TLan_HandleTxEOF, */
/* TLan_HandleStatOverflow, */
/* TLan_HandleRxEOF, */
/* TLan_HandleDummy, */
/* TLan_HandleTxEOC, */
/* TLan_HandleStatusCheck, */
/* TLan_HandleRxEOC */
/* } */;
static void TLan_SetTimer( struct net_device *dev, u32 ticks, u32 type )
{
TLanPrivateInfo *priv;
unsigned long flags;
priv = dev->priv;
flags = 0;
if (!in_irq){
//////////////////////////////////////////
spin_lock_irqsave(&priv->lock, flags);
/////////////////////////////////////////
}
if ( priv->timer.function != ((void *)0) && priv->timerType != 2 )
{
if (!in_irq){
//////////////////////////////////////////
spin_unlock_irqrestore(&priv->lock, flags);
//////////////////////////////////////////
}
return;
}
// TRACER priv->timer.function = &TLan_Timer;
if (!in_irq){
//////////////////////////////////////////
spin_unlock_irqrestore(&priv->lock, flags);
//////////////////////////////////////////
}
priv->timer.data = (unsigned long) dev;
priv->timerSetAt = jiffies_Rsmp_0da02d67;
priv->timerType = type;
mod_timer_Rsmp_1f13d309(&priv->timer, jiffies_Rsmp_0da02d67 + ticks);
}
static void tlan_remove_one( struct pci_dev *pdev)
{
struct net_device *dev;
TLanPrivateInfo *priv;
dev = pci_get_drvdata( pdev );
priv = dev->priv;
unregister_netdev_Rsmp_99639e9a( dev );
if ( priv->dmaStorage )
kfree_Rsmp_037a0cba( priv->dmaStorage );
__release_region_Rsmp_d49501d4(&ioport_resource_Rsmp_865ebccd, (dev->base_addr), (0x10));
kfree_Rsmp_037a0cba( dev );
pci_set_drvdata( pdev, ((void *)0) );
return;
}
static struct pci_driver tlan_driver/* = { */
/* name : "tlan" , */
/* id_table : tlan_pci_tbl , */
/* probe: tlan_init_one, */
/* remove : tlan_remove_one, */
/* } */;
/*extern*/ void * __constant_c_and_count_memset(void * s, unsigned long pattern, size_t count){}
/*extern*/ void * __constant_c_memset(void * s, unsigned long c, size_t count){}
/*extern*/ void * __memset_generic(void * s, char c,size_t count){}
/*extern*/ int __builtin_constant_p(int c){
int res__;
return res__;
}
void init_timer(struct timer_list * timer){ return;}
static int tlan_probe(void)
{
static int pad_allocated;
int temp_1,temp_2,temp_3,temp_4;
printk_Rsmp_1b7d4074("<6>" "%s", tlan_banner);
TLanPadBuffer = (u8 *) kmalloc_Rsmp_93d4cfe6(64,(0x20 | 0x10 | 0x40 | 0x80));
if (TLanPadBuffer == ((void *)0)) {
printk_Rsmp_1b7d4074("<3>" "TLAN: Could not allocate memory for pad buffer.\n");
return -12;
}
temp_1 = __builtin_constant_p(0);
if(temp_1){
temp_2 = __builtin_constant_p(64);
if(temp_2)
__constant_c_and_count_memset((TLanPadBuffer),0x01010101UL*(unsigned char)0,64);
else
__constant_c_memset((TLanPadBuffer),0x01010101UL*(unsigned char)0,64);
}
else{
temp_3 = __builtin_constant_p(64);
if(temp_3)
__memset_generic((TLanPadBuffer),0,64);
else
__memset_generic((TLanPadBuffer),0,64);
}
pad_allocated = 1;
if (debug&0x0010)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "Starting PCI Probe....\n" );
pci_module_init(&tlan_driver);
if (debug&0x0010)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "Starting EISA Probe....\n" );
TLan_EisaProbe();
printk_Rsmp_1b7d4074("<6>" "TLAN: %d device%s installed, PCI: %d EISA: %d\n",
TLanDevicesInstalled, TLanDevicesInstalled == 1 ? "" : "s",
tlan_have_pci, tlan_have_eisa);
if (TLanDevicesInstalled == 0) {
kfree_Rsmp_037a0cba(TLanPadBuffer);
return -19;
}
return 0;
}
static int tlan_init_one( struct pci_dev *pdev, struct pci_device_id *ent)
{
return TLan_probe1( pdev, -1, -1, 0, ent);
}
int TLan_probe1(struct pci_dev *pdev,long ioaddr, int irq, int rev,
struct pci_device_id *ent )
{
struct net_device *dev;
TLanPrivateInfo *priv;
u8 pci_rev;
u16 device_id;
int reg;
u32 pci_io_base;
int temp_1, temp_2;
temp_1 = pci_enable_device_Rsmp_d04fea08(pdev);
if (pdev && temp_1)
return -5;
dev = init_etherdev_Rsmp_5ef105a6(((void *)0), sizeof(TLanPrivateInfo));
if (dev == ((void *)0)) {
printk_Rsmp_1b7d4074("<3>" "TLAN: Could not allocate memory for device.\n");
return -12;
}
// TRACER do { (dev)->owner = (&__this_module); } while (0);
priv = dev->priv;
if (pdev)
{
pci_io_base = 0;
priv->adapter = &board_info[ent->driver_data];
pci_read_config_byte_Rsmp_e426c0e8 ( pdev, 0x08, &pci_rev);
//BLAST for loop for ( reg= 0; reg <= 5; reg ++ ) {
if (((pdev)->resource[(reg)].flags) & 0x00000100) {
pci_io_base = ((pdev)->resource[(reg)].start);
if (debug&0x0001)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "IO mapping is available at %x.\n", pci_io_base );
// break;
}
// }
if (!pci_io_base)
{
printk_Rsmp_1b7d4074("<3>" "TLAN: No IO mappings available\n");
unregister_netdev_Rsmp_99639e9a(dev);
kfree_Rsmp_037a0cba(dev);
return -19;
}
dev->base_addr = pci_io_base;
dev->irq = pdev->irq;
priv->adapterRev = pci_rev;
pci_set_master_Rsmp_2d0760ae(pdev);
pci_set_drvdata(pdev, dev);
}
else
{
device_id = inw(ioaddr + 0xc82);
priv->is_eisa = 1;
if (device_id == 0x20F1) {
priv->adapter = &board_info[13];
priv->adapterRev = 23;
} else {
priv->adapter = &board_info[14];
priv->adapterRev = 10;
}
dev->base_addr = ioaddr;
dev->irq = irq;
}
if (dev->mem_start)
{
priv->aui = dev->mem_start & 0x01;
/* TRACER priv->duplex = ((dev->mem_start & 0x06) == 0x06) ? 0 : (dev->mem_start & 0x06) >> 1; */
/* priv->speed = ((dev->mem_start & 0x18) == 0x18) ? 0 : (dev->mem_start & 0x18) >> 3; */
if (priv->speed == 0x1) {
priv->speed = 10;
} else if (priv->speed == 0x2) {
priv->speed = 100;
}
debug = dev->mem_end;
priv->debug =dev->mem_end ;
}
else
{
priv->aui = aui[boards_found];
priv->speed = speed[boards_found];
priv->duplex = duplex[boards_found];
priv->debug = debug;
}
/* TRACER do { (&priv->tlan_tqueue.list)->next =
(&priv->tlan_tqueue.list); (&priv->tlan_tqueue.list)->prev =
(&priv->tlan_tqueue.list); } while (0); */
priv->tlan_tqueue.sync = 0;
// TRACER priv->tlan_tqueue.routine = (void *)(void*)TLan_tx_timeout;
priv->tlan_tqueue.data = dev;
/* TRACER do { *(&priv->lock) = (spinlock_t) { 1 }; } while(0); */
temp_2 = TLan_Init(dev);
if (temp_2)
{
printk_Rsmp_1b7d4074("<3>" "TLAN: Could not register device.\n");
unregister_netdev_Rsmp_99639e9a(dev);
kfree_Rsmp_037a0cba(dev);
return -11;
}
else
{
TLanDevicesInstalled++;
boards_found++;
if (pdev)
tlan_have_pci++;
else {
priv->nextDevice = TLan_Eisa_Devices;
TLan_Eisa_Devices = dev;
tlan_have_eisa++;
}
printk_Rsmp_1b7d4074("<6>" "TLAN: %s irq=%2d, io=%04x, %s, Rev. %d\n",
dev->name,
(int) dev->irq,
(int) dev->base_addr,
priv->adapter->deviceLabel,
priv->adapterRev);
return 0;
}
}
static void TLan_Eisa_Cleanup(void)
{
struct net_device *dev;
TLanPrivateInfo *priv;
while( tlan_have_eisa ) {
dev = TLan_Eisa_Devices;
priv = dev->priv;
if (priv->dmaStorage) {
kfree_Rsmp_037a0cba(priv->dmaStorage);
}
__release_region_Rsmp_d49501d4(&ioport_resource_Rsmp_865ebccd, (dev->base_addr), (0x10));
unregister_netdev_Rsmp_99639e9a( dev );
TLan_Eisa_Devices = priv->nextDevice;
kfree_Rsmp_037a0cba( dev );
tlan_have_eisa--;
}
}
static void tlan_exit(void)
{
if (tlan_have_pci)
pci_unregister_driver_Rsmp_836ea211(&tlan_driver);
if (tlan_have_eisa)
TLan_Eisa_Cleanup();
kfree_Rsmp_037a0cba( TLanPadBuffer );
return;
}
int init_module(void);
void cleanup_module(void);
static void TLan_EisaProbe (void)
{
long ioaddr;
int rc;
int irq;
u16 device_id;
struct resource * temp_1;
unsigned char temp_2,temp_3, temp_4;
rc = -19;
if (!(0)) {
if (debug&0x0010) printk_Rsmp_1b7d4074("<7>" "TLAN: " "No EISA bus present\n" );;
return;
}
//BLAST for loop for (ioaddr = 0x1000; ioaddr < 0x9000; ioaddr += 0x1000) {
if (debug&0x0010)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "EISA_ID 0x%4x: 0x%4x\n", (int) ioaddr + 0xC80, inw(ioaddr + 0xc80) );
if (debug&0x0010)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "EISA_ID 0x%4x: 0x%4x\n", (int) ioaddr + 0xC82, inw(ioaddr + 0xc82) );
if (debug&0x0010)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "Probing for EISA adapter at IO: 0x%4x : ", (int) ioaddr );
temp_1 = __request_region_Rsmp_1a1a4f09(&ioport_resource_Rsmp_865ebccd,
ioaddr, 0x10, TLanSignature);
if ( temp_1 == (void *)0)
goto out;
temp_2 = inw(ioaddr + 0xc80);
if (temp_2 != 0x110E) {
__release_region_Rsmp_d49501d4(&ioport_resource_Rsmp_865ebccd, (ioaddr), (0x10));
goto out;
}
device_id = inw(ioaddr + 0xc82);
if (device_id != 0x20F1 && device_id != 0x40F1) {
__release_region_Rsmp_d49501d4(&ioport_resource_Rsmp_865ebccd, (ioaddr), (0x10));
goto out;
}
temp_3 =inb(ioaddr + 0xc84);
if (temp_3 != 0x1) {
__release_region_Rsmp_d49501d4(&ioport_resource_Rsmp_865ebccd, (ioaddr), (0x10));
goto out2;
}
if (debug == 0x10)
printk_Rsmp_1b7d4074("Found one\n");
temp_4 = inb(ioaddr + 0xCC0);
switch (temp_4) {
case 0x10 :
irq=5;
break;
case 0x20:
irq=9;
break;
case 0x40:
irq=10;
break;
case 0x80:
irq=11;
break;
default:
goto out;
}
rc = TLan_probe1( ((void *)0), ioaddr, irq, 12, ((void *)0));
//BLAST continue;
out:
if (debug == 0x10)
printk_Rsmp_1b7d4074("None found\n");
//BLAST continue;
out2: if (debug == 0x10)
printk_Rsmp_1b7d4074("Card found but it is not enabled, skipping\n");
//BLAST continue;
//}
}
static int TLan_Init( struct net_device *dev )
{
int dma_size;
int err;
int i;
TLanPrivateInfo *priv;
int temp_1,temp_2,temp_3;
struct resource* temp_4;
priv = dev->priv;
if (!priv->is_eisa)
temp_4 = __request_region_Rsmp_1a1a4f09(&ioport_resource_Rsmp_865ebccd,
(dev->base_addr), 0x10, TLanSignature);
if (! temp_4) {
printk_Rsmp_1b7d4074("<3>" "TLAN: %s: IO port region 0x%lx size 0x%x in use.\n",
dev->name,
dev->base_addr,
0x10 );
return -5;
}
if ( bbuf )
dma_size = ( 32 + 64 ) * ( sizeof(TLanList) + 1600 );
else
dma_size = ( 32 + 64 ) * ( sizeof(TLanList) );
priv->dmaStorage = (void *) kmalloc_Rsmp_93d4cfe6(dma_size, (0x20 | 0x10 | 0x40 | 0x80) | 0x01);
if ( priv->dmaStorage == ((void *)0) ) {
printk_Rsmp_1b7d4074("<3>" "TLAN: Could not allocate lists and buffers for %s.\n",
dev->name );
__release_region_Rsmp_d49501d4(&ioport_resource_Rsmp_865ebccd, (dev->base_addr), (0x10));
return -12;
}
temp_1 = __builtin_constant_p(0);
if(temp_1){
temp_2 = __builtin_constant_p(dma_size);
if(temp_2)
__constant_c_and_count_memset(((priv->dmaStorage)),
((0x01010101UL*(unsigned char)(0))),((dma_size)));
else
__constant_c_memset(((priv->dmaStorage)),
((0x01010101UL*(unsigned char)(0))),((dma_size)));
}
else{
temp_3 = __builtin_constant_p(dma_size);
if(temp_3)
__memset_generic((((priv->dmaStorage))),(((0))),(((dma_size))));
else
__memset_generic(((priv->dmaStorage)),((0)),((dma_size)));
}
priv->rxList = (TLanList *) ( ( ( (u32) priv->dmaStorage ) + 7 ) & 0xFFFFFFF8 );
priv->txList = priv->rxList + 32;
if ( bbuf ) {
priv->rxBuffer = (u8 *) ( priv->txList + 64 );
priv->txBuffer = priv->rxBuffer + ( 32 * 1600 );
}
err = 0;
//BLAST for ( i = 0; i < 6 ; i++ )
/*BLAST
err |= TLan_EeReadByte( dev,
(u8) priv->adapter->addrOfs + i,
(u8 *) &dev->dev_addr[i] );
*/
if ( err ) {
printk_Rsmp_1b7d4074("<3>" "TLAN: %s: Error reading MAC from eeprom: %d\n",
dev->name,
err );
}
dev->addr_len = 6;
// TRACER dev->open = &TLan_Open;
// TRACER dev->hard_start_xmit = &TLan_StartTx;
// TRACER dev->stop = &TLan_Close;
// TRACER dev->get_stats = &TLan_GetStats;
// TRACER dev->set_multicast_list = &TLan_SetMulticastList;
// TRACER dev->do_ioctl = &TLan_ioctl;
// TRACER dev->tx_timeout = &TLan_tx_timeout;
dev->watchdog_timeo = (10*100);
return 0;
}
static int TLan_Open( struct net_device *dev )
{
TLanPrivateInfo *priv;
int err;
priv = dev->priv;
priv->tlanRev = TLan_DioRead8( dev->base_addr, 0x0C );
err = request_irq_Rsmp_0c60f2e0( dev->irq, TLan_HandleInterrupt, 0x04000000, TLanSignature, dev );
if ( err ) {
printk_Rsmp_1b7d4074("<3>" "TLAN: Cannot open %s because IRQ %d is already in use.\n", dev->name, dev->irq );
return err;
}
init_timer(&priv->timer);
netif_start_queue(dev);
TLan_ResetLists( dev );
TLan_ReadAndClearStats( dev, 0 );
/*
TLan_ResetAdapter( dev );
*/
if (debug&0x0001) printk_Rsmp_1b7d4074("<7>" "TLAN: " "%s: Opened. TLAN Chip Rev: %x\n", dev->name, priv->tlanRev );;
return 0;
}
static int TLan_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
TLanPrivateInfo *priv;
struct mii_ioctl_data *data;
u32 phy;
int temp_1;
priv = dev->priv;
data = (struct mii_ioctl_data *)&rq->ifr_ifru.ifru_data;
phy = priv->phy[priv->phyNum];
if (!priv->phyOnline)
return -11;
switch(cmd) {
case 0x8947:
case 0x89F0:
data->phy_id = phy;
case 0x8948:
case 0x89F1 /*0x89F0 +1*/:
TLan_MiiReadReg(dev, data->phy_id & 0x1f, data->reg_num & 0x1f, &data->val_out);
return 0;
case 0x8949:
case 0x89F2 /* 0x89F0 +2 */:
temp_1 = capable(12);
if (!temp_1)
return -1;
TLan_MiiWriteReg(dev, data->phy_id & 0x1f, data->reg_num & 0x1f, data->val_in);
return 0;
default:
return -95;
}
}
static void TLan_tx_timeout(struct net_device *dev)
{
if (debug&0x0001)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "%s: Transmit timed out.\n", dev->name );;
TLan_FreeLists( dev );
TLan_ResetLists( dev );
TLan_ReadAndClearStats( dev, 0 );
TLan_ResetAdapter( dev );
dev->trans_start = jiffies_Rsmp_0da02d67;
netif_wake_queue( dev );
}
static int TLan_StartTx( struct sk_buff *skb, struct net_device *dev )
{
TLanPrivateInfo *priv;
TLanList *tail_list;
u8 *tail_buffer;
int pad;
unsigned long flags;
priv = dev->priv;
if ( ! priv->phyOnline ) {
if (debug&0x0002)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "TRANSMIT: %s PHY is not ready\n", dev->name );
dev_kfree_skb_any(skb);
return 0;
}
tail_list = priv->txList + priv->txTail;
if ( tail_list->cStat != 0x8000 ) {
if (debug&0x0002)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "TRANSMIT: %s is busy (Head=%d Tail=%d)\n", dev->name, priv->txHead, priv->txTail );
netif_stop_queue(dev);
priv->txBusyCount++;
return 1;
}
tail_list->forward = 0;
if ( bbuf ) {
tail_buffer = priv->txBuffer + ( priv->txTail * 1600 );
memcpy( tail_buffer, skb->data, skb->len );
} else {
tail_list->buffer[0].address = virt_to_phys( skb->data );
tail_list->buffer[9].address = (u32) skb;
}
pad = 64 - skb->len;
if ( pad > 0 ) {
tail_list->frameSize = (u16) skb->len + pad;
tail_list->buffer[0].count = (u32) skb->len;
tail_list->buffer[1].count = 0x80000000 | (u32) pad;
tail_list->buffer[1].address = virt_to_phys( TLanPadBuffer );
} else {
tail_list->frameSize = (u16) skb->len;
tail_list->buffer[0].count = 0x80000000 | (u32) skb->len;
tail_list->buffer[1].count = 0;
tail_list->buffer[1].address = 0;
}
///////////////////////////////////////////////////////////////
spin_lock_irqsave(&priv->lock, flags);
///////////////////////////////////////////////////////////////
tail_list->cStat = 0x3000;
if ( ! priv->txInProgress ) {
priv->txInProgress = 1;
if (debug&0x0002)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "TRANSMIT: Starting TX on buffer %d\n", priv->txTail );;
outl( virt_to_phys( tail_list ), dev->base_addr + 0x04 );
outl( 0x80000000, dev->base_addr + 0x00 );
}
else {
if (debug&0x0002)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "TRANSMIT: Adding buffer %d to TX channel\n", priv->txTail );;
if ( priv->txTail == 0 ) {
( priv->txList + ( 64 - 1 ) )->forward = virt_to_phys( tail_list );
} else {
( priv->txList + ( priv->txTail - 1 ) )->forward = virt_to_phys( tail_list );
}
}
///////////////////////////////////////////////////////////////
spin_unlock_irqrestore(&priv->lock, flags);
///////////////////////////////////////////////////////////////
priv->txTail++;
if ( priv->txTail >= 64 ) priv->txTail = 0;
if ( bbuf ) dev_kfree_skb_any(skb);
dev->trans_start = jiffies_Rsmp_0da02d67;
return 0;
}
static void TLan_HandleInterrupt(int irq, void *dev_id, struct pt_regs *regs)
{
u32 ack;
struct net_device *dev;
u32 host_cmd;
u16 host_int;
int type;
TLanPrivateInfo *priv;
dev = dev_id;
priv = dev->priv;
/////////////////////////////////////////////////////////////
spin_lock(&priv->lock);
/////////////////////////////////////////////////////////////
host_int = inw( dev->base_addr + 0x0A );
outw( host_int, dev->base_addr + 0x0A );
type = ( host_int & 0x001C ) >> 2;
ack = TLanIntVector[type]( dev, host_int );
if ( ack ) {
host_cmd = 0x20000000 | ack | ( type << 18 );
outl( host_cmd, dev->base_addr + 0x00 );
}
/////////////////////////////////////////////////////////////
spin_unlock(&priv->lock);
/////////////////////////////////////////////////////////////
}
static int TLan_Close(struct net_device *dev)
{
TLanPrivateInfo *priv = dev->priv;
netif_stop_queue(dev);
priv->neg_be_verbose = 0;
TLan_ReadAndClearStats( dev, 1 );
outl( 0x00008000, dev->base_addr + 0x00 );
if ( priv->timer.function != ((void *)0) ) {
del_timer_sync_Rsmp_daff266a( &priv->timer );
priv->timer.function = ((void *)0);
}
free_irq_Rsmp_f20dabd8( dev->irq, dev );
TLan_FreeLists( dev );
if (debug&0x0001)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "Device %s closed.\n", dev->name );
return 0;
}
static struct net_device_stats *TLan_GetStats( struct net_device *dev )
{
TLanPrivateInfo *priv;
int i;
priv = dev->priv;
TLan_ReadAndClearStats( dev, 1 );
if (debug&0x0004)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "RECEIVE: %s EOC count = %d\n", dev->name, priv->rxEocCount );
if (debug&0x0002)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "TRANSMIT: %s Busy count = %d\n", dev->name, priv->txBusyCount );
if ( debug & 0x0001 ) {
TLan_PrintDio( dev->base_addr );
TLan_PhyPrint( dev );
}
if ( debug & 0x0008 ) {
//BLAST for loop for ( i = 0; i < 32; i++ )
TLan_PrintList( priv->rxList + i, "RX", i );
//BLAST for loop for ( i = 0; i < 64; i++ )
TLan_PrintList( priv->txList + i, "TX", i );
}
return ( &( (TLanPrivateInfo *) dev->priv )->stats );
}
static void TLan_SetMulticastList( struct net_device *dev )
{
struct dev_mc_list *dmi;
u32 hash1;
u32 hash2;
int i;
u32 offset;
u8 tmp;
dmi = dev->mc_list;
hash1 = 0;
hash2 = 0;
if ( dev->flags & 0x100 ) {
tmp = TLan_DioRead8( dev->base_addr, 0x00 );
TLan_DioWrite8( dev->base_addr, 0x00, tmp | 0x10 );
}
else {
tmp = TLan_DioRead8( dev->base_addr, 0x00 );
TLan_DioWrite8( dev->base_addr, 0x00, tmp /* & ~0x10 */ );
if ( dev->flags & 0x200 ) {
//BLAST for loop for ( i = 0; i < 3; i++ )
TLan_SetMac( dev, i + 1, ((void *)0) );
TLan_DioWrite32( dev->base_addr, 0x28, 0xFFFFFFFF );
TLan_DioWrite32( dev->base_addr, 0x2C, 0xFFFFFFFF );
}
else {
// TRACER for loop for ( i = 0; i < dev->mc_count; i++ )
{
if ( i < 3 ) {
TLan_SetMac( dev, i + 1, (char *) &dmi->dmi_addr );
} else {
offset = TLan_HashFunc( (u8 *) &dmi->dmi_addr );
if ( offset < 32 )
hash1 = hash1 | ( 1 << offset );
else
hash2 = hash2 | ( 1 << ( offset - 32 ) );
}
dmi = dmi->next;
}
//BLAST for loop for ( ; i < 3; i++ )
TLan_SetMac( dev, i + 1, ((void *)0) );
TLan_DioWrite32( dev->base_addr, 0x28, hash1 );
TLan_DioWrite32( dev->base_addr, 0x2C, hash2 );
}
}
return;
}
u32 TLan_HandleInvalid( struct net_device *dev, u16 host_int )
{
return 0;
}
u32 TLan_HandleTxEOF( struct net_device *dev, u16 host_int )
{
TLanPrivateInfo *priv;
int eoc;
TLanList *head_list;
u32 ack;
u16 tmpCStat;
int temp_1, temp_2, temp_4, temp_5;
priv = dev->priv;
eoc = 0;
ack = 0;
if (debug&0x0002)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "TRANSMIT: Handling TX EOF (Head=%d Tail=%d)\n", priv->txHead, priv->txTail );;
head_list = priv->txList + priv->txHead;
// TRACER while (((tmpCStat = head_list->cStat ) & 0x4000) && (ack < 255))
{
ack++;
if ( ! bbuf ) {
dev_kfree_skb_any( (struct sk_buff *) head_list->buffer[9].address );
head_list->buffer[9].address = 0;
}
temp_4 = tmpCStat & 0x0800;
if (temp_4)
eoc = 1;
priv->stats.tx_bytes += head_list->frameSize;
head_list->cStat = 0x8000;
netif_start_queue(dev);
priv->txHead++;
if ( priv->txHead >= 64 )
priv->txHead = 0;
head_list = priv->txList + priv->txHead;
}
if (!ack)
printk_Rsmp_1b7d4074("<6>" "TLAN: Received interrupt for uncompleted TX frame.\n");
if ( eoc ) {
temp_5 = debug&0x0002;
if (temp_5)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "TRANSMIT: Handling TX EOC (Head=%d Tail=%d)\n", priv->txHead, priv->txTail );
head_list = priv->txList + priv->txHead;
temp_1 = head_list->cStat & 0x3000 ;
if ( temp_1 == 0x3000 ) {
outl( virt_to_phys( head_list ), dev->base_addr + 0x04 );
ack = ack | 0x80000000;
}
else
priv->txInProgress = 0;
}
temp_2 = priv->adapter->flags & 0x00000008;
if (temp_2) {
TLan_DioWrite8( dev->base_addr, 0x44, 0x01 | 0x10 );
if ( priv->timer.function == ((void *)0) ) {
// TRACER priv->timer.function = &TLan_Timer;
priv->timer.data = (unsigned long) dev;
priv->timer.expires = jiffies_Rsmp_0da02d67 + (100/10);
priv->timerSetAt = jiffies_Rsmp_0da02d67;
priv->timerType = 2;
add_timer_Rsmp_a19eacf8(&priv->timer);
}
else if ( priv->timerType == 2 ) {
priv->timerSetAt = jiffies_Rsmp_0da02d67;
}
}
return ack;
}
u32 TLan_HandleStatOverflow( struct net_device *dev, u16 host_int )
{
TLan_ReadAndClearStats( dev, 1 );
return 1;
}
u32 TLan_HandleRxEOF( struct net_device *dev, u16 host_int )
{
TLanPrivateInfo *priv;
u32 ack;
int eoc;
u8 *head_buffer;
TLanList *head_list;
struct sk_buff *skb;
TLanList *tail_list;
void *t;
u32 frameSize;
u16 tmpCStat;
struct sk_buff *new_skb;
priv = dev->priv;
ack = 0;
eoc = 0;
if (debug&0x0004)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "RECEIVE: Handling RX EOF (Head=%d Tail=%d)\n", priv->rxHead, priv->rxTail );
head_list = priv->rxList + priv->rxHead;
tmpCStat = head_list->cStat;
while (((tmpCStat /* = head_list->cStat */) & 0x4000) && (ack < 255)) {
frameSize = head_list->frameSize;
ack++;
if (tmpCStat & 0x0800)
eoc = 1;
if (bbuf) {
skb = dev_alloc_skb(frameSize + 7);
if (skb == ((void *)0))
printk_Rsmp_1b7d4074("<6>" "TLAN: Couldn't allocate memory for received data.\n");
else
{
head_buffer = priv->rxBuffer + (priv->rxHead * 1600);
skb->dev = dev;
skb_reserve(skb, 2);
t = (void *) skb_put(skb, frameSize);
priv->stats.rx_bytes += head_list->frameSize;
memcpy( t, head_buffer, frameSize );
skb->protocol = eth_type_trans_Rsmp_ef9f8c35( skb, dev );
netif_rx_Rsmp_4eecbd7e( skb );
}
}
else
{
// struct sk_buff *new_skb;
new_skb = dev_alloc_skb( 1600 + 7 );
if ( new_skb != ((void *)0) ) {
skb = (struct sk_buff *) head_list->buffer[9].address;
skb_trim( skb, frameSize );
priv->stats.rx_bytes += frameSize;
skb->protocol = eth_type_trans_Rsmp_ef9f8c35( skb, dev );
netif_rx_Rsmp_4eecbd7e( skb );
new_skb->dev = dev;
skb_reserve( new_skb, 2 );
t = (void *) skb_put( new_skb, 1600 );
head_list->buffer[0].address = virt_to_phys( t );
head_list->buffer[8].address = (u32) t;
head_list->buffer[9].address = (u32) new_skb;
} else
printk_Rsmp_1b7d4074("<4>" "TLAN: Couldn't allocate memory for received data.\n" );
}
head_list->forward = 0;
head_list->cStat = 0;
tail_list = priv->rxList + priv->rxTail;
tail_list->forward = virt_to_phys( head_list );
priv->rxHead++;
if ( priv->rxHead >= 32 )
priv->rxHead = 0;
priv->rxTail++;
if ( priv->rxTail >= 32 )
priv->rxTail = 0;
head_list = priv->rxList + priv->rxHead;
// TRACER
tmpCStat = head_list->cStat;
} // end of while
if (!ack)
printk_Rsmp_1b7d4074("<6>" "TLAN: Received interrupt for uncompleted RX frame.\n");
if ( eoc ) {
if (debug&0x0004)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "RECEIVE: Handling RX EOC (Head=%d Tail=%d)\n", priv->rxHead, priv->rxTail );
head_list = priv->rxList + priv->rxHead;
outl( virt_to_phys( head_list ), dev->base_addr + 0x04 );
ack= ack | 0x80000000 | 0x00080000;
priv->rxEocCount++;
}
if ( priv->adapter->flags & 0x00000008 ) {
TLan_DioWrite8( dev->base_addr, 0x44, 0x01 | 0x10 );
if ( priv->timer.function == ((void *)0) ) {
// TRACER priv->timer.function = &TLan_Timer;
priv->timer.data = (unsigned long) dev;
priv->timer.expires = jiffies_Rsmp_0da02d67 + (100/10);
priv->timerSetAt = jiffies_Rsmp_0da02d67;
priv->timerType = 2;
add_timer_Rsmp_a19eacf8(&priv->timer);
} else if ( priv->timerType == 2 ) {
priv->timerSetAt = jiffies_Rsmp_0da02d67;
}
}
dev->last_rx = jiffies_Rsmp_0da02d67;
return ack;
}
u32 TLan_HandleDummy( struct net_device *dev, u16 host_int )
{
printk_Rsmp_1b7d4074( "TLAN: Test interrupt on %s.\n", dev->name );
return 1;
}
u32 TLan_HandleTxEOC( struct net_device *dev, u16 host_int )
{
TLanPrivateInfo *priv;
TLanList *head_list;
u32 ack;
priv = dev->priv;
ack = 1;
host_int = 0;
if ( priv->tlanRev < 0x30 ) {
if (debug&0x0002)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "TRANSMIT: Handling TX EOC (Head=%d Tail=%d) -- IRQ\n", priv->txHead, priv->txTail );
head_list = priv->txList + priv->txHead;
if ( ( head_list->cStat & 0x3000 ) == 0x3000 ) {
netif_stop_queue(dev);
outl( virt_to_phys( head_list ), dev->base_addr + 0x04 );
ack = ack | 0x80000000;
} else {
priv->txInProgress = 0;
}
}
return ack;
}
u32 TLan_HandleStatusCheck( struct net_device *dev, u16 host_int )
{
TLanPrivateInfo *priv;
u32 ack;
u32 error;
u8 net_sts;
u32 phy;
u16 tlphy_ctl;
u16 tlphy_sts;
priv = dev->priv;
ack = 1;
if ( host_int & 0x1FE0 ) {
netif_stop_queue( dev );
error = inl( dev->base_addr + 0x04 );
printk_Rsmp_1b7d4074( "TLAN: %s: Adaptor Error = 0x%x\n", dev->name, error );
TLan_ReadAndClearStats( dev, 1 );
outl( 0x00008000, dev->base_addr + 0x00 );
queue_task(&priv->tlan_tqueue, &tq_immediate_Rsmp_0da0dcd1);
mark_bh(IMMEDIATE_BH);
netif_wake_queue(dev);
ack = 0;
}
else
{
if (debug&0x0001)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "%s: Status Check\n", dev->name );
phy = priv->phy[priv->phyNum];
net_sts = TLan_DioRead8( dev->base_addr, 0x02 );
if ( net_sts ) {
TLan_DioWrite8( dev->base_addr, 0x02, net_sts );
if (debug&0x0001)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "%s: Net_Sts = %x\n", dev->name, (unsigned) net_sts );
}
if ( ( net_sts & 0x80 ) && ( priv->phyNum == 0 ) ) {
TLan_MiiReadReg( dev, phy, 0x12, &tlphy_sts );
TLan_MiiReadReg( dev, phy, 0x11, &tlphy_ctl );
if ( ! ( tlphy_sts & 0x2000 ) && ! ( tlphy_ctl & 0x4000 ) ) {
tlphy_ctl = tlphy_ctl | 0x4000;
TLan_MiiWriteReg( dev, phy, 0x11, tlphy_ctl);
}
else if ( ( tlphy_sts & 0x2000 ) && ( tlphy_ctl & 0x4000 ) ) {
// tlphy_ctl &= ~0x4000;
TLan_MiiWriteReg( dev, phy, 0x11, tlphy_ctl);
}
if (debug) TLan_PhyPrint( dev );
}
}
return ack;
}
u32 TLan_HandleRxEOC( struct net_device *dev, u16 host_int )
{
TLanPrivateInfo *priv;
TLanList *head_list;
u32 ack;
priv = dev->priv;
ack = 1;
if ( priv->tlanRev < 0x30 ) {
if (debug&0x0004)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "RECEIVE: Handling RX EOC (Head=%d Tail=%d) -- IRQ\n", priv->rxHead, priv->rxTail );
head_list = priv->rxList + priv->rxHead;
outl( virt_to_phys( head_list ), dev->base_addr + 0x04 );
ack = ack | 0x80000000 | 0x00080000;
priv->rxEocCount++;
}
return ack;
}
void TLan_Timer( unsigned long data )
{
struct net_device *dev;
TLanPrivateInfo *priv;
u32 elapsed;
unsigned long flags;
dev = (struct net_device *) data;
priv = dev->priv;
flags = 0;
priv->timer.function = ((void *)0);
switch ( priv->timerType ) {
case 3:
TLan_PhyPowerDown( dev );
break;
case 4:
TLan_PhyPowerUp( dev );
break;
case 5:
TLan_PhyReset( dev );
break;
case 6:
TLan_PhyStartLink( dev );
break;
case 7:
TLan_PhyFinishAutoNeg( dev );
break;
case 8:
TLan_FinishReset( dev );
break;
case 2:
///////////////////////////////////////////////////////////////
spin_lock_irqsave(&priv->lock, flags);
///////////////////////////////////////////////////////////////
if ( priv->timer.function == ((void *)0) ) {
elapsed = jiffies_Rsmp_0da02d67 - priv->timerSetAt;
if ( elapsed >= (100/10) ) {
TLan_DioWrite8( dev->base_addr, 0x44, 0x01 );
}
else {
priv->timer.function = &TLan_Timer;
priv->timer.expires = priv->timerSetAt + (100/10);
///////////////////////////////////////////////////////////////
spin_unlock_irqrestore(&priv->lock, flags);
///////////////////////////////////////////////////////////////
add_timer_Rsmp_a19eacf8( &priv->timer );
break;
}
}
///////////////////////////////////////////////////////////////
spin_unlock_irqrestore(&priv->lock, flags);
///////////////////////////////////////////////////////////////
break;
default:
break;
}
}
void TLan_ResetLists( struct net_device *dev )
{
TLanPrivateInfo *priv;
int i;
TLanList *list;
struct sk_buff *skb;
void *t;
priv = dev->priv;
t = ((void *)0);
priv->txHead = 0;
priv->txTail = 0;
//BLAST for loop for ( i = 0; i < 64; i++ ) {
list = priv->txList + i;
list->cStat = 0x8000;
if ( bbuf )
list->buffer[0].address = virt_to_phys( priv->txBuffer + ( i * 1600 ) );
else
list->buffer[0].address = 0;
list->buffer[2].count = 0;
list->buffer[2].address = 0;
list->buffer[9].address = 0;
//}
priv->rxHead = 0;
priv->rxTail = 32 - 1;
//BLAST for loop for ( i = 0; i < 32; i++ ) {
list = priv->rxList + i;
list->cStat = 0x3000;
list->frameSize = 1600;
list->buffer[0].count = 1600 | 0x80000000;
if ( bbuf )
list->buffer[0].address = virt_to_phys( priv->rxBuffer + ( i * 1600 ) );
else
{
skb = dev_alloc_skb( 1600 + 7 );
if ( skb == ((void *)0) )
printk_Rsmp_1b7d4074( "TLAN: Couldn't allocate memory for received data.\n" );
else
{
skb->dev = dev;
skb_reserve( skb, 2 );
t = (void *) skb_put( skb, 1600 );
}
list->buffer[0].address = virt_to_phys( t );
list->buffer[8].address = (u32) t;
list->buffer[9].address = (u32) skb;
}
list->buffer[1].count = 0;
list->buffer[1].address = 0;
if ( i < 32 - 1 )
list->forward = virt_to_phys( list + 1 );
else
list->forward = 0;
//}
return;
}
void TLan_FreeLists( struct net_device *dev )
{
TLanPrivateInfo *priv = dev->priv;
int i;
TLanList *list;
struct sk_buff *skb;
priv = dev->priv;
if ( ! bbuf ) {
//BLAST for loop for ( i = 0; i < 64; i++ ) {
list = priv->txList + i;
skb = (struct sk_buff *) list->buffer[9].address;
if ( skb ) {
dev_kfree_skb_any( skb );
list->buffer[9].address = 0;
}
//}
//BLAST for loop for ( i = 0; i < 32; i++ ) {
list = priv->rxList + i;
skb = (struct sk_buff *) list->buffer[9].address;
if ( skb ) {
dev_kfree_skb_any( skb );
list->buffer[9].address = 0;
}
//}
}
return;
}
void TLan_PrintDio( u16 io_base )
{
u32 data0, data1;
int i;
printk_Rsmp_1b7d4074( "TLAN: Contents of internal registers for io base 0x%04hx.\n", io_base );
printk_Rsmp_1b7d4074( "TLAN: Off. +0 +4\n" );
//BLAST for loop for ( i = 0; i < 0x4C; i+= 8 ) {
data0 = TLan_DioRead32( io_base, i );
data1 = TLan_DioRead32( io_base, i + 0x4 );
printk_Rsmp_1b7d4074( "TLAN: 0x%02x 0x%08x 0x%08x\n", i, data0, data1 );
//}
return;
}
void TLan_PrintList( TLanList *list, char *type, int num)
{
int i;
printk_Rsmp_1b7d4074( "TLAN: %s List %d at 0x%08x\n", type, num, (u32) list );
printk_Rsmp_1b7d4074( "TLAN: Forward = 0x%08x\n", list->forward );
printk_Rsmp_1b7d4074( "TLAN: CSTAT = 0x%04hx\n", list->cStat );
printk_Rsmp_1b7d4074( "TLAN: Frame Size = 0x%04hx\n", list->frameSize );
//BLAST for loop for ( i = 0; i < 2; i++ ) {
printk_Rsmp_1b7d4074( "TLAN: Buffer[%d].count, addr = 0x%08x, 0x%08x\n", i, list->buffer[i].count, list->buffer[i].address );
//}
return;
}
void TLan_ReadAndClearStats( struct net_device *dev, int record )
{
TLanPrivateInfo *priv;
u32 tx_good, tx_under;
u32 rx_good, rx_over;
u32 def_tx, crc, code;
u32 multi_col, single_col;
u32 excess_col, late_col, loss;
priv = dev->priv;
outw( 0x30, dev->base_addr + 0x08 );
tx_good = inb( dev->base_addr + 0x0C );
tx_good += inb( dev->base_addr + 0x0C + 1 ) << 8;
tx_good += inb( dev->base_addr + 0x0C + 2 ) << 16;
tx_under = inb( dev->base_addr + 0x0C + 3 );
outw( 0x34, dev->base_addr + 0x08 );
rx_good = inb( dev->base_addr + 0x0C );
rx_good += inb( dev->base_addr + 0x0C + 1 ) << 8;
rx_good += inb( dev->base_addr + 0x0C + 2 ) << 16;
rx_over = inb( dev->base_addr + 0x0C + 3 );
outw( 0x38, dev->base_addr + 0x08 );
def_tx = inb( dev->base_addr + 0x0C );
def_tx += inb( dev->base_addr + 0x0C + 1 ) << 8;
crc = inb( dev->base_addr + 0x0C + 2 );
code = inb( dev->base_addr + 0x0C + 3 );
outw( 0x3C, dev->base_addr + 0x08 );
multi_col = inb( dev->base_addr + 0x0C );
multi_col += inb( dev->base_addr + 0x0C + 1 ) << 8;
single_col = inb( dev->base_addr + 0x0C + 2 );
single_col += inb( dev->base_addr + 0x0C + 3 ) << 8;
outw( 0x40, dev->base_addr + 0x08 );
excess_col = inb( dev->base_addr + 0x0C );
late_col = inb( dev->base_addr + 0x0C + 1 );
loss = inb( dev->base_addr + 0x0C + 2 );
if ( record ) {
priv->stats.rx_packets += rx_good;
priv->stats.rx_errors += rx_over + crc + code;
priv->stats.tx_packets += tx_good;
priv->stats.tx_errors += tx_under + loss;
priv->stats.collisions += multi_col + single_col + excess_col + late_col;
priv->stats.rx_over_errors += rx_over;
priv->stats.rx_crc_errors += crc;
priv->stats.rx_frame_errors += code;
priv->stats.tx_aborted_errors += tx_under;
priv->stats.tx_carrier_errors += loss;
}
return;
}
void TLan_ResetAdapter( struct net_device *dev )
{
TLanPrivateInfo *priv;
int i;
u32 addr;
u32 data;
u8 data8;
priv = dev->priv;
priv->tlanFullDuplex = 0;
priv->phyOnline=0;
data = inl(dev->base_addr + 0x00);
data = data | 0x00008000;
outl(data, dev->base_addr + 0x00);
udelay(1000);
data = inl(dev->base_addr + 0x00);
data = data | 0x00000800;
outl(data, dev->base_addr + 0x00);
//BLAST for loop for ( i = 0x10; i <= 0x2C; i += 4 ) {
TLan_DioWrite32( dev->base_addr, (u16) i, 0 );
// }
data = 0x0400 | 0x0200 | 0x0080;
TLan_DioWrite16( dev->base_addr, 0x04, (u16) data );
outl( 0x00004000 | 0x3f, dev->base_addr + 0x00 );
outl( 0x00002000 | 0x9, dev->base_addr + 0x00 );
outw( 0x01, dev->base_addr + 0x08 );
addr = dev->base_addr + 0x0C + 0x01;
outb_p(inb_p(addr) | 0x08, addr);
if ( priv->tlanRev >= 0x30 ) {
data8 = 0x04 | 0x01;
TLan_DioWrite8( dev->base_addr, 0x48, data8 );
}
TLan_PhyDetect( dev );
data = 0x0400 | 0x0200;
if ( priv->adapter->flags & 0x00000002 ) {
data |= 0x2000;
if ( priv->aui == 1 ) {
TLan_DioWrite8( dev->base_addr, 0x43, 0x0a );
} else if ( priv->duplex == 2 ) {
TLan_DioWrite8( dev->base_addr, 0x43, 0x00 );
priv->tlanFullDuplex = 1;
} else
TLan_DioWrite8( dev->base_addr, 0x43, 0x08 );
}
if ( priv->phyNum == 0 ) data = data | 0x0080;
TLan_DioWrite16( dev->base_addr, 0x04, (u16) data );
if ( priv->adapter->flags & 0x00000001 )
TLan_FinishReset( dev );
else
TLan_PhyPowerDown( dev );
return;
}
void TLan_FinishReset( struct net_device *dev )
{
TLanPrivateInfo *priv = dev->priv;
u8 data;
u32 phy;
u8 sio;
u16 status;
u16 partner;
u16 tlphy_ctl;
u16 tlphy_par;
u16 tlphy_id1, tlphy_id2;
int i;
priv = dev->priv;
phy = priv->phy[priv->phyNum];
data = 0x80 | 0x40;
if ( priv->tlanFullDuplex ) {
data = data | 0x04;
}
TLan_DioWrite8( dev->base_addr, 0x00, data );
data = 0x10 | 0x20;
if ( priv->phyNum == 0 ) {
data = data | 0x80;
}
TLan_DioWrite8( dev->base_addr, 0x03, data );
TLan_DioWrite16( dev->base_addr, 0x46, ((1536)+7)/* &~7 */ );
TLan_MiiReadReg( dev, phy, 0x02, &tlphy_id1 );
TLan_MiiReadReg( dev, phy, 0x03, &tlphy_id2 );
if ( ( priv->adapter->flags & 0x00000001 ) || ( priv->aui ) ) {
status = 0x0004;
printk_Rsmp_1b7d4074( "TLAN: %s: Link forced.\n", dev->name );
}
else {
TLan_MiiReadReg( dev, phy, 0x01, &status );
udelay( 1000 );
TLan_MiiReadReg( dev, phy, 0x01, &status );
if ( (status & 0x0004) && (tlphy_id1 == 0x2000) && (tlphy_id2 == 0x5C01) )
{
TLan_MiiReadReg( dev, phy, 0x05, &partner );
TLan_MiiReadReg( dev, phy, 0x19, &tlphy_par );
printk_Rsmp_1b7d4074( "TLAN: %s: Link active with ", dev->name );
if (!(tlphy_par & 0x0400))
{
printk_Rsmp_1b7d4074( "forced 10%sMbps %s-Duplex\n",
tlphy_par & 0x0040 ? "" : "0",
tlphy_par & 0x0080 ? "Full" : "Half");
}
else {
printk_Rsmp_1b7d4074( "AutoNegotiation enabled, at 10%sMbps %s-Duplex\n",
tlphy_par & 0x0040 ? "" : "0",
tlphy_par & 0x0080 ? "Full" : "Half");
printk_Rsmp_1b7d4074("TLAN: Partner capability: ");
//BLAST for loop for (i = 5; i <= 10; i++)
if (partner & (1<<i))
printk_Rsmp_1b7d4074("%s", media[i-5]);
printk_Rsmp_1b7d4074("\n");
}
TLan_DioWrite8( dev->base_addr, 0x44, 0x01 );
} else if (status & 0x0004) {
printk_Rsmp_1b7d4074( "TLAN: %s: Link active\n", dev->name );
TLan_DioWrite8( dev->base_addr, 0x44, 0x01 );
}
}
if ( priv->phyNum == 0 ) {
TLan_MiiReadReg( dev, phy, 0x11, &tlphy_ctl );
tlphy_ctl = tlphy_ctl | 0x0002;
TLan_MiiWriteReg( dev, phy, 0x11, tlphy_ctl );
sio = TLan_DioRead8( dev->base_addr, 0x01 );
sio = sio | 0x80;
TLan_DioWrite8( dev->base_addr, 0x01, sio );
}
if ( status & 0x0004 ) {
TLan_SetMac( dev, 0, dev->dev_addr );
priv->phyOnline = 1;
outb( ( 0x00000400 >> 8 ), dev->base_addr + 0x00 + 1 );
if ( debug >= 1 && debug != 0x0010 ) {
outb( ( 0x00001000 >> 8 ), dev->base_addr + 0x00 + 1 );
}
outl( virt_to_phys( priv->rxList ), dev->base_addr + 0x04 );
outl( 0x80000000 | 0x00080000, dev->base_addr + 0x00 );
} else {
printk_Rsmp_1b7d4074( "TLAN: %s: Link inactive, will retry in 10 secs...\n", dev->name );
TLan_SetTimer( dev, (10*100), 8 );
return;
}
}
void TLan_SetMac( struct net_device *dev, int areg, char *mac )
{
int i;
areg *= 6;
if ( mac != ((void *)0) ) {
//BLAST for loop for ( i = 0; i < 6; i++ )
TLan_DioWrite8( dev->base_addr, 0x10 + areg + i, mac[i] );
} else {
//BLAST for loop for ( i = 0; i < 6; i++ )
TLan_DioWrite8( dev->base_addr, 0x10 + areg + i, 0 );
}
return;
}
void TLan_PhyPrint( struct net_device *dev )
{
TLanPrivateInfo *priv;
u16 i, data0, data1, data2, data3, phy;
priv = dev->priv;
phy = priv->phy[priv->phyNum];
if ( priv->adapter->flags & 0x00000001 ) {
printk_Rsmp_1b7d4074( "TLAN: Device %s, Unmanaged PHY.\n", dev->name );
} else if ( phy <= 0x1F ) {
printk_Rsmp_1b7d4074( "TLAN: Device %s, PHY 0x%02x.\n", dev->name, phy );
printk_Rsmp_1b7d4074( "TLAN: Off. +0 +1 +2 +3 \n" );
//BLAST for loop for ( i = 0; i < 0x20; i+= 4 ) {
printk_Rsmp_1b7d4074( "TLAN: 0x%02x", i );
TLan_MiiReadReg( dev, phy, i, &data0 );
printk_Rsmp_1b7d4074( " 0x%04hx", data0 );
TLan_MiiReadReg( dev, phy, i + 1, &data1 );
printk_Rsmp_1b7d4074( " 0x%04hx", data1 );
TLan_MiiReadReg( dev, phy, i + 2, &data2 );
printk_Rsmp_1b7d4074( " 0x%04hx", data2 );
TLan_MiiReadReg( dev, phy, i + 3, &data3 );
printk_Rsmp_1b7d4074( " 0x%04hx\n", data3 );
//}
}
else {
printk_Rsmp_1b7d4074( "TLAN: Device %s, Invalid PHY.\n", dev->name );
}
return;
}
void TLan_PhyDetect( struct net_device *dev )
{
TLanPrivateInfo *priv = dev->priv;
u16 control;
u16 hi;
u16 lo;
u32 phy;
priv = dev->priv;
if ( priv->adapter->flags & 0x00000001 ) {
priv->phyNum = 0xFFFF;
return;
}
TLan_MiiReadReg( dev, 0x1F, 0x02, &hi );
if ( hi != 0xFFFF )
priv->phy[0] = 0x1F;
else
priv->phy[0] = 0x20;
priv->phy[1] = 0x20;
//BLAST for loop for ( phy = 0; phy <= 0x1F; phy++ ) {
TLan_MiiReadReg( dev, phy, 0x00, &control );
TLan_MiiReadReg( dev, phy, 0x02, &hi );
TLan_MiiReadReg( dev, phy, 0x03, &lo );
if ( ( control != 0xFFFF ) || ( hi != 0xFFFF ) || ( lo != 0xFFFF ) ) {
if (debug&0x0001)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "PHY found at %02x %04x %04x %04x\n", phy, control, hi, lo );
if ( ( priv->phy[1] == 0x20 ) && ( phy != 0x1F ) ) {
priv->phy[1] = phy;
}
}
//}
if ( priv->phy[1] != 0x20 ) {
priv->phyNum = 1;
} else if ( priv->phy[0] != 0x20 ) {
priv->phyNum = 0;
} else
printk_Rsmp_1b7d4074( "TLAN: Cannot initialize device, no PHY was found!\n" );
}
void TLan_PhyPowerDown( struct net_device *dev )
{
TLanPrivateInfo *priv;
u16 value;
priv = dev->priv;
if (debug&0x0001)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "%s: Powering down PHY(s).\n", dev->name );
value = 0x0800 | 0x4000 | 0x0400;
TLan_MiiSync( dev->base_addr );
TLan_MiiWriteReg( dev, priv->phy[priv->phyNum], 0x00, value );
if ( ( priv->phyNum == 0 ) && ( priv->phy[1] != 0x20 ) && ( ! ( priv->adapter->flags & 0x00000004 ) ) ) {
TLan_MiiSync( dev->base_addr );
TLan_MiiWriteReg( dev, priv->phy[1], 0x00, value );
}
TLan_SetTimer( dev, (100/20), 4 );
return;
}
void TLan_PhyPowerUp( struct net_device *dev )
{
TLanPrivateInfo *priv;
u16 value;
priv = dev->priv;
if (debug&0x0001)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "%s: Powering up PHY.\n", dev->name );
TLan_MiiSync( dev->base_addr );
value = 0x4000;
TLan_MiiWriteReg( dev, priv->phy[priv->phyNum], 0x00, value );
TLan_MiiSync(dev->base_addr);
TLan_SetTimer( dev, (100/20), 5 );
}
void TLan_PhyReset( struct net_device *dev )
{
TLanPrivateInfo *priv;
u16 phy;
u16 value;
priv = dev->priv;
phy = priv->phy[priv->phyNum];
if (debug&0x0001)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "%s: Reseting PHY.\n", dev->name );
TLan_MiiSync( dev->base_addr );
value = 0x4000 | 0x8000;
TLan_MiiWriteReg( dev, phy, 0x00, value );
TLan_MiiReadReg( dev, phy, 0x00, &value );
// TRACER while ( value & 0x8000 ) {
TLan_MiiReadReg( dev, phy, 0x00, &value );
// }
TLan_SetTimer( dev, (100/20), 6 );
}
void TLan_PhyStartLink( struct net_device *dev )
{
TLanPrivateInfo *priv;
u16 ability;
u16 control;
u16 data;
u16 phy;
u16 status;
u16 tctl;
priv = dev->priv;
phy = priv->phy[priv->phyNum];
if (debug&0x0001)
printk_Rsmp_1b7d4074("<7>" "TLAN: " "%s: Trying to activate link.\n", dev->name );
TLan_MiiReadReg( dev, phy, 0x01, &status );
TLan_MiiReadReg( dev, phy, 0x01, &ability );
if ( ( status & 0x0008 ) && ( ! priv->aui ) ) {
ability = status >> 11;
if ( priv->speed == 10 && priv->duplex == 1) {
TLan_MiiWriteReg( dev, phy, 0x00, 0x0000);
} else if ( priv->speed == 10 && priv->duplex == 2) {
priv->tlanFullDuplex = 1;
TLan_MiiWriteReg( dev, phy, 0x00, 0x0100);
} else if ( priv->speed == 100 && priv->duplex == 1) {
TLan_MiiWriteReg( dev, phy, 0x00, 0x2000);
} else if ( priv->speed == 100 && priv->duplex == 2) {
priv->tlanFullDuplex = 1;
TLan_MiiWriteReg( dev, phy, 0x00, 0x2100);
} else
{
TLan_MiiWriteReg( dev, phy, 0x04, (ability << 5) | 1);
TLan_MiiWriteReg( dev, phy, 0x00, 0x1000 );
TLan_MiiWriteReg( dev, phy, 0x00, 0x1200 );
printk_Rsmp_1b7d4074( "TLAN: %s: Starting autonegotiation.\n", dev->name );
TLan_SetTimer( dev, (2*100), 7 );
return;
}
}
if ( ( priv->aui ) && ( priv->phyNum != 0 ) ) {
priv->phyNum = 0;
data = 0x0400 | 0x0200 | 0x0080;
TLan_DioWrite16( dev->base_addr, 0x04, data );
TLan_SetTimer( dev, (40*100/1000), 3 );
return;
} else if ( priv->phyNum == 0 ) {
TLan_MiiReadReg( dev, phy, 0x11, &tctl );
if ( priv->aui )
tctl = tctl | 0x2000;
else {
tctl = tctl & /* ~ */0x2000;
control = 0;
if ( priv->duplex == 2 ) {
control = control | 0x0100;
priv->tlanFullDuplex = 1;
}
if ( priv->speed == 100 ) control = control | 0x2000;
TLan_MiiWriteReg( dev, phy, 0x00, control );
}
TLan_MiiWriteReg( dev, phy, 0x11, tctl );
}
TLan_SetTimer( dev, (4*100), 8 );
}
void TLan_PhyFinishAutoNeg( struct net_device *dev )
{
TLanPrivateInfo *priv;
u16 an_adv;
u16 an_lpa;
u16 data;
u16 mode;
u16 phy;
u16 status;
priv = dev->priv;
phy = priv->phy[priv->phyNum];
TLan_MiiReadReg( dev, phy, 0x01, &status );
udelay( 1000 );
TLan_MiiReadReg( dev, phy, 0x01, &status );
if ( ! ( status & 0x0020 ) ) {
if (!priv->neg_be_verbose/* ++ */) {
priv->neg_be_verbose++;
printk_Rsmp_1b7d4074("<6>" "TLAN: Giving autonegotiation more time.\n");
printk_Rsmp_1b7d4074("<6>" "TLAN: Please check that your adapter has\n");
printk_Rsmp_1b7d4074("<6>" "TLAN: been properly connected to a HUB or Switch.\n");
printk_Rsmp_1b7d4074("<6>" "TLAN: Trying to establish link in the background...\n");
}
else{
priv->neg_be_verbose++;
}
TLan_SetTimer( dev, (8*100), 7 );
return;
}
printk_Rsmp_1b7d4074( "TLAN: %s: Autonegotiation complete.\n", dev->name );
TLan_MiiReadReg( dev, phy, 0x04, &an_adv );
TLan_MiiReadReg( dev, phy, 0x05, &an_lpa );
mode = an_adv & an_lpa & 0x03E0;
if ( mode & 0x0100 ) {
priv->tlanFullDuplex = 1;
} else if ( ! ( mode & 0x0080 ) && ( mode & 0x0040 ) ) {
priv->tlanFullDuplex = 1;
}
if ( ( ! ( mode & 0x0180 ) ) && ( priv->adapter->flags & 0x00000004 ) && ( priv->phyNum != 0 ) ) {
priv->phyNum = 0;
data = 0x0400 | 0x0200 | 0x0080;
TLan_DioWrite16( dev->base_addr, 0x04, data );
TLan_SetTimer( dev, (400*100/1000), 3 );
return;
}
if ( priv->phyNum == 0 ) {
if ( ( priv->duplex == 2 ) || ( an_adv & an_lpa & 0x0040 ) ) {
TLan_MiiWriteReg( dev, phy, 0x00, 0x1000 | 0x0100 );
printk_Rsmp_1b7d4074( "TLAN: Starting internal PHY with FULL-DUPLEX\n" );
} else {
TLan_MiiWriteReg( dev, phy, 0x00, 0x1000 );
printk_Rsmp_1b7d4074( "TLAN: Starting internal PHY with HALF-DUPLEX\n" );
}
}
TLan_SetTimer( dev, (100/10), 8 );
}
int TLan_MiiReadReg( struct net_device *dev, u16 phy, u16 reg, u16 *val )
{
u8 nack;
u16 sio, tmp;
u32 i;
int err;
int minten;
TLanPrivateInfo *priv;
unsigned long flags;
int temp_1;
priv = dev->priv;
flags = 0;
err = 0;
outw(0x01, dev->base_addr + 0x08);
sio = dev->base_addr + 0x0C + 0x01;
if (!in_irq){
///////////////////////////////////////////////////
spin_lock_irqsave(&priv->lock, flags);
///////////////////////////////////////////////////
}
TLan_MiiSync(dev->base_addr);
minten = ((int) (inb_p(sio) & 0x80));
if ( minten )
outb_p(inb_p(sio) & /* ~ */0x80, sio);
TLan_MiiSendData( dev->base_addr, 0x1, 2 );
TLan_MiiSendData( dev->base_addr, 0x2, 2 );
TLan_MiiSendData( dev->base_addr, phy, 5 );
TLan_MiiSendData( dev->base_addr, reg, 5 );
outb_p(inb_p(sio) & /* ~ */0x02, sio);
outb_p(inb_p(sio) & /* ~ */0x04, sio);
outb_p(inb_p(sio) | 0x04, sio);
outb_p(inb_p(sio) & /* ~ */0x04, sio);
nack = ((int) (inb_p(sio) & 0x01));
outb_p(inb_p(sio) | 0x04, sio);
if (nack) {
//BLAST for loopfor (i = 0; i < 16; i++) {
outb_p(inb_p(sio) & /*~*/0x04, sio);
outb_p(inb_p(sio) | 0x04, sio);
//}
tmp = 0xffff;
err = 1;
} else {
//BLAST for loop for (tmp = 0, i = 0x8000; i; i >>= 1) {
outb_p(inb_p(sio) & /*~*/0x04, sio);
temp_1 = inb_p(sio);
if (((int) (temp_1 & 0x01)))
tmp = tmp | i;
outb_p(inb_p(sio) | 0x04, sio);
//}
}
outb_p(inb_p(sio) & /*~*/0x04, sio);
outb_p(inb_p(sio) | 0x04, sio);
if ( minten )
outb_p(inb_p(sio) | 0x80, sio);
*val = tmp;
if (!in_irq){
///////////////////////////////////////////////////
spin_unlock_irqrestore(&priv->lock, flags);
///////////////////////////////////////////////////
}
return err;
}
void TLan_MiiSendData( u16 base_port, u32 data, unsigned num_bits )
{
u16 sio;
u32 i;
if ( num_bits == 0 )
return;
outw( 0x01, base_port + 0x08 );
sio = base_port + 0x0C + 0x01;
outb_p(inb_p(sio) | 0x02, sio);
//TRACER for ( i = ( 0x1 << ( num_bits - 1 ) ); i; i >>= 1 ) {
outb_p(inb_p(sio) & /*~*/0x04, sio);
(void) ((int) (inb_p(sio) & 0x04));
if ( data & i )
outb_p(inb_p(sio) | 0x01, sio);
else
outb_p(inb_p(sio) & /*~*/0x01, sio);
outb_p(inb_p(sio) | 0x04, sio);
(void) ((int) (inb_p(sio) & 0x04));
// }
}
void TLan_MiiSync( u16 base_port )
{
int i;
u16 sio;
outw( 0x01, base_port + 0x08 );
sio = base_port + 0x0C + 0x01;
outb_p(inb_p(sio) & /*~*/0x02, sio);
//BLAST for loop for ( i = 0; i < 32; i++ ) {
outb_p(inb_p(sio) & /*~*/0x04, sio);
outb_p(inb_p(sio) | 0x04, sio);
//}
}
void TLan_MiiWriteReg( struct net_device *dev, u16 phy, u16 reg, u16 val )
{
u16 sio;
int minten;
unsigned long flags = 0;
TLanPrivateInfo *priv = dev->priv;
flags = 0;
priv = dev->priv;
outw(0x01, dev->base_addr + 0x08);
sio = dev->base_addr + 0x0C + 0x01;
if (!in_irq){
/////////////////////////////////////////////////////
spin_lock_irqsave(&priv->lock, flags);
/////////////////////////////////////////////////////
}
TLan_MiiSync( dev->base_addr );
minten = ((int) (inb_p(sio) & 0x80));
if ( minten )
outb_p(inb_p(sio) & /*~*/0x80, sio);
TLan_MiiSendData( dev->base_addr, 0x1, 2 );
TLan_MiiSendData( dev->base_addr, 0x1, 2 );
TLan_MiiSendData( dev->base_addr, phy, 5 );
TLan_MiiSendData( dev->base_addr, reg, 5 );
TLan_MiiSendData( dev->base_addr, 0x2, 2 );
TLan_MiiSendData( dev->base_addr, val, 16 );
outb_p(inb_p(sio) & /*~*/0x04, sio);
outb_p(inb_p(sio) | 0x04, sio);
if ( minten )
outb_p(inb_p(sio) | 0x80, sio);
if (!in_irq){
/////////////////////////////////////////////////////
spin_unlock_irqrestore(&priv->lock, flags);
/////////////////////////////////////////////////////
}
}
void TLan_EeSendStart( u16 io_base )
{
u16 sio;
outw( 0x01, io_base + 0x08 );
sio = io_base + 0x0C + 0x01;
outb_p(inb_p(sio) | 0x40, sio);
outb_p(inb_p(sio) | 0x10, sio);
outb_p(inb_p(sio) | 0x20, sio);
outb_p(inb_p(sio) & /*~*/0x10, sio);
outb_p(inb_p(sio) & /*~*/0x40, sio);
}
int TLan_EeSendByte( u16 io_base, u8 data, int stop )
{
int err;
u8 place;
u16 sio;
outw( 0x01, io_base + 0x08 );
sio = io_base + 0x0C + 0x01;
//BLAST for loop for ( place = 0x80; place != 0; place >>= 1 ) {
if ( place & data )
outb_p(inb_p(sio) | 0x10, sio);
else
outb_p(inb_p(sio) & /*~*/0x10, sio);
outb_p(inb_p(sio) | 0x40, sio);
outb_p(inb_p(sio) & /*~*/0x40, sio);
//BLAST }
outb_p(inb_p(sio) & /*~*/0x20, sio);
outb_p(inb_p(sio) | 0x40, sio);
err = ((int) (inb_p(sio) & 0x10));
outb_p(inb_p(sio) & /*~*/0x40, sio);
outb_p(inb_p(sio) | 0x20, sio);
if ( ( ! err ) && stop ) {
outb_p(inb_p(sio) & /*~*/0x10, sio);
outb_p(inb_p(sio) | 0x40, sio);
outb_p(inb_p(sio) | 0x10, sio);
}
return ( err );
}
void TLan_EeReceiveByte( u16 io_base, u8 *data, int stop )
{
u8 place;
u16 sio;
int temp_1;
outw( 0x01, io_base + 0x08 );
sio = io_base + 0x0C + 0x01;
*data = 0;
outb_p(inb_p(sio) & /*~*/0x20, sio);
//BLAST for loop for ( place = 0x80; place; place >>= 1 ) {
outb_p(inb_p(sio) | 0x40, sio);
temp_1 = (int) (inb_p(sio));
if ( temp_1 & 0x10)
*data |= place;
outb_p(inb_p(sio) & /*~*/0x40, sio);
//}
outb_p(inb_p(sio) | 0x20, sio);
if ( ! stop ) {
outb_p(inb_p(sio) & /*~*/0x10, sio);
outb_p(inb_p(sio) | 0x40, sio);
outb_p(inb_p(sio) & /*~*/0x40, sio);
} else {
outb_p(inb_p(sio) | 0x10, sio);
outb_p(inb_p(sio) | 0x40, sio);
outb_p(inb_p(sio) & /*~*/0x40, sio);
outb_p(inb_p(sio) & /*~*/0x10, sio);
outb_p(inb_p(sio) | 0x40, sio);
outb_p(inb_p(sio) | 0x10, sio);
}
}
int TLan_EeReadByte( struct net_device *dev, u8 ee_addr, u8 *data )
{
int err;
TLanPrivateInfo *priv;
unsigned long flags;
int ret;
priv = dev->priv;
flags = 0;
ret=0;
/////////////////////////////////////////////
spin_lock_irqsave(&priv->lock, flags);
/////////////////////////////////////////////
TLan_EeSendStart( dev->base_addr );
err = TLan_EeSendByte( dev->base_addr, 0xA0, 0 );
if (err)
{
ret=1;
/////////////////////////////////////////////////
spin_unlock_irqrestore(&priv->lock, flags);
/////////////////////////////////////////////////
return ret;
}
err = TLan_EeSendByte( dev->base_addr, ee_addr, 0 );
if (err)
{
ret=2;
/////////////////////////////////////////////////
spin_unlock_irqrestore(&priv->lock, flags);
/////////////////////////////////////////////////
return ret;
}
TLan_EeSendStart( dev->base_addr );
err = TLan_EeSendByte( dev->base_addr, 0xA1, 0 );
if (err)
{
ret=3;
/////////////////////////////////////////////////
spin_unlock_irqrestore(&priv->lock, flags);
/////////////////////////////////////////////////
return ret;
}
TLan_EeReceiveByte( dev->base_addr, data, 1 );
/////////////////////////////////////////////////
spin_unlock_irqrestore(&priv->lock, flags);
/////////////////////////////////////////////////
return ret;
}
struct net_device *dev;
int main() {
struct sk_buff *skb;
int cmd;
struct ifreq *rq;
_BLAST_init();
TLan_Init(dev);
TLan_Open(dev);
TLan_EisaProbe( );
TLan_Eisa_Cleanup( );
TLan_StartTx(skb, dev);
TLan_ioctl( dev, rq, cmd);
TLan_GetStats( dev );
/* static void TLan_HandleInterrupt( int, void *, struct pt_regs *); */
/* static void TLan_SetMulticastList( struct net_device *); */
/* static int TLan_probe1(struct pci_dev *pdev,long ioaddr,int irq,int rev,struct pci_device_id *ent); */
/* static void TLan_tx_timeout( struct net_device *dev); */
/* static int tlan_init_one( struct pci_dev *pdev, struct pci_device_id *ent); */
TLan_SetTimer (dev, 1024, 1024);
TLan_Close(dev);
if(lockStatus == 1)
errorFn();
}
|
the_stack_data/237643847.c | /**
*****************************************************************************
**
** File : syscalls.c
**
** Author : Auto-generated by STM32CubeIDE
**
** Abstract : STM32CubeIDE Minimal System calls file
**
** For more information about which c-functions
** need which of these lowlevel functions
** please consult the Newlib libc-manual
**
** Environment : STM32CubeIDE MCU
**
** Distribution: The file is distributed as is, without any warranty
** of any kind.
**
*****************************************************************************
**
** <h2><center>© COPYRIGHT(c) 2020 STMicroelectronics</center></h2>
**
** Redistribution and use in source and binary forms, with or without modification,
** are permitted provided that the following conditions are met:
** 1. Redistributions of source code must retain the above copyright notice,
** this list of conditions and the following disclaimer.
** 2. 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.
** 3. Neither the name of STMicroelectronics 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 HOLDER 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.
**
**
*****************************************************************************
*/
/* Includes */
#include <sys/stat.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
#include <sys/times.h>
/* Variables */
//#undef errno
extern int errno;
extern int __io_putchar(int ch) __attribute__((weak));
extern int __io_getchar(void) __attribute__((weak));
register char * stack_ptr asm("sp");
char *__env[1] = { 0 };
char **environ = __env;
/* Functions */
void initialise_monitor_handles()
{
}
int _getpid(void)
{
return 1;
}
int _kill(int pid, int sig)
{
errno = EINVAL;
return -1;
}
void _exit (int status)
{
_kill(status, -1);
while (1) {} /* Make sure we hang here */
}
__attribute__((weak)) int _read(int file, char *ptr, int len)
{
int DataIdx;
for (DataIdx = 0; DataIdx < len; DataIdx++)
{
*ptr++ = __io_getchar();
}
return len;
}
__attribute__((weak)) int _write(int file, char *ptr, int len)
{
int DataIdx;
for (DataIdx = 0; DataIdx < len; DataIdx++)
{
__io_putchar(*ptr++);
}
return len;
}
int _close(int file)
{
return -1;
}
int _fstat(int file, struct stat *st)
{
st->st_mode = S_IFCHR;
return 0;
}
int _isatty(int file)
{
return 1;
}
int _lseek(int file, int ptr, int dir)
{
return 0;
}
int _open(char *path, int flags, ...)
{
/* Pretend like we always fail */
return -1;
}
int _wait(int *status)
{
errno = ECHILD;
return -1;
}
int _unlink(char *name)
{
errno = ENOENT;
return -1;
}
int _times(struct tms *buf)
{
return -1;
}
int _stat(char *file, struct stat *st)
{
st->st_mode = S_IFCHR;
return 0;
}
int _link(char *old, char *new)
{
errno = EMLINK;
return -1;
}
int _fork(void)
{
errno = EAGAIN;
return -1;
}
int _execve(char *name, char **argv, char **env)
{
errno = ENOMEM;
return -1;
}
|
the_stack_data/175143840.c | #include<stdio.h>
int main()
{
int n,temp,a,res=0;
printf("Enter Number:");
scanf("%d",&n);
temp=n;
while(n>0)
{
a=n%10;
res=res*10+a;
n=n/10;
}
if(temp==res)
{
printf("Palendrome Number");
}
else
{
printf("Not Palindrome Number");
}
}
|
the_stack_data/29357.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int chunk = RAND_MAX / 6;
int hitenter() {
int ch = 0;
while((ch = getc(stdin)) != EOF && ch != '\n') continue;
return EOF == ch;
}
int passball() {
int roll;
roll = 1 + rand()/chunk;
switch (roll) {
case 1:
printf("It's a pass to striker left, \n");
return 2;
case 2:
printf( "A pass to the right striker, \n");
return 2;
case 3:
printf( "A quick pass to midfield left, \n");
return 1;
case 4:
printf( "Over to the right midfielder, \n");
return 1;
case 5:
printf( "It's a header on goal... \n");
return 2;
case 6:
printf( "Ball stolen!");
return -1;
}
}
int shotball() {
int roll;
roll = 1 + rand()/chunk;
switch (roll) {
case 1:
printf("and GOOOOOOAL!!!!!\n");
return -11;
case 2:
printf("The shot's caught; the goalie boots it back with a clear kick.\n");
return -3;
case 3:
printf( "The shot was just wide. Play restarts with a goal kick.\n");
return -3;
case 4:
printf( "It's up, on target... ooh, too high. The goalie punts it out.\n");
return -3;
case 5:
printf( "Shot blocked! Play resumes with a corner kick right.\n");
return 3;
case 6:
printf( "Blocked by a defender! Restarting from corner kick left.\n");
return 3;
}
}
int kickball() {
int roll;
roll = 1 + rand()/chunk;
switch (roll) {
case 1:
printf("Passed to midfield right.\n");
return 1;
case 2:
printf( "Narrowly passed to midfield left.\n");
return 1;
case 3:
printf( "An easy pass to the fullback.\n");
return 1;
case 4:
printf( "It's a long pass to the left striker!\n");
return 2;
case 5:
printf( "Ball stolen!\n");
return -1;
case 6:
printf( "Foul! Offense is awarded a free kick,\n");
return 2;
}
}
int main() {
printf("\n\n\nFIVE POINT SOCCER\n=================\n");
printf("First team to five points wins!\n\n\n(Press enter to begin)");
hitenter();
srand (time(NULL));
int score[2] = {0,0};
int team = 0;
int nextmove = 1;
printf("\n\n%s Team:\n", (team==0)?"Home":"Away" );
do {
if (nextmove < 0) {
printf("\n\n%s Team:\n", (team==0)?"Home":"Away" );
}
switch ( abs(nextmove) ) {
case 1:
nextmove = passball();
break;
case 2:
nextmove = shotball();
break;
case 3:
nextmove = kickball();
break;
}
if (nextmove < 0) {
if (nextmove == -11) {
score[team]++;
nextmove = -1;
}
printf("\nScore - Home: %d, Away: %d\n", score[0], score[1]);
printf("(%s player, press enter)", (team==0)?"Home":"Away" );
hitenter();
team = (team + 1) % 2;
}
} while (score[0]<5 && score[1]<5);
printf("\n\nTHE %s TEAM ARE THE CHAMPIONS!!\n\n\n\n(Press enter to exit)"
, (score[0] > score[1])?"HOME":"AWAY" );
hitenter();
return 0;
}
|
the_stack_data/82951429.c | /*====================================================================*
*
* argv.c - display argument vector;
*
* this program is a simple debugging tool that displays the argument
* vector argv[] on stdout for inspection.
*
* use it to see how your host system processes command line arguments;
*
*. Motley Tools by Charles Maier;
*: Copyright (c) 2001-2006 by Charles Maier Associates Limited;
*; Licensed under the Internet Software Consortium License;
*
*--------------------------------------------------------------------*/
#include <stdio.h>
int main (int argc, char const * argv [])
{
char const ** argp;
for (argp = argv; * argp; argp++)
{
printf (" argv[%lu] = [%s]\n", (long unsigned) (argp - argv), * argp);
}
printf (" argv[%lu] = NULL\n", (long unsigned) (argp - argv));
return (0);
}
|
the_stack_data/448771.c | /**
* P.6 Softmax Activation
* Associated YT NNFS tutorial: https://www.youtube.com/watch?v=omz_NdFgWyU
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define RAND_HIGH_RANGE (0.10)
#define RAND_MIN_RANGE (-0.10)
#define INIT_BIASES (0.0)
#define NET_BATCH_SIZE 300
#define NET_INPUT_LAYER_1_SIZE 2 // Can be replaced with (sizeof(var)/sizeof(double))
#define NET_INPUT_LAYER_2_SIZE 3 // Can be replaced with (sizeof(var)/sizeof(double))
#define NET_OUTPUT_LAYER_SIZE 3 // Can be replaced with (sizeof(var)/sizeof(double))
//Callback function template definition
typedef void (*actiavtion_callback)(double * output);
typedef struct{
double *weights; /*Neural layer network weights*/
double *biase; /*Neural layer network biase*/
double *output; /*Output of the neural layer*/
int input_size; /*Size of the input layer*/
int output_size; /*Size of the output layer*/
actiavtion_callback callback; /* Pionter to the callback used for the activation function */
}layer_dense_t;
typedef struct{
double *x; /* Holds the x y axis data. Data is formated x y x y x y*/
double *y; /* Holds the group the data belongs too. Two steps of x is a single step of y*/
}spiral_data_t;
/**@brief Get the dot product of a neuron and add the bias.
*
* @param[in] input Pointer to the first address of the inputs.
* @param[in] weights Pointer to the first address of the weights.
* @param[in] bias Pointer to the value of the neurons bias.
* @param[in] input_size Number of neurons in the input layer.
* @param[in] callback Pionter to the activation callback function.
* @retval[out] output The dot product of the neuron.
*/
double dot_product(double *input,double *weights,double *bias,int input_size,actiavtion_callback callback){
int i = 0;
double output = 0.0;
for(i = 0;i<input_size;i++){
output += input[i]*weights[i];
}
output += *bias;
if(callback != NULL){
callback(&output);
}
return output;
}
/**@brief Get the dot products of each neuron and add the bias and store it in an output array.
*
* @param[in] input Pointer to the first address of the inputs.
* @param[in] weights Pointer to the first address of the weights.
* @param[in] bias Pointer to the first address of the neuron bases.
* @param[in] input_size Number of neurons in the input layer.
* @param[in/out] outputs Pointer to the first address of the outputs array.
* @param[in] output_size Number of neurons in the output layer.
* @param[in] callback Pionter to the activation callback function.
*/
void layer_output(double *input,double *weights,double *bias,int input_size,double *outputs,int output_size,actiavtion_callback callback){
int i = 0;
int offset = 0;
for(i = 0; i < output_size; i++){
outputs[i] = dot_product(input,weights + offset,&bias[i],input_size,callback);
offset+=input_size;
}
}
// Generate a random floating point number from min to max
double rand_range(double min, double max)
{
double range = (max - min);
double div = RAND_MAX / range;
return min + (rand() / div);
}
/**@brief Setup a layer with random weights and bais as well as allocating memory for the storage buffers.
*
* @param[in] layer Pointer to an empty layer with no values.
* @param[in] intput_size Size of the input layer.
* @param[in] output_size Size of the output layer.
*/
void layer_init(layer_dense_t *layer,int intput_size,int output_size){
layer->input_size = intput_size;
layer->output_size = output_size;
//create data as a flat 1-D dataset
layer->weights = malloc(sizeof(double) * intput_size * output_size);
if(layer->weights == NULL){
printf("weights mem error\n");
return;
}
layer->biase = malloc(sizeof(double) * output_size);
if(layer->biase == NULL){
printf("biase mem error\n");
return;
}
layer->output = malloc(sizeof(double) * output_size);
if(layer->output == NULL){
printf("output mem error\n");
return;
}
int i = 0;
for(i = 0; i < (output_size); i++){
layer->biase[i] = INIT_BIASES;
}
for(i = 0; i < (intput_size*output_size); i++){
layer->weights[i] = rand_range(RAND_MIN_RANGE,RAND_HIGH_RANGE);
}
}
//free the memory allocated by a layer
void deloc_layer(layer_dense_t *layer){
if(layer->weights != NULL){
free(layer->weights);
}
if(layer->biase != NULL){
free(layer->biase);
}
if(layer->biase != NULL){
free(layer->output);
}
}
/**@brief Does a forward pass in the network from one layer to the next.
*
* @param[in] previos_layer Pointer the previos layer struct.
* @param[in] next_layer Pointer the next layer struct.
*/
void forward(layer_dense_t *previos_layer,layer_dense_t *next_layer){
layer_output((previos_layer->output),next_layer->weights,next_layer->biase,next_layer->input_size,(next_layer->output),next_layer->output_size,next_layer->callback);
}
//sigmoid activation function
double activation_sigmoid(double x) {
double result;
result = 1 / (1 + exp(-x));
return result;
}
//ReLU activation function
double activation_ReLU(double x){
if(x < 0.0){
x = 0.0;
}
return x;
}
/**@brief Callback to apply a activation function to the output of a node.
*
* @param[in] output Pointer to the dot product output.
*/
void actiavtion1(double *output){
*output = activation_ReLU(*output);
//*output = sigmoid(*output);
}
/**@brief Generate a random range in a uniform distribution.
* @Note Code was lifted from here https://stackoverflow.com/questions/11641629/generating-a-uniform-distribution-of-integers-in-c
*
* @param[in] rangeLow Lowest value that in the range that can be genarated.
* @param[in] rangeHigh Highest value that in the range that can be genarated.
* @retval[out] rng_scaled Random mumber that has been generated.
*/
double uniform_distribution(double rangeLow, double rangeHigh) {
double rng = rand()/(1.0 + RAND_MAX);
double range = rangeHigh - rangeLow + 1;
double rng_scaled = (rng * range) + rangeLow;
return rng_scaled;
}
/**@brief Generate a random range in a uniform distribution.
* @Note Credit to shreeviknesh (#106) saved alot of time.
*
* @param[in] points Number of points to generate per class.
* @param[in] classes Number of classes to generate.
* @param[out] data Structure holding the generated spiral data.
*/
void spiral_data(int points,int classes,spiral_data_t *data){
data->x = (double*)malloc(sizeof(double)*points*classes*2);
if(data->x == NULL){
printf("data mem error\n");
return;
}
data->y = (double*)malloc(sizeof(double)*points*classes);
if(data->y == NULL){
printf("pionts mem error\n");
return;
}
int ix = 0;
int iy = 0;
int class_number = 0;
for(class_number = 0; class_number < classes; class_number++) {
double r = 0;
double t = class_number * 4;
while(r <= 1 && t <= (class_number + 1) * 4) {
// adding some randomness to t
double random_t = t + uniform_distribution(-1.0,1.0) * 0.2;
// converting from polar to cartesian coordinates
data->x[ix] = r * sin(random_t * 2.5);
data->x[ix+1] = r * cos(random_t * 2.5);
data->y[iy] = class_number;
// the below two statements achieve linspace-like functionality
r += 1.0f / (points - 1);
t += 4.0f / (points - 1);
iy++;
ix+=2; // increment index
}
}
}
/**@brief Free the allocated memory for the spiral data.
*
* @param[in] data Structure holding the generated spiral data.
*/
void deloc_spiral(spiral_data_t *data){
if(data->x != NULL){
free(data->x);
}
if(data->y != NULL){
free(data->y);
}
}
/**@brief Gets the sum of the output layer and normalizes each output value.
*
* @note C can not do inline summation of arrays. This can only be done after a forward pass has been done.
*
* @param[in/out] output_layer Pointer the output layer struct.
*/
void activation_softmax(layer_dense_t *output_layer){
double sum = 0.0;
double maxu = 0.0;
int i = 0;
maxu = output_layer->output[0];
for(i = 1; i < output_layer->output_size;i++){
if(output_layer->output[i] > maxu){
maxu = output_layer->output[i];
}
}
for(i = 0; i < output_layer->output_size;i++){
output_layer->output[i] = exp(output_layer->output[i] - maxu);
sum += output_layer->output[i];
}
for(i = 0; i < output_layer->output_size;i++){
output_layer->output[i] = output_layer->output[i] / sum;
}
}
/**@brief Test function. Sums the output after activation_softmax has run on the output layer. Correct output is 1.0.
*
* @param[in] output_layer Pointer the output layer struct.
*/
double sum_softmax_layer_output(layer_dense_t *output_layer){
double sum = 0.0;
int i = 0;
for(i = 0; i < output_layer->output_size;i++){
sum += output_layer->output[i];
}
return sum;
}
int main()
{
//seed the random values
srand(0);
int i = 0;
int j = 0;
spiral_data_t X_data;
layer_dense_t X;
layer_dense_t dense1;
layer_dense_t dense2;
spiral_data(100,3,&X_data);
if(X_data.x == NULL){
printf("data null\n");
return 0;
}
X.callback = NULL;
dense1 .callback = actiavtion1;
dense2.callback = NULL;
layer_init(&dense1 ,NET_INPUT_LAYER_1_SIZE,NET_INPUT_LAYER_2_SIZE);
layer_init(&dense2,NET_INPUT_LAYER_2_SIZE,NET_OUTPUT_LAYER_SIZE);
for(i = 0; i < NET_BATCH_SIZE;i++){
X.output = &X_data.x[i*2];
forward(&X,&dense1);
/* printf("batch: %d layer1_output: ",i);
for(j = 0; j < dense1 .output_size; j++){
printf("%f ",dense1 .output[j]);
}*/
forward(&dense1,&dense2);
/*printf("batch: %d layer2_output: ",i);
for(j = 0; j < dense2.output_size; j++){
printf("%f ",dense2.output[j]);
}
printf("\n");*/
activation_softmax(&dense2);
printf("batch: %d layer2_softmax: ",i);
for(j = 0; j < dense2.output_size; j++){
printf("%f ",dense2.output[j]);
}
printf("\n");
//printf("batch: %d layer2_normalize_sum: %f\n",i,sum_softmax_layer_output(&dense2));
}
deloc_layer(&dense1);
deloc_layer(&dense2);
deloc_spiral(&X_data);
return 0;
}
|
the_stack_data/173578684.c | /*
* uselib() for uClibc
*
* Copyright (C) 2000-2006 Erik Andersen <[email protected]>
*
* Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
*/
#if 0
linux specific and we do not use it in uClibc.
#include <sys/syscall.h>
#include <unistd.h>
#ifdef __NR_uselib
int uselib (const char *library);
_syscall1(int, uselib, const char *, library)
#endif
#endif
|
the_stack_data/25138045.c | int main() {
int a = 3;
return a |= 5;
}
|
the_stack_data/41915.c | #include <stdio.h>
#include <assert.h>
int int_shifts_are_arithmetic(){
//0xffffffff
int num = -1;
return !(num ^ (num >> 1));
}
int main(void){
assert(int_shifts_are_arithmetic());
return 0;
}
|
the_stack_data/184519152.c | /* { dg-do compile { target { ! x32 } } } */
/* { dg-options "-fcheck-pointer-bounds -mmpx -fsanitize=address" } */
/* { dg-error ".-fcheck-pointer-bounds. is not supported with Address Sanitizer" "" { target *-*-* } 0 } */
extern int x[];
void
foo ()
{
x[0] = 0;
}
|
the_stack_data/107228.c | /*
* Copyright 2019 The Emscripten Authors. All rights reserved.
* Emscripten is available under two separate licenses, the MIT license and the
* University of Illinois/NCSA Open Source License. Both these licenses can be
* found in the LICENSE file.
*/
#include <assert.h>
#include <stdio.h>
void *emscripten_return_address(int level);
void func() {
assert(emscripten_return_address(0) != 0);
assert(emscripten_return_address(50) == 0);
}
// We need to take these two arguments or clang can potentially generate
// a main function that takes two arguments and calls our main, messing up
// the stack trace and breaking this test.
int main(int argc, char **argv) {
assert(emscripten_return_address(50) == 0);
func();
puts("passed");
}
|
the_stack_data/95449566.c | /**
* This program computes the sum of the first n
* prime numbers. Optionally, it allows the user
* to provide n as a command line argument, but
* defaults to the first n = 10 primes
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
/**
* This function takes an integer array (of size n) and
* returns the sum of its elements. It returns 0 if the
* array is NULL or if its size is <= 0
*/
int sum(int *arr, int n);
/**
* This function returns an array containing the first
* n prime numbers
*/
int* getPrimes(int n);
/**
* This function determines returns true if the give
* integer is prime and false otherwise.
*/
int isPrime(int x);
int main(int argc, char **argv) {
int n = 10; //default to the first 10 primes
if(argc = 2) {
atoi(argv[2]);
}
int *primes = getPrimes(n);
int s = sum(primes, n);
printf("The sum of the first %d primes is %d\n", n, s);
return 0;
}
int sum(int *arr, int n) {
int i;
int total;
for(i=0; i<n; i++) {
total =+ arr[i];
}
return total;
}
int* getPrimes(int n) {
int result[n];
int i = 0;
int x = 2;
while(i < n) {
if(isPrime(x)) {
result[i] = x;
i++;
x += 2;
}
}
return result;
}
int isPrime(int x) {
if(x % 2 == 0) {
return 0;
}
for(int i=3; i<=sqrt(x); i+=2) {
if(x % i == 0) {
return 0;
}
}
return 1;
}
|
the_stack_data/31389225.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
int HeadCurrentPosition,MaxTrackNum,ElementNum;
printf("Enter the currect head position:");
scanf("%d",&HeadCurrentPosition);
printf("\nEnter the Maximum tracks number:");
scanf("%d",&MaxTrackNum);
printf("\nEnter number of the tracks that we are seeking:");
scanf("%d",&ElementNum);
printf("\nEnter the tracks number in order:\n");
int count1=0,count2=0,queue[ElementNum],seektime=0,TotalSeekTime=0;
while (count1<ElementNum)
{
int value;
scanf("%d",&value);
if(value>0 && value<=MaxTrackNum) queue[count1]=value;
count1++;
}
while (count2<ElementNum) {
seektime = abs(HeadCurrentPosition-queue[count2]);
printf("%d--(%d)-->%d\n",HeadCurrentPosition,seektime,queue[count2]);
HeadCurrentPosition = queue[count2];
TotalSeekTime +=seektime;
count2++;
}
printf("The Total seek time is equal to:%.2f\n",(float)TotalSeekTime);
printf("The Average of total seek time is equal to:%.2f\n",(float)TotalSeekTime/ElementNum);
return 0;
}
|
the_stack_data/1071204.c | // peer1_0 = server > client. other player disconnects while docked
char peer1_0[] = {
0x00, 0x00, 0x00, 0x10, 0x01, 0x00, 0xd6, 0x08 };
char peer1_1[] = {
0x0e, 0xb2, 0x01, 0xd7, 0x79, 0x49, 0xeb, 0xe3,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6b, 0x6b,
0x00, 0x00, 0x00, 0x10, 0x01, 0x00, 0xd6, 0x08,
0x1b, 0x54, 0x01, 0xd7, 0x79, 0x49, 0xeb, 0xe3,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6e, 0x00 };
|
the_stack_data/922703.c | #include <stdio.h>
#include <assert.h>
int alertFailureCount = 0;
int networkAlertStub(float celcius)
{
printf("ALERT: Temperature is %.1f celcius.\n", celcius);
if(celcius < 200.0f)
{
return 200; // Return 200 for ok
}
else
{
return 500; // Return 500 for ok
}
}
float ConvertFarenheitToCelsius(float farenheit)
{
return (farenheit - 32) * 5 / 9;
}
void alertInCelcius(float farenheit)
{
float celcius = ConvertFarenheitToCelsius(farenheit);
int returnCode = networkAlertStub(celcius);
if (returnCode != 200)
{
// non-ok response is not an error! Issues happen in life!
// let us keep a count of failures to report
// However, this code doesn't count failures!
// Add a test below to catch this bug. Alter the stub above, if needed.
alertFailureCount += 0;
}
}
int main()
{
alertInCelcius(400.5);
alertInCelcius(303.6);
alertInCelcius(212.7);
assert(alertFailureCount == 0);
printf("%d alerts failed.\n", alertFailureCount);
printf("All is well (maybe!)\n");
return 0;
}
|
the_stack_data/97013156.c | void main()
{
int n;
printf("Numeros pares de 2 a 100:\n");
for(n=2 ; n<=100 ; n++)
{
if( n%2==0 )
printf("%d\n", n);
}
return 0;
}
|
the_stack_data/797896.c | #ifndef DEFN_H_
#define DEFN_H_
#define INTEGER 'i'
#define FLOAT 'f'
#define STRING 'c'
#endif /* DEFN_H_ */ |
the_stack_data/140765019.c | #include <stdint.h>
#define int32 int32_t
#define int32_MINMAX(a,b) \
do { \
int32 ab = b ^ a; \
int32 c = b - a; \
c ^= ab & (c ^ b); \
c >>= 31; \
c &= ab; \
a ^= c; \
b ^= c; \
} while(0)
void OQS_KEM_LEDACRYPT_40787_CLEAN_int32_sort(int32 *x, long long n);
void OQS_KEM_LEDACRYPT_40787_CLEAN_int32_sort(int32 *x, long long n)
{
long long top,p,q,r,i,j;
if (n < 2) return;
top = 1;
while (top < n - top) top += top;
for (p = top; p >= 1; p >>= 1) {
i = 0;
while (i + 2 * p <= n) {
for (j = i; j < i + p; ++j)
int32_MINMAX(x[j],x[j+p]);
i += 2 * p;
}
for (j = i; j < n - p; ++j)
int32_MINMAX(x[j],x[j+p]);
i = 0;
j = 0;
for (q = top; q > p; q >>= 1) {
if (j != i) for (;;) {
if (j == n - q) goto done;
int32 a = x[j + p];
for (r = q; r > p; r >>= 1)
int32_MINMAX(a,x[j + r]);
x[j + p] = a;
++j;
if (j == i + p) {
i += 2 * p;
break;
}
}
while (i + p <= n - q) {
for (j = i; j < i + p; ++j) {
int32 a = x[j + p];
for (r = q; r > p; r >>= 1)
int32_MINMAX(a,x[j+r]);
x[j + p] = a;
}
i += 2 * p;
}
/* now i + p > n - q */
j = i;
while (j < n - q) {
int32 a = x[j + p];
for (r = q; r > p; r >>= 1)
int32_MINMAX(a,x[j+r]);
x[j + p] = a;
++j;
}
done:
;
}
}
}
|
the_stack_data/118364.c | #include<stdio.h>
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
int a[10005],s;
int n(int l,int r)
{
int sum=0,i;
for(i=l;i<=r;i++)
{
sum+=a[i]%s;
}
return sum%s;
}
int m(int l,int r)
{
int sum=1,i;
for(i=l;i<=r;i++)
{
sum=((sum%s)*(a[i]%s))%s;
}
return sum;
}
int h(int l,int r)
{
int sum=a[l],i;
for(i=l+1;i<=r;i++)
{
sum=sum^a[i];
}
return sum;
}
int main()
{
int i,j,k,l,r;
scanf("%d%d",&s,&k);
for(i=0;i<s;i++)
{
scanf("%d",&a[i]);
}
for(j=0;j<k;j++)
{
scanf("%d%d",&l,&r);
printf("%d\n",h(min(n(l,r),m(l,r)),max(n(l,r),m(l,r))));
}
return 0;
} |
the_stack_data/37193.c | /* A C-program for MT19937: Integer version */
/* genrand() generates one pseudorandom unsigned integer (32bit) */
/* which is uniformly distributed among 0 to 2^32-1 for each */
/* call. sgenrand(seed) set initial values to the working area */
/* of 624 words. Before genrand(), sgenrand(seed) must be */
/* called once. (seed is any 32-bit integer except for 0). */
/* Coded by Takuji Nishimura, considering the suggestions by */
/* Topher Cooper and Marc Rieffel in July-Aug. 1997. */
/* This library is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Library General Public */
/* License as published by the Free Software Foundation; either */
/* version 2 of the License, or (at your option) any later */
/* version. */
/* This library 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 Library General Public License for more details. */
/* You should have received a copy of the GNU Library General */
/* Public License along with this library; if not, write to the */
/* Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA */
/* 02111-1307 USA */
/* Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura. */
/* Any feedback is very welcome. For any question, comments, */
/* see http://www.math.keio.ac.jp/matumoto/emt.html or email */
/* [email protected] */
#include<stdio.h>
/* Period parameters */
#define N 624
#define M 397
#define MATRIX_A 0x9908b0df /* constant vector a */
#define UPPER_MASK 0x80000000 /* most significant w-r bits */
#define LOWER_MASK 0x7fffffff /* least significant r bits */
/* Tempering parameters */
#define TEMPERING_MASK_B 0x9d2c5680
#define TEMPERING_MASK_C 0xefc60000
#define TEMPERING_SHIFT_U(y) (y >> 11)
#define TEMPERING_SHIFT_S(y) (y << 7)
#define TEMPERING_SHIFT_T(y) (y << 15)
#define TEMPERING_SHIFT_L(y) (y >> 18)
static unsigned long mt[N]; /* the array for the state vector */
static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */
/* initializing the array with a NONZERO seed */
void
isgenrand(seed)
unsigned long seed;
{
/* setting initial seeds to mt[N] using */
/* the generator Line 25 of Table 1 in */
/* [KNUTH 1981, The Art of Computer Programming */
/* Vol. 2 (2nd Ed.), pp102] */
mt[0]= seed & 0xffffffff;
for (mti=1; mti<N; mti++)
mt[mti] = (69069 * mt[mti-1]) & 0xffffffff;
}
unsigned long
igenrand()
{
unsigned long y;
static unsigned long mag01[2]={0x0, MATRIX_A};
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (mti >= N) { /* generate N words at one time */
int kk;
if (mti == N+1) /* if sgenrand() has not been called, */
isgenrand(4357); /* a default initial seed is used */
for (kk=0;kk<N-M;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
}
for (;kk<N-1;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
}
y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
mti = 0;
}
y = mt[mti++];
y ^= TEMPERING_SHIFT_U(y);
y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
y ^= TEMPERING_SHIFT_L(y);
return y;
}
|
the_stack_data/140764391.c | //REPLACED with perl script select words
// massage R's output to the format mallet output so that R's
// output can be fed into the mallet pipeline.
// *** this is the works that make up topic part of the transformation (the top of the file)
// scott needs the lower part
#include "stdio.h"
#include <stdlib.h>
#include "string.h"
#include "malloc.h"
typedef int(*cmpfn)(const void *, const void *);
//#define THRESHOLD 0.01
//#define THRESHOLD 0.33 -- to high 20% cc is sufficient
#define THRESHOLD 0.01
typedef struct
{
char word[10];
double weight;
} tWord;
typedef struct
{
tWord words[3];
} tTopic;
static int cmp(char **a, char **b)
{
// printf("compare %s %s\n", *a , *b);
return strcmp(*b, *a);
}
static int topic_cmp(tTopic *a, tTopic *b)
{
if (a->words[0].weight != b->words[0].weight)
return (int)(10000*(b->words[0].weight - a->words[0].weight));
if (a->words[1].weight != b->words[1].weight)
return (int)(10000*(b->words[1].weight - a->words[1].weight));
return (int)(10000*b->words[2].weight - a->words[2].weight);
}
static int word_cmp(tWord *a, tWord *b)
{
return *a->word - *b->word;
}
static void lint() { lint(); topic_cmp(0,0);}
int main()
{
char buff[1024], alpha[1024];
char *out[3];
out[0] = malloc(20);
out[1] = malloc(20);
out[2] = malloc(20);
double largest_ignored = 0.0;
strcpy(alpha, "no alpha line found yet");
while (fgets(buff, 1024, stdin) != NULL)
{
char order[3][10] = {"aa", "bb", "cc"};
int i, j;
tTopic t[3];
if (strncmp(buff, "alpha", 5) == 0)
{
char *ch = strchr(buff, '\n');
*ch = '\0';
ch = strchr(buff, '=');
strcpy(alpha, ch+1);
continue;
}
if (strstr(buff, "BREAK BREAK BREAK") == NULL)
continue;
// sometimes you get all three topics on one line
// sometimes not ....
fgets(buff, 1024, stdin); // scan off "Topic #1 ..."
int x = sscanf(buff, "%s %s %s", t[0].words[0].word, t[0].words[1].word, t[0].words[2].word);
if (x != 3)
fprintf(stderr, "counts are wrong :( %d\n", x);
for(i=0; i<3; i++)
{
strcpy(t[i].words[0].word, t[0].words[0].word);
strcpy(t[i].words[1].word, t[0].words[1].word);
strcpy(t[i].words[2].word, t[0].words[2].word);
char *ch;
fgets(buff, 1024, stdin);
for(ch = index(buff, '"'); ch != NULL; ch = index(ch, '"'))
*ch = ' ';
x = sscanf(buff, "%*s %*s %lf %lf %lf", &t[i].words[0].weight,
&t[i].words[1].weight, &t[i].words[2].weight);
if (x != 3)
fprintf(stderr, "counts are wrong :( %d\n", x);
}
// put words in abc order
// [[ 3/13 malcom output forms likely obviates the need for this ]]
for(i=0; i<3; i++)
qsort(t[i].words, 3, sizeof(tWord), (cmpfn)word_cmp);
for(i=0; i<3; i++)
{
if (t[0].words[i].weight < THRESHOLD && t[0].words[i].weight > largest_ignored)
largest_ignored = t[0].words[i].weight;
if (t[1].words[i].weight < THRESHOLD && t[1].words[i].weight > largest_ignored)
largest_ignored = t[1].words[i].weight;
if (t[2].words[i].weight < THRESHOLD && t[2].words[i].weight > largest_ignored)
largest_ignored = t[2].words[i].weight;
}
//for(i=0; i<3; i++)
//{
//printf("Topic %d: %s %5.10lf %s %5.10lf %s %5.10lf\n", i+1,
//t[i].words[0].word, t[i].words[0].weight,
//t[i].words[1].word, t[i].words[1].weight,
//t[i].words[2].word, t[i].words[2].weight);
//}
// sequencing and sorting below obviates the need for this
//qsort(t, 3, sizeof(tTopic), (cmpfn)topic_cmp);
//for(i=0; i<3; i++)
//{
//printf("Topic %d: %s %5.10lf %s %5.10lf %s %5.10lf\n", i+1,
//t[i].words[0].word, t[i].words[0].weight,
//t[i].words[1].word, t[i].words[1].weight,
//t[i].words[2].word, t[i].words[2].weight);
//}
for(i=0; i<3; i++)
out[i][0] = '\0';
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
if (strcmp(order[i], t[0].words[j].word) == 0)
strcat(out[0], (t[0].words[j].weight > THRESHOLD ? t[0].words[j].word: ".."));
if (strcmp(order[i], t[1].words[j].word) == 0)
strcat(out[1], (t[1].words[j].weight > THRESHOLD ? t[1].words[j].word: ".."));
if (strcmp(order[i], t[2].words[j].word) == 0)
strcat(out[2], (t[2].words[j].weight > THRESHOLD ? t[2].words[j].word: ".."));
}
if (i < 2)
{
strcat(out[0], "-");
strcat(out[1], "-");
strcat(out[2], "-");
}
}
// printf("iteration 000 %s %s %s %s\n", alpha, out[0], out[1], out[2]);
qsort(out, 3, sizeof(out[0]), (cmpfn)cmp);
printf("iteration 000 %s %s %s %s\n", alpha, out[0], out[1], out[2]);
}
fprintf(stderr, "largest ignored = %10.8lf\n", largest_ignored);
return 0;
}
|
the_stack_data/159516138.c | // justsyms_lib.cc -- test --just-symbols for gold
// Copyright (C) 2011-2018 Free Software Foundation, Inc.
// Written by Cary Coutant <[email protected]>.
// This file is part of gold.
// This program 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 3 of the License, or
// (at your option) any later version.
// This program 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 this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
// MA 02110-1301, USA.
// This test goes with justsyms_exec.cc. We compile this file, then
// link it into an executable image with -Ttext and -Tdata to set
// the starting addresses for each segment.
int exported_func(void);
int exported_data = 0x1000;
int
exported_func(void)
{
return 1;
}
|
the_stack_data/193894306.c | #include <unistd.h>
int main(void)
{
void *addr = (void *)0xaffe;
size_t len = 123;
int prot = 0xabc;
int flag = 0xdef;
int fd = 92;
off_t off = 0xbadf00d;
mmap(addr, len, prot, flag, fd, off);
return 0;
}
|
the_stack_data/72013559.c | // LANGUAGE: C
// AUTOR: Timea Kinga Deák
// GITHUB: https://github.com/DTimi
#include <stdio.h>
int main(void)
{
printf("Hello, World from Dublin!\n");
}
|
the_stack_data/155333.c | // ============================================================================
// Proportional font Header Format:
// ------------------------------------------------
// Character Width (Used as a marker to indicate use this format. i.e.: = 0x00)
// Character Height
// First Character (Reserved. 0x00)
// Number Of Characters (Reserved. 0x00)
// Individual Character Format:
// ----------------------------
// Character Code
// Adjusted Y Offset
// Width
// Height
// xOffset
// xDelta (the distance to move the cursor. Effective width of the character.)
// Data[n]
// NOTE: You can remove any of these characters if they are not needed in
// your application. The first character number in each Glyph indicates
// the ASCII character code. Therefore, these do not have to be sequential.
// Just remove all the content for a particular character to save space.
// ============================================================================
// DejaVuSans
// Point Size : 18
// Memory usage : 1828 bytes
// # characters : 95
const unsigned char tft_Dejavu18[] =
{
0x00, 0x12, 0x00, 0x00,
// ' '
0x20,0x0E,0x00,0x00,0x00,0x06,
// '!'
0x21,0x01,0x02,0x0D,0x03,0x07,
0xFF,0xFF,0xC3,0xC0,
// '"'
0x22,0x01,0x06,0x05,0x01,0x08,
0xCF,0x3C,0xF3,0xCC,
// '#'
0x23,0x00,0x0C,0x0E,0x01,0x0F,
0x04,0x40,0x44,0x0C,0xC0,0xC8,0x7F,0xF7,0xFF,0x09,0x81,0x90,0xFF,0xEF,0xFE,0x13,0x03,0x30,0x32,0x02,0x20,
// '$'
0x24,0x00,0x0A,0x11,0x01,0x0B,
0x08,0x02,0x03,0xE1,0xFC,0xE9,0x32,0x0F,0x81,0xF8,0x0F,0x02,0x60,0x9A,0x2E,0xFF,0x1F,0x80,0x80,0x20,0x08,0x00,
// '%'
0x25,0x01,0x0F,0x0D,0x01,0x11,
0x78,0x10,0x90,0x43,0x31,0x86,0x62,0x0C,0xC8,0x19,0x10,0x1E,0x4F,0x01,0x12,0x02,0x66,0x08,0xCC,0x31,0x98,0x41,0x21,0x03,0xC0,
// '&'
0x26,0x01,0x0C,0x0D,0x01,0x0D,
0x0F,0x01,0xF8,0x30,0x83,0x00,0x38,0x03,0xC0,0x7E,0x6C,0x76,0xC3,0xCC,0x18,0xE1,0xC7,0xFE,0x3E,0x70,
// '''
0x27,0x01,0x02,0x05,0x01,0x04,
0xFF,0xC0,
// '('
0x28,0x00,0x04,0x10,0x02,0x07,
0x32,0x66,0x4C,0xCC,0xCC,0xC4,0x66,0x23,
// ')'
0x29,0x00,0x04,0x10,0x01,0x07,
0xC4,0x66,0x23,0x33,0x33,0x32,0x66,0x4C,
// '*'
0x2A,0x01,0x07,0x08,0x01,0x09,
0x11,0x25,0x51,0xC3,0x8A,0xA4,0x88,
// '+'
0x2B,0x02,0x0C,0x0C,0x02,0x0F,
0x06,0x00,0x60,0x06,0x00,0x60,0x06,0x0F,0xFF,0xFF,0xF0,0x60,0x06,0x00,0x60,0x06,0x00,0x60,
// ','
0x2C,0x0C,0x03,0x04,0x01,0x06,
0x6D,0x40,
// '-'
0x2D,0x08,0x05,0x02,0x01,0x07,
0xFF,0xC0,
// '.'
0x2E,0x0C,0x02,0x02,0x02,0x06,
0xF0,
// '/'
0x2F,0x01,0x06,0x0F,0x00,0x06,
0x0C,0x31,0x86,0x18,0xE3,0x0C,0x31,0xC6,0x18,0x63,0x0C,0x00,
// '0'
0x30,0x01,0x09,0x0D,0x01,0x0B,
0x3E,0x3F,0x98,0xD8,0x3C,0x1E,0x0F,0x07,0x83,0xC1,0xE0,0xD8,0xCF,0xE3,0xE0,
// '1'
0x31,0x01,0x08,0x0D,0x02,0x0B,
0x38,0xF8,0xD8,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0xFF,0xFF,
// '2'
0x32,0x01,0x09,0x0D,0x01,0x0B,
0x7C,0x7F,0x21,0xC0,0x60,0x30,0x30,0x18,0x18,0x18,0x18,0x18,0x1F,0xEF,0xF0,
// '3'
0x33,0x01,0x09,0x0D,0x01,0x0B,
0x7E,0x7F,0xA0,0xE0,0x30,0x39,0xF0,0xFC,0x07,0x01,0x80,0xE0,0xFF,0xE7,0xE0,
// '4'
0x34,0x01,0x0A,0x0D,0x01,0x0B,
0x07,0x01,0xC0,0xB0,0x6C,0x13,0x08,0xC6,0x31,0x0C,0xFF,0xFF,0xF0,0x30,0x0C,0x03,0x00,
// '5'
0x35,0x01,0x08,0x0D,0x01,0x0B,
0x7E,0x7E,0x60,0x60,0x7C,0x7E,0x47,0x03,0x03,0x03,0x87,0xFE,0x7C,
// '6'
0x36,0x01,0x09,0x0D,0x01,0x0B,
0x1E,0x1F,0x9C,0x5C,0x0C,0x06,0xF3,0xFD,0xC7,0xC1,0xE0,0xD8,0xEF,0xE1,0xE0,
// '7'
0x37,0x01,0x08,0x0D,0x01,0x0B,
0xFF,0xFF,0x06,0x06,0x06,0x0E,0x0C,0x0C,0x1C,0x18,0x18,0x38,0x30,
// '8'
0x38,0x01,0x09,0x0D,0x01,0x0B,
0x3E,0x3F,0xB8,0xF8,0x3E,0x39,0xF1,0xFD,0xC7,0xC1,0xE0,0xF8,0xEF,0xE3,0xE0,
// '9'
0x39,0x01,0x09,0x0D,0x01,0x0B,
0x3C,0x3F,0xB8,0xD8,0x3C,0x1F,0x1D,0xFE,0x7B,0x01,0x81,0xD1,0xCF,0xC3,0xC0,
// ':'
0x3A,0x05,0x02,0x09,0x02,0x06,
0xF0,0x03,0xC0,
// ';'
0x3B,0x05,0x03,0x0B,0x01,0x06,
0x6C,0x00,0x03,0x6A,0x00,
// '<'
0x3C,0x04,0x0B,0x0A,0x02,0x0F,
0x00,0x20,0x3C,0x1F,0x1F,0x0F,0x81,0xF0,0x0F,0x80,0x3E,0x01,0xE0,0x04,
// '='
0x3D,0x05,0x0B,0x06,0x02,0x0F,
0xFF,0xFF,0xFC,0x00,0x00,0x0F,0xFF,0xFF,0xC0,
// '>'
0x3E,0x04,0x0B,0x0A,0x02,0x0F,
0x80,0x1E,0x01,0xF0,0x07,0xC0,0x3E,0x07,0xC3,0xE3,0xE0,0xF0,0x10,0x00,
// '?'
0x3F,0x01,0x07,0x0D,0x01,0x0A,
0x79,0xFA,0x38,0x30,0x61,0x86,0x18,0x30,0x60,0x01,0x83,0x00,
// '@'
0x40,0x01,0x10,0x10,0x01,0x12,
0x07,0xE0,0x1F,0xF8,0x3C,0x1C,0x70,0x06,0x60,0x07,0xE3,0x63,0xC7,0xE3,0xC6,0x63,0xC6,0x66,0xC7,0xFC,0xE3,0x70,0x60,0x00,0x70,0x00,0x3C,0x30,0x1F,0xF0,0x07,0xC0,
// 'A'
0x41,0x01,0x0C,0x0D,0x00,0x0C,
0x06,0x00,0x60,0x0F,0x00,0xF0,0x19,0x81,0x98,0x19,0x83,0x0C,0x3F,0xC7,0xFE,0x60,0x66,0x06,0xC0,0x30,
// 'B'
0x42,0x01,0x09,0x0D,0x02,0x0C,
0xFC,0x7F,0xB0,0xD8,0x6C,0x37,0xF3,0xF9,0x86,0xC1,0xE0,0xF0,0xFF,0xEF,0xE0,
// 'C'
0x43,0x01,0x0B,0x0D,0x01,0x0D,
0x0F,0xC7,0xFD,0xC0,0xB0,0x0C,0x01,0x80,0x30,0x06,0x00,0xC0,0x0C,0x01,0xC0,0x9F,0xF0,0xFC,
// 'D'
0x44,0x01,0x0B,0x0D,0x02,0x0E,
0xFE,0x1F,0xF3,0x07,0x60,0x6C,0x07,0x80,0xF0,0x1E,0x03,0xC0,0x78,0x1B,0x07,0x7F,0xCF,0xE0,
// 'E'
0x45,0x01,0x08,0x0D,0x02,0x0B,
0xFF,0xFF,0xC0,0xC0,0xC0,0xFF,0xFF,0xC0,0xC0,0xC0,0xC0,0xFF,0xFF,
// 'F'
0x46,0x01,0x08,0x0D,0x02,0x0A,
0xFF,0xFF,0xC0,0xC0,0xC0,0xFE,0xFE,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,
// 'G'
0x47,0x01,0x0B,0x0D,0x01,0x0E,
0x0F,0xC7,0xFD,0xC0,0xB0,0x0C,0x01,0x87,0xF0,0xFE,0x03,0xC0,0x6C,0x0D,0xC1,0x9F,0xE0,0xF8,
// 'H'
0x48,0x01,0x0A,0x0D,0x02,0x0E,
0xC0,0xF0,0x3C,0x0F,0x03,0xC0,0xFF,0xFF,0xFF,0x03,0xC0,0xF0,0x3C,0x0F,0x03,0xC0,0xC0,
// 'I'
0x49,0x01,0x02,0x0D,0x02,0x06,
0xFF,0xFF,0xFF,0xC0,
// 'J'
0x4A,0x01,0x05,0x11,0xFF,0x06,
0x18,0xC6,0x31,0x8C,0x63,0x18,0xC6,0x31,0x8C,0xFE,0xE0,
// 'K'
0x4B,0x01,0x0B,0x0D,0x02,0x0C,
0xC1,0x98,0x63,0x18,0x66,0x0D,0x81,0xE0,0x3C,0x06,0xC0,0xCC,0x18,0xC3,0x0C,0x60,0xCC,0x0C,
// 'L'
0x4C,0x01,0x08,0x0D,0x02,0x0A,
0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xFF,0xFF,
// 'M'
0x4D,0x01,0x0C,0x0D,0x02,0x10,
0xE0,0x7F,0x0F,0xF0,0xFD,0x8B,0xD9,0xBD,0x9B,0xCF,0x3C,0xF3,0xC6,0x3C,0x63,0xC0,0x3C,0x03,0xC0,0x30,
// 'N'
0x4E,0x01,0x0A,0x0D,0x02,0x0E,
0xE0,0xF8,0x3F,0x0F,0xC3,0xD8,0xF6,0x3C,0xCF,0x1B,0xC6,0xF0,0xFC,0x3F,0x07,0xC1,0xC0,
// 'O'
0x4F,0x01,0x0C,0x0D,0x01,0x0E,
0x1F,0x83,0xFC,0x70,0xE6,0x06,0xC0,0x3C,0x03,0xC0,0x3C,0x03,0xC0,0x36,0x06,0x70,0xE3,0xFC,0x1F,0x80,
// 'P'
0x50,0x01,0x08,0x0D,0x02,0x0B,
0xFC,0xFE,0xC7,0xC3,0xC3,0xC7,0xFE,0xFC,0xC0,0xC0,0xC0,0xC0,0xC0,
// 'Q'
0x51,0x01,0x0C,0x0F,0x01,0x0E,
0x1F,0x83,0xFC,0x70,0xE6,0x06,0xC0,0x3C,0x03,0xC0,0x3C,0x03,0xC0,0x36,0x06,0x70,0xE3,0xFC,0x1F,0x80,0x18,0x00,0xC0,
// 'R'
0x52,0x01,0x0A,0x0D,0x02,0x0D,
0xFC,0x3F,0x8C,0x73,0x0C,0xC3,0x31,0xCF,0xE3,0xF0,0xC6,0x30,0xCC,0x33,0x06,0xC1,0xC0,
// 'S'
0x53,0x01,0x0A,0x0D,0x01,0x0B,
0x3E,0x1F,0xCE,0x13,0x00,0xC0,0x1F,0x03,0xF0,0x0E,0x01,0x80,0x68,0x3B,0xFC,0x7E,0x00,
// 'T'
0x54,0x01,0x0C,0x0D,0x00,0x0C,
0xFF,0xFF,0xFF,0x06,0x00,0x60,0x06,0x00,0x60,0x06,0x00,0x60,0x06,0x00,0x60,0x06,0x00,0x60,0x06,0x00,
// 'U'
0x55,0x01,0x0A,0x0D,0x02,0x0E,
0xC0,0xF0,0x3C,0x0F,0x03,0xC0,0xF0,0x3C,0x0F,0x03,0xC0,0xF0,0x36,0x19,0xFE,0x1E,0x00,
// 'V'
0x56,0x01,0x0C,0x0D,0x00,0x0C,
0xC0,0x36,0x06,0x60,0x66,0x06,0x30,0xC3,0x0C,0x19,0x81,0x98,0x19,0x80,0xF0,0x0F,0x00,0x60,0x06,0x00,
// 'W'
0x57,0x01,0x11,0x0D,0x01,0x13,
0xC1,0xC1,0xE0,0xE0,0xD8,0xF8,0xCC,0x6C,0x66,0x36,0x33,0x1B,0x18,0xD8,0xD8,0x6C,0x6C,0x36,0x36,0x1F,0x1F,0x07,0x07,0x03,0x83,0x81,0xC1,0xC0,
// 'X'
0x58,0x01,0x0B,0x0D,0x01,0x0D,
0x70,0xE6,0x18,0xE6,0x0D,0xC0,0xF0,0x1C,0x03,0x80,0x78,0x1B,0x07,0x30,0xC7,0x30,0x6E,0x0E,
// 'Y'
0x59,0x01,0x0C,0x0D,0x00,0x0C,
0xE0,0x76,0x06,0x30,0xC1,0x98,0x19,0x80,0xF0,0x06,0x00,0x60,0x06,0x00,0x60,0x06,0x00,0x60,0x06,0x00,
// 'Z'
0x5A,0x01,0x0B,0x0D,0x01,0x0D,
0xFF,0xFF,0xFC,0x07,0x01,0xC0,0x30,0x0E,0x03,0x80,0xE0,0x18,0x06,0x01,0xC0,0x7F,0xFF,0xFE,
// '['
0x5B,0x00,0x04,0x10,0x01,0x07,
0xFF,0xCC,0xCC,0xCC,0xCC,0xCC,0xCC,0xFF,
// '\'
0x5C,0x01,0x06,0x0F,0x00,0x06,
0xC3,0x06,0x18,0x61,0xC3,0x0C,0x30,0xE1,0x86,0x18,0x30,0xC0,
// ']'
0x5D,0x00,0x04,0x10,0x02,0x07,
0xFF,0x33,0x33,0x33,0x33,0x33,0x33,0xFF,
// '^'
0x5E,0x01,0x0B,0x05,0x02,0x0F,
0x0E,0x03,0xE0,0xC6,0x30,0x6C,0x06,
// '_'
0x5F,0x10,0x09,0x02,0x00,0x09,
0xFF,0xFF,0xC0,
// '`'
0x60,0x00,0x04,0x03,0x02,0x09,
0xC6,0x30,
// 'a'
0x61,0x04,0x08,0x0A,0x01,0x0A,
0x3C,0x7E,0x47,0x03,0x3F,0xFF,0xC3,0xC7,0xFF,0x7B,
// 'b'
0x62,0x00,0x09,0x0E,0x02,0x0B,
0xC0,0x60,0x30,0x18,0x0D,0xE7,0xFB,0x8F,0x83,0xC1,0xE0,0xF0,0x7C,0x7F,0xF6,0xF0,
// 'c'
0x63,0x04,0x08,0x0A,0x01,0x09,
0x1E,0x7F,0x61,0xC0,0xC0,0xC0,0xC0,0x61,0x7F,0x1E,
// 'd'
0x64,0x00,0x09,0x0E,0x01,0x0B,
0x01,0x80,0xC0,0x60,0x33,0xDB,0xFF,0x8F,0x83,0xC1,0xE0,0xF0,0x7C,0x77,0xF9,0xEC,
// 'e'
0x65,0x04,0x0A,0x0A,0x01,0x0B,
0x1F,0x1F,0xE6,0x1F,0x03,0xFF,0xFF,0xFC,0x01,0x81,0x7F,0xC7,0xE0,
// 'f'
0x66,0x00,0x07,0x0E,0x00,0x06,
0x1E,0x7C,0xC1,0x8F,0xFF,0xCC,0x18,0x30,0x60,0xC1,0x83,0x06,0x00,
// 'g'
0x67,0x04,0x09,0x0E,0x01,0x0B,
0x3D,0xBF,0xF8,0xF8,0x3C,0x1E,0x0F,0x07,0xC7,0x7F,0x9E,0xC0,0x68,0x67,0xF1,0xF0,
// 'h'
0x68,0x00,0x08,0x0E,0x02,0x0B,
0xC0,0xC0,0xC0,0xC0,0xDE,0xFE,0xE7,0xC3,0xC3,0xC3,0xC3,0xC3,0xC3,0xC3,
// 'i'
0x69,0x00,0x02,0x0E,0x02,0x05,
0xF0,0xFF,0xFF,0xF0,
// 'j'
0x6A,0x00,0x04,0x12,0x00,0x05,
0x33,0x00,0x33,0x33,0x33,0x33,0x33,0x33,0xEC,
// 'k'
0x6B,0x00,0x09,0x0E,0x02,0x0A,
0xC0,0x60,0x30,0x18,0x0C,0x36,0x33,0x31,0xB0,0xF0,0x78,0x36,0x19,0x8C,0x66,0x18,
// 'l'
0x6C,0x00,0x02,0x0E,0x02,0x05,
0xFF,0xFF,0xFF,0xF0,
// 'm'
0x6D,0x04,0x0E,0x0A,0x02,0x11,
0xDC,0x7B,0xFB,0xEE,0x79,0xF0,0xC3,0xC3,0x0F,0x0C,0x3C,0x30,0xF0,0xC3,0xC3,0x0F,0x0C,0x30,
// 'n'
0x6E,0x04,0x08,0x0A,0x02,0x0B,
0xDE,0xFE,0xE7,0xC3,0xC3,0xC3,0xC3,0xC3,0xC3,0xC3,
// 'o'
0x6F,0x04,0x0A,0x0A,0x01,0x0B,
0x1E,0x1F,0xE6,0x1B,0x03,0xC0,0xF0,0x3C,0x0D,0x86,0x7F,0x87,0x80,
// 'p'
0x70,0x04,0x09,0x0E,0x02,0x0B,
0xDE,0x7F,0xB8,0xF8,0x3C,0x1E,0x0F,0x07,0xC7,0xFF,0x6F,0x30,0x18,0x0C,0x06,0x00,
// 'q'
0x71,0x04,0x09,0x0E,0x01,0x0B,
0x3D,0xBF,0xF8,0xF8,0x3C,0x1E,0x0F,0x07,0xC7,0x7F,0x9E,0xC0,0x60,0x30,0x18,0x0C,
// 'r'
0x72,0x04,0x06,0x0A,0x02,0x08,
0xDF,0xFE,0x30,0xC3,0x0C,0x30,0xC3,0x00,
// 's'
0x73,0x04,0x08,0x0A,0x01,0x08,
0x7C,0xFE,0xC2,0xE0,0x7C,0x1E,0x06,0x86,0xFE,0x78,
// 't'
0x74,0x01,0x06,0x0D,0x01,0x07,
0x61,0x86,0x3F,0xFD,0x86,0x18,0x61,0x86,0x1F,0x3C,
// 'u'
0x75,0x04,0x08,0x0A,0x02,0x0B,
0xC3,0xC3,0xC3,0xC3,0xC3,0xC3,0xC3,0xE7,0x7F,0x7B,
// 'v'
0x76,0x04,0x0C,0x0A,0x00,0x0B,
0x60,0x66,0x06,0x30,0xC3,0x0C,0x19,0x81,0x98,0x19,0x80,0xF0,0x0F,0x00,0x60,
// 'w'
0x77,0x04,0x0F,0x0A,0x01,0x10,
0x63,0x8C,0xC7,0x19,0x8E,0x31,0xB6,0xC3,0x6D,0x86,0xDB,0x0F,0x1E,0x0E,0x38,0x1C,0x70,0x38,0xE0,
// 'x'
0x78,0x04,0x0A,0x0A,0x01,0x0B,
0xE1,0xD8,0x63,0x30,0xCC,0x1E,0x07,0x83,0x30,0xCC,0x61,0xB8,0x70,
// 'y'
0x79,0x04,0x0C,0x0E,0x00,0x0B,
0x60,0x66,0x06,0x30,0xC3,0x0C,0x19,0x81,0x98,0x0F,0x00,0xF0,0x06,0x00,0x60,0x06,0x00,0xC0,0x3C,0x03,0x80,
// 'z'
0x7A,0x04,0x08,0x0A,0x01,0x09,
0xFF,0xFF,0x06,0x0C,0x1C,0x38,0x30,0x70,0xFF,0xFF,
// '{'
0x7B,0x00,0x08,0x11,0x02,0x0B,
0x0F,0x1F,0x18,0x18,0x18,0x18,0x38,0xF0,0xF0,0x38,0x18,0x18,0x18,0x18,0x18,0x1F,0x0F,
// '|'
0x7C,0x00,0x02,0x12,0x02,0x06,
0xFF,0xFF,0xFF,0xFF,0xF0,
// '}'
0x7D,0x00,0x08,0x11,0x02,0x0B,
0xF0,0xF8,0x18,0x18,0x18,0x18,0x1C,0x0F,0x0F,0x1C,0x18,0x18,0x18,0x18,0x18,0xF8,0xF0,
// '~'
0x7E,0x05,0x0B,0x05,0x02,0x0F,
0x00,0x0F,0x87,0xFF,0xC3,0xE0,0x00,
// Terminator
0xFF
};
|
the_stack_data/5785.c | /* Generated by CIL v. 1.7.0 */
/* print_CIL_Input is false */
struct _IO_FILE;
struct timeval;
extern float strtof(char const *str , char const *endptr ) ;
extern void signal(int sig , void *func ) ;
typedef struct _IO_FILE FILE;
extern int atoi(char const *s ) ;
extern double strtod(char const *str , char const *endptr ) ;
extern int fclose(void *stream ) ;
extern void *fopen(char const *filename , char const *mode ) ;
extern void abort() ;
extern void exit(int status ) ;
extern int raise(int sig ) ;
extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ;
extern int strcmp(char const *a , char const *b ) ;
extern int rand() ;
extern unsigned long strtoul(char const *str , char const *endptr , int base ) ;
void RandomFunc(unsigned long input[1] , unsigned long output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
void megaInit(void)
{
{
}
}
int main(int argc , char *argv[] )
{
unsigned long input[1] ;
unsigned long output[1] ;
int randomFuns_i5 ;
unsigned long randomFuns_value6 ;
int randomFuns_main_i7 ;
{
megaInit();
if (argc != 2) {
printf("Call this program with %i arguments\n", 1);
exit(-1);
} else {
}
randomFuns_i5 = 0;
while (randomFuns_i5 < 1) {
randomFuns_value6 = strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == 16717361816685092373UL) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%lu\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
void RandomFunc(unsigned long input[1] , unsigned long output[1] )
{
unsigned long state[1] ;
unsigned long local2 ;
unsigned long local1 ;
char copy11 ;
{
state[0UL] = (input[0UL] + 914778474UL) ^ 0xffffffffce5d000bUL;
local1 = 0UL;
while (local1 < 0UL) {
local2 = 0UL;
while (local2 < 0UL) {
if (state[0UL] == local2 + local1) {
state[0UL] |= ((state[local2] + state[0UL]) & 15UL) << 2UL;
} else {
copy11 = *((char *)(& state[local1]) + 5);
*((char *)(& state[local1]) + 5) = *((char *)(& state[local1]) + 1);
*((char *)(& state[local1]) + 1) = copy11;
}
local2 += 2UL;
}
local1 ++;
}
output[0UL] = state[0UL] + 0xe80000000056046dUL;
}
}
|
the_stack_data/315161.c | #include<stdio.h>
int main()
{
printf("XIn Chao !!!\n");
} |
the_stack_data/68887186.c | /*
* main.c
*
* Created: 2015/04/1
* Author: Timothy Thompkins
*/
|
the_stack_data/43889223.c | #include <stdio.h>
#include <openssl/bn.h>
void printBN(char *msg, BIGNUM * a);
int main()
{
BN_CTX *ctx = BN_CTX_new();
BIGNUM *e = BN_new(); //(e, n) public key
BIGNUM *n = BN_new(); //(e, n) public key
BIGNUM *Scor = BN_new(); // correct Signature
BIGNUM *Sinc = BN_new(); // incorrect Signature
BIGNUM *msgCor = BN_new(); // correct Message
BIGNUM *msgInc = BN_new(); // incorrect Message
// Ekxwrisi timwn
BN_hex2bn(&e, "010001");
BN_hex2bn(&n, "AE1CD4DC432798D933779FBD46C6E1247F0CF1233595113AA51B450F18116115");
BN_hex2bn(&Scor, "643D6F34902D9C7EC90CB0B2BCA36C47FA37165C0005CAB026C0542CBDB6802F");
BN_hex2bn(&Sinc, "643D6F34902D9C7EC90CB0B2BCA36C47FA37165C0005CAB026C0542CBDB6803F");
// Epalitheusi ypografis msg = S ^ e mod n
BN_mod_exp(msgCor, Scor, e, n , ctx);
BN_mod_exp(msgInc, Sinc, e, n , ctx);
// Ektypwsh apotelesmatwn
printBN("e = ", e);
printBN("n = ", n);
printBN("Scor = ", Scor);
printBN("Sinc = ", Sinc);
printBN("msgCor = ", msgCor);
printBN("msgInc = ", msgInc);
}
void printBN(char *msg, BIGNUM * a)
{
char * number_str = BN_bn2hex(a);
printf("%s%s\n", msg, number_str);
OPENSSL_free(number_str);
} |
the_stack_data/117327492.c | #include <stdio.h>
#include <string.h>
#include <sys/types.h>
#define NCHARS 42
#define BUF_SIZE 4096
int norm_et_ver(char *buf, char *inv) {
char len = 0;
memset(inv, 0, NCHARS);
while (*buf) {
if (*buf < '1' || 'Z' < *buf) return 1;
*buf -= '1';
if (inv[(unsigned char)*buf]) return 1;
inv[(unsigned char)*buf] = len++;
++buf;
}
if (len != NCHARS) return 1;
return 0;
}
void Qnorm(char i, char *c) {
*c = (i + *c) % NCHARS;
}
int main(int argc, char **argv) {
if (argc != 5) return 1;
// retrieve stuff
char *L = argv[1], *R = argv[2], *T = argv[3];
char l = argv[4][0], r = argv[4][1];
if (argv[4][2]) return 1;
char Linv[NCHARS] = {0}, Rinv[NCHARS] = {0}, Tinv[NCHARS] = {0};
// normalize & verify
if (norm_et_ver(L, Linv)) return 1;
if (norm_et_ver(R, Rinv)) return 1;
if (norm_et_ver(T, Tinv)) return 1;
if (memcmp(T, Tinv, NCHARS)) return 1;
if (l < '1' || 'Z' < l) return 1;
if (r < '1' || 'Z' < r) return 1;
l -= '1';
r -= '1';
char buf[BUF_SIZE] = {0};
while (fgets(&buf[0], BUF_SIZE, stdin)) {
char *cur = buf;
while (*cur) {
if (*cur < '1' || 'Z' < *cur) return 1;
*cur -= '1';
++r; if (r == NCHARS) r = 0;
if (r == 'L' - '1' || r == 'R' - '1' || r == 'T' - '1') {
++l; if (l == NCHARS) l = 0;
}
Qnorm(r, cur);
*cur = R[(unsigned char)*cur];
Qnorm(r > 0 ? 42 - r : 0, cur);
Qnorm(l, cur);
*cur = L[(unsigned char)*cur];
Qnorm(l > 0 ? 42 - l : 0, cur);
*cur = T[(unsigned char)*cur];
Qnorm(l, cur);
*cur = Linv[(unsigned char)*cur];
Qnorm(l > 0 ? 42 - l : 0, cur);
Qnorm(r, cur);
*cur = Rinv[(unsigned char)*cur];
Qnorm(r > 0 ? 42 - r : 0, cur);
*cur += '1';
++cur;
}
fwrite(&buf[0], 1, cur - buf, stdout);
}
return 0;
}
|
the_stack_data/65088.c | void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int* nums, int numsSize) {
int pivot = nums[numsSize - 1];
int i = -1;
for (int j = 0; j < numsSize - 1; j ++) {
if (nums[j] <= pivot) {
i ++;
swap(&nums[i], &nums[j]);
}
}
swap(&nums[i + 1], &nums[numsSize - 1]);
return i + 1;
}
int findKthLargest(int* nums, int numsSize, int k) {
int index = partition(nums, numsSize);
if (index == numsSize - k) {
return nums[index];
} else if (index < numsSize - k) {
return findKthLargest(nums + index + 1, numsSize - index - 1, k);
} else if (index > numsSize - k) {
return findKthLargest(nums, index, k - (numsSize - index));
}
return 0;
}
|
the_stack_data/84646.c | /* momati_c rewritten from Fortan
Thomas Roatsch, DLR, 5-Mar-2001 */
/* 22 JULY 80 ...GMY... INITIAL RELEASE
Sept. 1992 ...WPL... Ported for UNIX Conversion
THIS ROUTINE COMPUTES THE PLANET TO CAMERA ROTATION MATRIX (A) AND THE
VECTOR FROM PLANET CENTER TO SPACECRAFT (RS), EXPRESSED IN THE PLANET
SYSTEM. A VECTOR V IN THE PLANET SYSTEM IS THEN RELATED TO THE SAME
VECTOR VP IN THE CAMERA SYSTEM by
VP = A*V + RS , Note A is a 3x3 Matrix
REQUIRED NAVIGATION INFORMATION ...
OAL,OAS=LINE,SAMPLE LOCATION OF OPTIAXIS
SSL,SSS=LINE,SAMPLE LOCATION OF PLANET CENTER
SCLA=PLANETOCENTRILATITUDE OF S/(DEG)
SCLO=WEST LONGITUDE OF S/C
ANGN=NORTH ANGLE AT OPTIAXIS INTERCEPT POINT
RANGE=RANGE FROM S/TO PLANET CENTER
SCALE=SCALE IN PIXELS/MM
FL=FOCAL LENGTH IN MM */
#include <math.h>
void momati_c(double oal, double oas, double ssl, double sss,
double scale, double fl, double sclo, double scla,
double angn, double range, double a[3][3], double rs[3])
{
double pi, rad;
double cla, sla, clon, slon;
double x,y,z,d;
int icase,i;
double cna,sna,cra,sra,crb,srb,d1;
double cx,cy,cz,g,a1,a2;
pi = 3.141592653589;
rad = pi/180.0;
cla = cos(scla*rad);
sla = sin(scla*rad);
clon = cos(sclo*rad);
slon = sin(sclo*rad);
/* THIS SECTION COMPUTES ROTATIONS A AND B
FIRST COMPUT RS VECTOR IN CAMERA SYSTEM */
x = sss - oas;
y = ssl - oal;
z = fl*scale;
d = sqrt(x*x+y*y+z*z);
/* CHECK FOR SPECIAL CASES */
icase = 0;
/* INITIALLY, NA=0, A=90, B=0 (CASE 1) */
cna = 1.0;
sna = 0.0;
cra = 0.0;
sra = 1.0;
if (scla < 0) sra=-1.0;
crb = 1.0;
srb = 0.0;
d1 = sqrt(x*x+y*y);
if(fabs(scla) != 90) goto go_3;
if(d1 == 0) goto go_5;
/* CASE 2 SCLA=90, (OAL,OAS).NE.(SSL,SSS) */
icase = 2;
clon = -clon;
slon = -slon;
cna = y/d1;
sna = -x/d1;
if(scla > 0) goto go_10;
cna = -cna;
sna = -sna;
goto go_10;
go_3:
if(angn != -999.) goto go_6;
if(d1 == 0) goto go_5;
/* CASE 3 SPIN AXIS PARALLEL TO OPTIC AXIS */
cna = y/d1;
sna = -x/d1;
if(scla < 0) goto go_4;
cna = -cna;
sna = -sna;
go_4:
cla = fabs((-x*sna+y*cna)/d);
sla = z/d;
if(scla < 0.0) sla=-sla;
goto go_15;
/* CASE 1 SCLA=90, (OAL,OAS)=(SSL,SSS) */
go_5:
cla = 0.0;
sla = -1.0;
if(scla < 0) goto go_15;
sla = 1.0;
clon = -clon;
slon = -slon;
goto go_15;
/* NORMAL CASE */
go_6:
cna = cos(angn*rad);
sna = sin(angn*rad);
/* ROTATE ABOUT Z-AXIS SO THAT NORTH IS UP IN IMAGE */
go_10:
cx = (x*cna + y*sna)/d;
cy = (-x*sna+ y*cna)/d;
cz = z/d;
/* ROTATE ABOUT X-AXIS SO THAT -Y AXIS IS PARALLEL TO SPIN AXIS. */
d = cy*cy + cz*cz;
g = d - sla*sla;
if(g < 0) g=0.0;
g = sqrt(g);
cra = (cy*sla+cz*g)/d;
sra = (cz*sla-cy*g)/d;
if(icase != 0) goto go_15;
cz = cz*cra - cy*sra;
d = sqrt(cx*cx+cz*cz);
crb = cz/d;
srb = cx/d;
/* THIS SECTION COMPUTES RESULTANT ROTATION MATRIX
A MATRIX IS INITIALLY NORTH ANGLE ROTATION ABOUT Z-AXIS */
go_15:
a[2][0] = 0.0;
a[2][1] = 0.0;
a[0][2] = 0.0;
a[1][2] = 0.0;
a[0][0] = cna;
a[0][1] = sna;
a[1][0] = -sna;
a[1][1] = cna;
a[2][2] = 1.0;
/* ROTATE ABOUT X-AXIS SO THAT -Y AXIS IS PARALLEL TO SPIN AXIS .
A = M1*A */
for (i=0; i<3; i++)
{
a2 = cra*a[1][i] + sra*a[2][i];
a[2][i] = -sra*a[1][i] + cra*a[2][i];
a[1][i] = a2;
}
/* ROTATE ABOUT Y-AXIS SO THAT PLANET CENTER LIES IN Y-Z PLANE.
A = M2*A */
for (i=0; i<3; i++)
{
a1 = crb*a[0][i] - srb*a[2][i];
a[2][i] = srb*a[0][i] + crb*a[2][i];
a[0][i] = a1;
}
/* INTERCHANGE COORDINATES SO THAT
XP = -Z, YP=X, ZP=-Y */
for (i=0; i<3; i++)
{
a1 = a[0][i];
a2 = a[1][i];
a[0][i] = -a[2][i];
a[1][i] = a1;
a[2][i] = -a2;
}
/* ROTATE ABOUT Z-AXIS SO THAT X-AXIS POINTS TO LON 0, LAT 0.
A = M3*A */
for (i=0; i<3; i++)
{
a1 = clon*a[0][i] + slon*a[1][i];
a[1][i] = -slon*a[0][i] + clon*a[1][i];
a[0][i] = a1;
}
/* COMPUTE VECTOR FROM PLANET CENTER TO S/C, IN PLANET SYSTEM.*/
rs[0] = range*cla*clon;
rs[1] = -range*cla*slon;
rs[2] = range*sla;
}
|
the_stack_data/64300.c | /* Test that IPA-CP is able to figure out that both parameters a are constant 7
even though f and h recursively call each other and specialize them
accordingly. */
/* { dg-do compile } */
/* { dg-options "-O3 -fipa-cp -fipa-cp-clone -fdump-ipa-cp -fno-early-inlining" } */
/* { dg-add-options bind_pic_locally } */
extern void use_stuff (int);
static
int g (int b, int c)
{
int i;
for (i = 0; i < b; i++)
use_stuff (c);
}
static void f (int a, int x, int z);
static void h (int z, int a)
{
use_stuff (z);
f (a, 9, 10);
}
static void
f (int a, int x, int z)
{
if (z > 1)
g (a, x);
else
h (5, a);
}
int
main (int argc, char *argv[])
{
int i;
for (i = 0; i < 100; i++)
f (7, 8, argc);
return 0;
}
/* { dg-final { scan-ipa-dump "Creating a specialized node of f.*for all known contexts" "cp" } } */
/* { dg-final { scan-ipa-dump "replacing param .0 a with const 7" "cp" } } */
|
the_stack_data/43446.c | char *getenv(char *);
int main() {
char *p = getenv("PATH");
printf(p);
return 0;
}
|
the_stack_data/70449169.c | #include <stdio.h>
char ParaMaiusculo(char);
char ParaMinusculo(char);
int main()
{
char letra1 = 'b', letra2 = 'C';
printf("Funcao maiuscula: %c | %c\n", ParaMaiusculo(letra1), ParaMaiusculo(letra2));
printf("Funcao minuscula: %c | %c\n", ParaMinusculo(letra1), ParaMinusculo(letra2));
}
char ParaMaiusculo(char caracter)
{
if (caracter >= 'A' && caracter <= 'Z')
return caracter;
else if (caracter >= 'a' && caracter <= 'z')
return caracter - 32;
}
char ParaMinusculo(char caracter)
{
if (caracter >= 'A' && caracter <= 'Z')
return caracter + 32;
else if (caracter >= 'a' && caracter <= 'z')
return caracter;
}
|
the_stack_data/1056409.c | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
// Let us create a global variable to change it in threads
int g = 0;
// The function to be executed by all threads
void *test_thread(void *arg)
{
// Store the value argument passed to this thread
pthread_t thd_id = (pthread_t)arg;
// Let us create a static variable to observe its changes
static int s = 0;
int t = 0;
// Change static and global variables
++s; ++g; ++t;
// Print the argument, static and global variables
printf("Thread ID: %lu, Static: %d, Global: %d, Local: %d\n", thd_id, ++s, ++g, ++t);
pthread_exit(NULL);
}
int main()
{
int i;
pthread_t tid;
// Let us create three threads
for (i = 0; i < 3; i++)
pthread_create(&tid, NULL, test_thread, (void *)tid);
pthread_exit(NULL);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.