id
int64
1
722k
file_path
stringlengths
8
177
funcs
stringlengths
1
35.8M
701
./wapiti/src/gradient.c
/* * Wapiti - A linear-chain CRF tool * * Copyright (c) 2009-2013 CNRS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <math.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "wapiti.h" #include "gradient.h" #include "model.h" #include "options.h" #include "progress.h" #include "sequence.h" #include "tools.h" #include "thread.h" #include "vmath.h" /* atm_inc: * Atomically increment the value pointed by [ptr] by [inc]. If ATM_ANSI is * defined this NOT atomic at all so caller must have to deal with this. */ #ifdef ATM_ANSI static inline void atm_inc(double *value, double inc) { *value += inc; } #else static inline void atm_inc(volatile double *value, double inc) { while (1) { volatile union { double d; uint64_t u; } old, new; old.d = *value; new.d = old.d + inc; uint64_t *ptr = (uint64_t *)value; if (__sync_bool_compare_and_swap(ptr, old.u, new.u)) break; } } #endif /****************************************************************************** * Maxent gradient computation * * Maxent or maximum entropy models are multi class logistic regression (see * [1]. Then can be viewed as a special class of CRFs models where the there * is no dependencies between the output labels. This mean that the * normalization is local to each nodes and can be done a lot more efficiently * as we do not have to perform the forward backward procedure. * * This code is used both when the maxent type of model is used and in other * modes if the sequence length is one or if there is no bigrams features. * * [1] A maximum entropy approach to natural language processing, A. Berger * and S. Della Pietra and V. Della Pietra, Computational Linguistics, * (22-1), March 1996. ******************************************************************************/ void grd_domaxent(grd_st_t *grd_st, const seq_t *seq) { const mdl_t *mdl = grd_st->mdl; const double *x = mdl->theta; const uint32_t T = seq->len; const uint32_t Y = mdl->nlbl; double *psi = grd_st->psi; double *g = grd_st->g; for (uint32_t t = 0; t < T; t++) { const pos_t *pos = &(seq->pos[t]); // We first compute for each Y the sum of weights of all // features actives in the sample: // Ψ(y,x^i) = \exp( ∑_k θ_k f_k(y,x^i) ) // Z_θ(x^i) = ∑_y Ψ(y,x^i) double Z = 0.0; for (uint32_t y = 0; y < Y; y++) psi[y] = 0.0; for (uint32_t n = 0; n < pos->ucnt; n++) { const double *wgh = x + mdl->uoff[pos->uobs[n]]; for (uint32_t y = 0; y < Y; y++) psi[y] += wgh[y]; } double lloss = psi[pos->lbl]; for (uint32_t y = 0; y < Y; y++) { psi[y] = (psi[y] == 0.0) ? 1.0 : exp(psi[y]); Z += psi[y]; } // Now, we can compute the gradient update, for each active // feature in the sample the update is the expectation over the // current model minus the expectation over the observed // distribution: // E_{q_θ}(x,y) - E_{p}(x,y) // and we can compute the expectation over the model with: // E_{q_θ}(x,y) = f_k(y,x^i) * ψ(y,x) / Z_θ(x) for (uint32_t y = 0; y < Y; y++) psi[y] /= Z; for (uint32_t n = 0; n < pos->ucnt; n++) { double *grd = g + mdl->uoff[pos->uobs[n]]; for (uint32_t y = 0; y < Y; y++) atm_inc(grd + y, psi[y]); atm_inc(grd + pos->lbl, -1.0); } // And finally the log-likelihood with: // L_θ(x^i,y^i) = log(Z_θ(x^i)) - log(ψ(y^i,x^i)) grd_st->lloss += log(Z) - lloss; } } /****************************************************************************** * Maximum entropy markov model gradient computation * * Maximum entropy markov models are similar to linear-chains CRFs but with * local normalization instead of global normalization (see [2]). This change * make the computation a lot more simpler as at training time the gradient * can be computed similarily to the maxent cases with the previous output * label observed. * * This mean that for bigram features we only have to consider the reference * label at previous position instead of all possible labels, so we don't have * to perform the forward backward. Bigrams features are handle in the same * way than unigrams features. * * [2] Maximum Entropy Markov Models for Information Extraction and * Segmentation, A. McCallum and D. Freitag and F. Pereira, 2000, * Proceedings of ICML 2000 , 591–598. Stanford, California. ******************************************************************************/ void grd_domemm(grd_st_t *grd_st, const seq_t *seq) { const mdl_t *mdl = grd_st->mdl; const double *x = mdl->theta; const uint32_t T = seq->len; const uint32_t Y = mdl->nlbl; double *psi = grd_st->psi; double *g = grd_st->g; for (uint32_t t = 0; t < T; t++) { const pos_t *pos = &(seq->pos[t]); // We first compute for each Y the sum of weights of all // features actives in the sample: // Ψ(y,x^i) = \exp( ∑_k θ_k f_k(y_t-1, y,x^i) ) // Z_θ(x^i) = ∑_y Ψ(y,x^i) // Bigram features rely on the gold label at previous position // for the markov dependency unlike in CRFs. double Z = 0.0; for (uint32_t y = 0; y < Y; y++) psi[y] = 0.0; for (uint32_t n = 0; n < pos->ucnt; n++) { const double *wgh = x + mdl->uoff[pos->uobs[n]]; for (uint32_t y = 0; y < Y; y++) psi[y] += wgh[y]; } if (t != 0) { const uint32_t yp = seq->pos[t - 1].lbl; const uint32_t d = yp * Y; for (uint32_t y = 0; y < Y; y++) { double sum = 0.0; for (uint32_t n = 0; n < pos->bcnt; n++) { const uint64_t o = pos->bobs[n]; sum += x[mdl->boff[o] + d + y]; } psi[y] += sum; } } double lloss = psi[pos->lbl]; for (uint32_t y = 0; y < Y; y++) { psi[y] = (psi[y] == 0.0) ? 1.0 : exp(psi[y]); Z += psi[y]; } // Now, we can compute the gradient update, for each active // feature in the sample the update is the expectation over the // current model minus the expectation over the observed // distribution: // E_{q_θ}(x,y) - E_{p}(x,y) // and we can compute the expectation over the model with: // E_{q_θ}(x,y) = f_k(y, y,x^i) * ψ(y,x) / Z_θ(x) for (uint32_t y = 0; y < Y; y++) psi[y] /= Z; for (uint32_t n = 0; n < pos->ucnt; n++) { double *grd = g + mdl->uoff[pos->uobs[n]]; for (uint32_t y = 0; y < Y; y++) atm_inc(grd + y, psi[y]); atm_inc(grd + pos->lbl, -1.0); } if (t != 0) { const uint32_t yp = seq->pos[t - 1].lbl; const uint32_t d = yp * Y; for (uint32_t n = 0; n < pos->bcnt; n++) { double *grd = g + mdl->boff[pos->bobs[n]] + d; for (uint32_t y = 0; y < Y; y++) atm_inc(grd + y, psi[y]); atm_inc(grd + pos->lbl, -1.0); } } // And finally the log-likelihood with: // L_θ(x^i,y^i) = log(Z_θ(x^i)) - log(ψ(y^i,x^i)) grd_st->lloss += log(Z) - lloss; } } /****************************************************************************** * Linear-chain CRF gradient computation * * This section is responsible for computing the gradient of the * log-likelihood function to optimize over a single sequence. * * There is two version of this code, one using dense matrix and one with * sparse matrix. The sparse version use the fact that for L1 regularized * trainers, the bigrams scores will be very sparse so there is a way to * reduce the amount of computation needed in the forward backward at the * price of a more complex implementation. Due to the fact that using a sparse * matrix have a cost, this implementation is slower on L2 regularized models * and on lighty L1-regularized models, this is why there is also a classical * dense version of the algorithm used for example by the L-BFGS trainer. * * The sparse matrix implementation is a bit tricky because we need to store * all values in sequences in order to use the vector exponential who gives * also a lot of performance improvement on vector able machine. * We need four arrays noted <val>, <off>, <idx>, and <yp>. For each positions * t, <off>[t] value indicate where the non-zero values for t starts in <val>. * The other arrays gives the y and yp indices of these values. The easier one * to retrieve is yp, the yp indice for value at <val>[<off>[t] + n] is stored * at the same position in <yp>. * The y are more difficult: the indice y are stored with n between <idx>[y-1] * and <idx>[y]. It may seems inefective but the matrix is indexed in the * other way, we go through the idx array, and for each y we get the yp and * values, so in practice it's very efficient. * * This can seem too complex but we have to keep in mind that Y are generally * very low and any sparse-matrix have overhead so we have to reduce it to the * minimum in order to get a real improvment. Dedicated library are optimized * for bigger matrix where the overhead is not a so important problem. * Another problem here is cache size. The optimization process will last most * of his time in this function so it have to be well optimized and we already * need a lot of memory for other data so we have to be carefull here if we * don't want to flush the cache all the time. Sparse matrix require less * memory than dense one only if we now in advance the number of non-zero * entries, which is not the case here, so we have to use a scheme which in * the worst case use as less as possible memory. ******************************************************************************/ /* grd_fldopsi: * We first have to compute the Ψ_t(y',y,x) weights defined as * Ψ_t(y',y,x) = \exp( ∑_k θ_k f_k(y',y,x_t) ) * So at position 't' in the sequence, for each couple (y',y) we have to sum * weights of all features. Only the observations present at this position * will have a non-nul weight so we can sum only on thoses. As we use only two * kind of features: unigram and bigram, we can rewrite this as * \exp ( ∑_k μ_k(y, x_t) f_k(y, x_t) * + ∑_k λ_k(y', y, x_t) f_k(y', y, x_t) ) * Where the first sum is over the unigrams features and the second is over * bigrams ones. * This allow us to compute Ψ efficiently in three steps * 1/ we sum the unigrams features weights by looping over actives * unigrams observations. (we compute this sum once and use it * for each value of y') * 2/ we add the bigrams features weights by looping over actives * bigrams observations (we don't have to do this for t=0 since * there is no bigrams here) * 3/ we take the component-wise exponential of the resulting matrix * (this can be done efficiently with vector maths) */ void grd_fldopsi(grd_st_t *grd_st, const seq_t *seq) { const mdl_t *mdl = grd_st->mdl; const double *x = mdl->theta; const uint32_t Y = mdl->nlbl; const uint32_t T = seq->len; double (*psi)[T][Y][Y] = (void *)grd_st->psi; for (uint32_t t = 0; t < T; t++) { const pos_t *pos = &(seq->pos[t]); for (uint32_t y = 0; y < Y; y++) { double sum = 0.0; for (uint32_t n = 0; n < pos->ucnt; n++) { const uint64_t o = pos->uobs[n]; sum += x[mdl->uoff[o] + y]; } for (uint32_t yp = 0; yp < Y; yp++) (*psi)[t][yp][y] = sum; } } for (uint32_t t = 1; t < T; t++) { const pos_t *pos = &(seq->pos[t]); for (uint32_t yp = 0, d = 0; yp < Y; yp++) { for (uint32_t y = 0; y < Y; y++, d++) { double sum = 0.0; for (uint32_t n = 0; n < pos->bcnt; n++) { const uint64_t o = pos->bobs[n]; sum += x[mdl->boff[o] + d]; } (*psi)[t][yp][y] += sum; } } } xvm_expma((double *)psi, (double *)psi, 0.0, (uint64_t)T * Y * Y); } /* grd_spdopsi: * For the sparse version, we keep the two sum separate so we will have * separate Ψ_t(y,x) and Ψ_t(y',y,x). The first one define a vector for * unigram at each position, and the second one a matrix for bigrams. This is * where the trick is as we will store Ψ_t(y',y,x) - 1. If the sum is nul, his * exponential will be 1.0 and so we have to store 0.0. As most of the sum * are expected to be nul the resulting matrix will be very sparse and we will * save computation in the forward-backward. * * So we compute Ψ differently here * 1/ we sum the unigrams features weights by looping over actives * unigrams observations and store them in |psiuni|. * 2/ we sum the bigrams features weights by looping over actives * bigrams observations (we don't have to do this for t=0 since * there is no bigrams here) and we store the non-nul one in the * sparse matrix. * 3/ we take the component-wise exponential of the unigrams vectors, * and the component-wise exponential of the sparse matrix minus * one. (here also this can be done efficiently with vector * maths) */ void grd_spdopsi(grd_st_t *grd_st, const seq_t *seq) { const mdl_t *mdl = grd_st->mdl; const double *x = mdl->theta; const uint32_t Y = mdl->nlbl; const uint32_t T = seq->len; double (*psiuni)[T][Y] = (void *)grd_st->psiuni; double *psival = grd_st->psi; uint32_t *psiyp = grd_st->psiyp; uint32_t (*psiidx)[T][Y] = (void *)grd_st->psiidx; uint32_t *psioff = grd_st->psioff; for (uint32_t t = 0; t < T; t++) { const pos_t *pos = &(seq->pos[t]); for (uint32_t y = 0; y < Y; y++) { double sum = 0.0; for (uint32_t n = 0; n < pos->ucnt; n++) { const uint64_t o = pos->uobs[n]; sum += x[mdl->uoff[o] + y]; } (*psiuni)[t][y] = sum; } } uint32_t off = 0; for (uint32_t t = 1; t < T; t++) { const pos_t *pos = &(seq->pos[t]); psioff[t] = off; for (uint32_t y = 0, nnz = 0; y < Y; y++) { for (uint32_t yp = 0; yp < Y; yp++) { double sum = 0.0; for (uint32_t n = 0; n < pos->bcnt; n++) { const uint64_t o = pos->bobs[n]; sum += x[mdl->boff[o] + yp * Y + y]; } if (sum == 0.0) continue; psiyp [off] = yp; psival[off] = sum; nnz++, off++; } (*psiidx)[t][y] = nnz; } } xvm_expma((double *)psiuni, (double *)psiuni, 0.0, (uint64_t)T * Y); xvm_expma((double *)psival, (double *)psival, 1.0, off); } /* grd_flfwdbwd: * Now, we go to the forward-backward algorithm. As this part of the code rely * on a lot of recursive sums and products of exponentials, we have to take * care of numerical problems. * First the forward recursion * | α_1(y) = Ψ_1(y,x) * | α_t(y) = ∑_{y'} α_{t-1}(y') * Ψ_t(y',y,x) * Next come the backward recursion which is very similar * | β_T(y') = 1 * | β_t(y') = ∑_y β_{t+1}(y) * Ψ_{t+1}(y',y,x) * The numerical problems can appear here. To solve them we will scale the α_t * and β_t vectors so they sum to 1 but we have to keep the scaling coeficient * as we will need them later. * Now, we have to compute the nomalization factor. But, due to the scaling * performed during the forward-backward recursions, we have to compute it at * each positions and separately for unigrams and bigrams using * for unigrams: Z_θ(t) = ∑_y α_t(y) β_t(y) * for bigrams: Z_θ(t) = ∑_y α_t(y) β_t(y) / α-scale_t * with α-scale_t the scaling factor used for the α vector at position t * in the forward recursion. */ void grd_flfwdbwd(grd_st_t *grd_st, const seq_t *seq) { const mdl_t *mdl = grd_st->mdl; const uint64_t Y = mdl->nlbl; const uint32_t T = seq->len; const double (*psi)[T][Y][Y] = (void *)grd_st->psi; double (*alpha)[T][Y] = (void *)grd_st->alpha; double (*beta )[T][Y] = (void *)grd_st->beta; double *scale = grd_st->scale; double *unorm = grd_st->unorm; double *bnorm = grd_st->bnorm; for (uint32_t y = 0; y < Y; y++) (*alpha)[0][y] = (*psi)[0][0][y]; scale[0] = xvm_unit((*alpha)[0], (*alpha)[0], Y); for (uint32_t t = 1; t < grd_st->last + 1; t++) { for (uint32_t y = 0; y < Y; y++) { double sum = 0.0; for (uint32_t yp = 0; yp < Y; yp++) sum += (*alpha)[t - 1][yp] * (*psi)[t][yp][y]; (*alpha)[t][y] = sum; } scale[t] = xvm_unit((*alpha)[t], (*alpha)[t], Y); } for (uint32_t yp = 0; yp < Y; yp++) (*beta)[T - 1][yp] = 1.0 / Y; for (uint32_t t = T - 1; t > grd_st->first; t--) { for (uint32_t yp = 0; yp < Y; yp++) { double sum = 0.0; for (uint32_t y = 0; y < Y; y++) sum += (*beta)[t][y] * (*psi)[t][yp][y]; (*beta)[t - 1][yp] = sum; } xvm_unit((*beta)[t - 1], (*beta)[t - 1], Y); } for (uint32_t t = 0; t < T; t++) { double z = 0.0; for (uint32_t y = 0; y < Y; y++) z += (*alpha)[t][y] * (*beta)[t][y]; unorm[t] = 1.0 / z; bnorm[t] = scale[t] / z; } } /* grd_spfwdbwd: * And the sparse version which is a bit more cmoplicated but follow the same * general path. First the forward recursion * | α_1(y) = Ψ_1(y,x) * | α_t(y) = Ψ_t(y,x) * ( ∑_{y'} α_{t-1}(y') * + ∑_{y'} α_{t-1}(y') * (Ψ_t(y',y,x) - 1) ) * The inner part contains two sums, the first one will be 1.0 as we scale the * α vectors, and the second is a sparse matrix multiplication who need less * than |Y|x|Y| multiplication if the matrix is really sparse, so we will gain * here. * Next come the backward recursion which is very similar * | β_T(y') = 1 * | β_t(y') = ∑_y v_{t+1}(y) + ∑_y v_{t+1}(y) * (Ψ_{t+1}(y',y,x) - 1) * with * v_{t+1}(y) = β_{t+1}(y) * Ψ_{t+1}(y,x) * And here also we reduce the number of multiplication if the matrix is * really sparse. */ void grd_spfwdbwd(grd_st_t *grd_st, const seq_t *seq) { const mdl_t *mdl = grd_st->mdl; const uint32_t Y = mdl->nlbl; const uint32_t T = seq->len; const double (*psiuni)[T][Y] = (void *)grd_st->psiuni; const double *psival = grd_st->psi; const uint32_t *psiyp = grd_st->psiyp; const uint32_t (*psiidx)[T][Y] = (void *)grd_st->psiidx; const uint32_t *psioff = grd_st->psioff; double (*alpha)[T][Y] = (void *)grd_st->alpha; double (*beta )[T][Y] = (void *)grd_st->beta; double *scale = grd_st->scale; double *unorm = grd_st->unorm; double *bnorm = grd_st->bnorm; for (uint32_t y = 0; y < Y; y++) (*alpha)[0][y] = (*psiuni)[0][y]; scale[0] = xvm_unit((*alpha)[0], (*alpha)[0], Y); for (uint32_t t = 1; t < grd_st->last + 1; t++) { for (uint32_t y = 0; y < Y; y++) (*alpha)[t][y] = 1.0; const uint32_t off = psioff[t]; for (uint32_t n = 0, y = 0; n < (*psiidx)[t][Y - 1]; ) { while (n >= (*psiidx)[t][y]) y++; while (n < (*psiidx)[t][y]) { const uint32_t yp = psiyp [off + n]; const double v = psival[off + n]; (*alpha)[t][y] += (*alpha)[t - 1][yp] * v; n++; } } for (uint32_t y = 0; y < Y; y++) (*alpha)[t][y] *= (*psiuni)[t][y]; scale[t] = xvm_unit((*alpha)[t], (*alpha)[t], Y); } for (uint32_t yp = 0; yp < Y; yp++) (*beta)[T - 1][yp] = 1.0 / Y; for (uint32_t t = T - 1; t > grd_st->first; t--) { double sum = 0.0, tmp[Y]; for (uint32_t y = 0; y < Y; y++) { tmp[y] = (*beta)[t][y] * (*psiuni)[t][y]; sum += tmp[y]; } for (uint32_t y = 0; y < Y; y++) (*beta)[t - 1][y] = sum; const uint32_t off = psioff[t]; for (uint32_t n = 0, y = 0; n < (*psiidx)[t][Y - 1]; ) { while (n >= (*psiidx)[t][y]) y++; while (n < (*psiidx)[t][y]) { const uint32_t yp = psiyp [off + n]; const double v = psival[off + n]; (*beta)[t - 1][yp] += v * tmp[y]; n++; } } xvm_unit((*beta)[t - 1], (*beta)[t - 1], Y); } for (uint32_t t = 0; t < T; t++) { double z = 0.0; for (uint32_t y = 0; y < Y; y++) z += (*alpha)[t][y] * (*beta)[t][y]; unorm[t] = 1.0 / z; bnorm[t] = scale[t] / z; } } /* grd_flupgrad: * Now, we have all we need to compute the gradient of the negative log- * likelihood * ∂-L(θ) * ------ = ∑_t ∑_{(y',y)} f_k(y',y,x_t) p_θ(y_{t-1}=y',y_t=y|x) * ∂θ_k - ∑_t f_k(y_{t-1},y_t,x_t) * * The first term is the expectation of f_k under the model distribution and * the second one is the expectation of f_k under the empirical distribution. * * The second is very simple to compute as we just have to sum over the * actives observations in the sequence and will be done by the grd_subemp. * The first one is more tricky as it involve computing the probability p_θ. * This is where we use all the previous computations. Again we separate the * computations for unigrams and bigrams here. * * These probabilities are given by * p_θ(y_t=y|x) = α_t(y)β_t(y) / Z_θ * p_θ(y_{t-1}=y',y_t=y|x) = α_{t-1}(y') Ψ_t(y',y,x) β_t(y) / Z_θ * but we have to remember that, since we have scaled the α and β, we have to * use the local normalization constants. * * We must also take care of not clearing previous value of the gradient * vector but just adding the contribution of this sequence. This allow to * compute it easily the gradient over more than one sequence. */ void grd_flupgrad(grd_st_t *grd_st, const seq_t *seq) { const mdl_t *mdl = grd_st->mdl; const uint32_t Y = mdl->nlbl; const uint32_t T = seq->len; const double (*psi )[T][Y][Y] = (void *)grd_st->psi; const double (*alpha)[T][Y] = (void *)grd_st->alpha; const double (*beta )[T][Y] = (void *)grd_st->beta; const double *unorm = grd_st->unorm; const double *bnorm = grd_st->bnorm; double *g = grd_st->g; for (uint32_t t = 0; t < T; t++) { const pos_t *pos = &(seq->pos[t]); for (uint32_t y = 0; y < Y; y++) { double e = (*alpha)[t][y] * (*beta)[t][y] * unorm[t]; for (uint32_t n = 0; n < pos->ucnt; n++) { const uint64_t o = pos->uobs[n]; atm_inc(g + mdl->uoff[o] + y, e); } } } for (uint32_t t = 1; t < T; t++) { const pos_t *pos = &(seq->pos[t]); for (uint32_t yp = 0, d = 0; yp < Y; yp++) { for (uint32_t y = 0; y < Y; y++, d++) { double e = (*alpha)[t - 1][yp] * (*beta)[t][y] * (*psi)[t][yp][y] * bnorm[t]; for (uint32_t n = 0; n < pos->bcnt; n++) { const uint64_t o = pos->bobs[n]; atm_inc(g + mdl->boff[o] + d, e); } } } } } /* grd_spupgrad: * The sparse matrix make things a bit more complicated here as we cannot * directly multiply with the original Ψ_t(y',y,x) because we have split it * two components and the second one is sparse, so we have to make a quite * complex workaround to fix that. We have to explicitly build the expectation * matrix. We first fill it with the unigram component and next multiply it * with the bigram one. */ void grd_spupgrad(grd_st_t *grd_st, const seq_t *seq) { const mdl_t *mdl = grd_st->mdl; const uint32_t Y = mdl->nlbl; const uint32_t T = seq->len; const double (*psiuni)[T][Y] = (void *)grd_st->psiuni; const double *psival = grd_st->psi; const uint32_t *psiyp = grd_st->psiyp; const uint32_t (*psiidx)[T][Y] = (void *)grd_st->psiidx; const uint32_t *psioff = grd_st->psioff; const double (*alpha)[T][Y] = (void *)grd_st->alpha; const double (*beta )[T][Y] = (void *)grd_st->beta; const double *unorm = grd_st->unorm; const double *bnorm = grd_st->bnorm; double *g = grd_st->g; for (uint32_t t = 0; t < T; t++) { const pos_t *pos = &(seq->pos[t]); for (uint32_t y = 0; y < Y; y++) { double e = (*alpha)[t][y] * (*beta)[t][y] * unorm[t]; for (uint32_t n = 0; n < pos->ucnt; n++) { const uint64_t o = pos->uobs[n]; atm_inc(g + mdl->uoff[o] + y, e); } } } for (uint32_t t = 1; t < T; t++) { const pos_t *pos = &(seq->pos[t]); // We build the expectation matrix double e[Y][Y]; for (uint32_t yp = 0; yp < Y; yp++) for (uint32_t y = 0; y < Y; y++) e[yp][y] = (*alpha)[t - 1][yp] * (*beta)[t][y] * (*psiuni)[t][y] * bnorm[t]; const uint32_t off = psioff[t]; for (uint32_t n = 0, y = 0; n < (*psiidx)[t][Y - 1]; ) { while (n >= (*psiidx)[t][y]) y++; while (n < (*psiidx)[t][y]) { const uint32_t yp = psiyp [off + n]; const double v = psival[off + n]; e[yp][y] += e[yp][y] * v; n++; } } // Add the expectation over the model distribution for (uint32_t yp = 0, d = 0; yp < Y; yp++) { for (uint32_t y = 0; y < Y; y++, d++) { for (uint32_t n = 0; n < pos->bcnt; n++) { const uint64_t o = pos->bobs[n]; atm_inc(g + mdl->boff[o] + d, e[yp][y]); } } } } } /* grd_subemp: * Substract from the gradient, the expectation over the empirical * distribution. This is the second step of the gradient computation shared * by the non-sparse and sparse version. */ void grd_subemp(grd_st_t *grd_st, const seq_t *seq) { const mdl_t *mdl = grd_st->mdl; const uint32_t Y = mdl->nlbl; const uint32_t T = seq->len; double *g = grd_st->g; for (uint32_t t = 0; t < T; t++) { const pos_t *pos = &(seq->pos[t]); const uint32_t y = seq->pos[t].lbl; for (uint32_t n = 0; n < pos->ucnt; n++) atm_inc(g + mdl->uoff[pos->uobs[n]] + y, -1.0); } for (uint32_t t = 1; t < T; t++) { const pos_t *pos = &(seq->pos[t]); const uint32_t yp = seq->pos[t - 1].lbl; const uint32_t y = seq->pos[t ].lbl; const uint32_t d = yp * Y + y; for (uint32_t n = 0; n < pos->bcnt; n++) atm_inc(g + mdl->boff[pos->bobs[n]] + d, -1.0); } } /* grd_logloss: * And the final touch, the computation of the negative log-likelihood * -L(θ) = log(Z_θ) - ∑_t ∑_k θ_k f_k(y_{t-1}, y_t, x_t) * * The numerical problems show again here as we cannot compute the Z_θ * directly for the same reason we have done scaling. Fortunately, there is a * way to directly compute his logarithm * log(Z_θ) = log( ∑_y α_t(y) β_t(y) ) * - ∑_{i=1..t} log(α-scale_i) * - ∑_{i=t..T} log(β-scale_i) * for any value of t. * * So we can compute it at any position in the sequence but the last one is * easier as the value of β_T(y) and β-scale_T are constant and cancel out. * This is why we have just keep the α-scale_t values. * * Now, we have the first term of -L(θ). We have now to substract the second * one. As we have done for the computation of Ψ, we separate the sum over K * in two sums, one for unigrams and one for bigrams. And, as here also the * weights will be non-nul only for observations present in the sequence, we * sum only over these ones. */ void grd_logloss(grd_st_t *grd_st, const seq_t *seq) { const mdl_t *mdl = grd_st->mdl; const double *x = mdl->theta; const uint32_t Y = mdl->nlbl; const uint32_t T = seq->len; const double (*alpha)[T][Y] = (void *)grd_st->alpha; const double *scale = grd_st->scale; double logz = 0.0; for (uint32_t y = 0; y < Y; y++) logz += (*alpha)[T - 1][y]; logz = log(logz); for (uint32_t t = 0; t < T; t++) logz -= log(scale[t]); double lloss = logz; for (uint32_t t = 0; t < T; t++) { const pos_t *pos = &(seq->pos[t]); const uint32_t y = seq->pos[t].lbl; for (uint32_t n = 0; n < pos->ucnt; n++) lloss -= x[mdl->uoff[pos->uobs[n]] + y]; } for (uint32_t t = 1; t < T; t++) { const pos_t *pos = &(seq->pos[t]); const uint32_t yp = seq->pos[t - 1].lbl; const uint32_t y = seq->pos[t ].lbl; const uint32_t d = yp * Y + y; for (uint32_t n = 0; n < pos->bcnt; n++) lloss -= x[mdl->boff[pos->bobs[n]] + d]; } grd_st->lloss += lloss; } /* grd_docrf: * This function compute the gradient and value of the negative log-likelihood * of the model over a single training sequence. * * This function will not clear the gradient before computation, but instead * just accumulate the values for the given sequence in it. This allow to * easily compute the gradient over a set of sequences. */ void grd_docrf(grd_st_t *grd_st, const seq_t *seq) { const mdl_t *mdl = grd_st->mdl; grd_st->first = 0; grd_st->last = seq->len - 1; if (!mdl->opt->sparse) { grd_fldopsi(grd_st, seq); grd_flfwdbwd(grd_st, seq); grd_flupgrad(grd_st, seq); } else { grd_spdopsi(grd_st, seq); grd_spfwdbwd(grd_st, seq); grd_spupgrad(grd_st, seq); } grd_subemp(grd_st, seq); grd_logloss(grd_st, seq); } /****************************************************************************** * Dataset gradient computation * * This section is responsible for computing the gradient of the * log-likelihood function to optimize over the full training set. * * The gradient computation is multi-threaded, you first have to call the * function 'grd_setup' to prepare the workers pool, and next you can use * 'grd_gradient' to ask for the full gradient as many time as you want. Each * time the gradient is computed over the full training set, using the curent * value of the parameters and applying the regularization. If need the * pseudo-gradient can also be computed. When you have done, you have to call * 'grd_cleanup' to free the allocated memory. * * This require an additional vector of size <nftr> per thread after the * first, so it can take a lot of memory to compute big models on a lot of * threads. It is strongly discouraged to ask for more threads than you have * cores, or to more thread than you have memory to hold vectors. ******************************************************************************/ /* grd_stcheck: * Check that enough memory is allocated in the gradient object so that the * linear-chain codepath can be computed for a sequence of the given length. */ void grd_stcheck(grd_st_t *grd_st, uint32_t len) { // Check if user ask for clearing the state tracker or if he requested a // bigger tracker. In this case we have to free the previous allocated // memory. if (len == 0 || (len > grd_st->len && grd_st->len != 0)) { if (grd_st->mdl->opt->sparse) { xvm_free(grd_st->psiuni); grd_st->psiuni = NULL; free(grd_st->psiyp); grd_st->psiyp = NULL; free(grd_st->psiidx); grd_st->psiidx = NULL; free(grd_st->psioff); grd_st->psioff = NULL; } xvm_free(grd_st->psi); grd_st->psi = NULL; xvm_free(grd_st->alpha); grd_st->alpha = NULL; xvm_free(grd_st->beta); grd_st->beta = NULL; xvm_free(grd_st->unorm); grd_st->unorm = NULL; xvm_free(grd_st->bnorm); grd_st->bnorm = NULL; xvm_free(grd_st->scale); grd_st->scale = NULL; grd_st->len = 0; } if (len == 0 || len <= grd_st->len) return; // If we are here, we have to allocate a new state. This is simple, we // just have to take care of the special case for sparse mode. const uint32_t Y = grd_st->mdl->nlbl; const uint32_t T = len; grd_st->psi = xvm_new(T * Y * Y); grd_st->alpha = xvm_new(T * Y); grd_st->beta = xvm_new(T * Y); grd_st->scale = xvm_new(T); grd_st->unorm = xvm_new(T); grd_st->bnorm = xvm_new(T); if (grd_st->mdl->opt->sparse) { grd_st->psiuni = xvm_new(T * Y); grd_st->psiyp = xmalloc(sizeof(uint32_t) * T * Y * Y); grd_st->psiidx = xmalloc(sizeof(uint32_t) * T * Y); grd_st->psioff = xmalloc(sizeof(uint32_t) * T); } grd_st->len = len; } /* grd_stnew: * Allocation memory for gradient computation state. This allocate memory for * the longest sequence present in the data set. */ grd_st_t *grd_stnew(mdl_t *mdl, double *g) { grd_st_t *grd_st = xmalloc(sizeof(grd_st_t)); grd_st->mdl = mdl; grd_st->len = 0; grd_st->g = g; grd_st->psi = NULL; grd_st->psiuni = NULL; grd_st->psiyp = NULL; grd_st->psiidx = NULL; grd_st->psioff = NULL; grd_st->alpha = NULL; grd_st->beta = NULL; grd_st->unorm = NULL; grd_st->bnorm = NULL; grd_st->scale = NULL; return grd_st; } /* grd_stfree: * Free all memory used by gradient computation. */ void grd_stfree(grd_st_t *grd_st) { grd_stcheck(grd_st, 0); free(grd_st); } /* grd_dospl: * Compute the gradient of a single sample choosing between the maxent * optimised codepath and classical one depending of the sample. */ void grd_dospl(grd_st_t *grd_st, const seq_t *seq) { grd_stcheck(grd_st, seq->len); if (seq->len == 1 || grd_st->mdl->reader->nbi == 0) grd_domaxent(grd_st, seq); else if (grd_st->mdl->type == 0) grd_domaxent(grd_st, seq); else if (grd_st->mdl->type == 1) grd_domemm(grd_st, seq); else grd_docrf(grd_st, seq); } /* grd_new: * Allocate a new parallel gradient computer. Return a grd_t object who can * compute gradient over the full data set and store it in the vector <g>. */ grd_t *grd_new(mdl_t *mdl, double *g) { const uint32_t W = mdl->opt->nthread; grd_t *grd = xmalloc(sizeof(grd_t)); grd->mdl = mdl; grd->grd_st = xmalloc(sizeof(grd_st_t *) * W); #ifdef ATM_ANSI grd->grd_st[0] = grd_stnew(mdl, g); for (uint32_t w = 1; w < W; w++) grd->grd_st[w] = grd_stnew(mdl, xvm_new(mdl->nftr)); #else for (uint32_t w = 0; w < W; w++) grd->grd_st[w] = grd_stnew(mdl, g); #endif return grd; } /* grd_free: * Free all memory allocated for the given gradient computer object. */ void grd_free(grd_t *grd) { const uint32_t W = grd->mdl->opt->nthread; #ifdef ATM_ANSI for (uint32_t w = 1; w < W; w++) xvm_free(grd->grd_st[w]->g); #endif for (uint32_t w = 0; w < W; w++) grd_stfree(grd->grd_st[w]); free(grd->grd_st); free(grd); } /* grd_worker: * This is a simple function who compute the gradient over a subset of the * training set. It is mean to be called by the thread spawner in order to * compute the gradient over the full training set. */ static void grd_worker(job_t *job, uint32_t id, uint32_t cnt, grd_st_t *grd_st) { unused(id && cnt); mdl_t *mdl = grd_st->mdl; const dat_t *dat = mdl->train; // We first cleanup the gradient and value as our parent don't do it (it // is better to do this also in parallel) grd_st->lloss = 0.0; #ifdef ATM_ANSI const uint64_t F = mdl->nftr; for (uint64_t f = 0; f < F; f++) grd_st->g[f] = 0.0; #endif // Now all is ready, we can process our sequences and accumulate the // gradient and inverse log-likelihood uint32_t count, pos; while (mth_getjob(job, &count, &pos)) { for (uint32_t s = pos; !uit_stop && s < pos + count; s++) grd_dospl(grd_st, dat->seq[s]); if (uit_stop) break; } } /* grd_gradient: * Compute the gradient and value of the negative log-likelihood of the model * at current point. The computation is done in parallel taking profit of * the fact that the gradient over the full training set is just the sum of * the gradient of each sequence. */ double grd_gradient(grd_t *grd) { mdl_t *mdl = grd->mdl; const double *x = mdl->theta; const uint64_t F = mdl->nftr; const uint32_t W = mdl->opt->nthread; double *g = grd->grd_st[0]->g; #ifndef ATM_ANSI for (uint64_t f = 0; f < F; f++) g[f] = 0.0; #endif // All is ready to compute the gradient, we spawn the threads of // workers, each one working on a part of the data. As the gradient and // log-likelihood are additive, computing the final values will be // trivial. mth_spawn((func_t *)grd_worker, W, (void **)grd->grd_st, mdl->train->nseq, mdl->opt->jobsize); if (uit_stop) return -1.0; // All computations are done, it just remain to add all the gradients // and negative log-likelihood from all the workers. double fx = grd->grd_st[0]->lloss; for (uint32_t w = 1; w < W; w++) fx += grd->grd_st[w]->lloss; #ifdef ATM_ANSI for (uint32_t w = 1; w < W; w++) for (uint64_t f = 0; f < F; f++) g[f] += grd->grd_st[w]->g[f]; #endif // If needed we clip the gradient: setting to 0.0 all coordinates where // the function is 0.0. if (mdl->opt->lbfgs.clip == true) for (uint64_t f = 0; f < F; f++) if (x[f] == 0.0) g[f] = 0.0; // Now we can apply the elastic-net penalty. Depending of the values of // rho1 and rho2, this can in fact be a classical L1 or L2 penalty. const double rho1 = mdl->opt->rho1; const double rho2 = mdl->opt->rho2; double nl1 = 0.0, nl2 = 0.0; for (uint64_t f = 0; f < F; f++) { const double v = x[f]; g[f] += rho2 * v; nl1 += fabs(v); nl2 += v * v; } fx += nl1 * rho1 + nl2 * rho2 / 2.0; return fx; }
702
./wapiti/src/options.c
/* * Wapiti - A linear-chain CRF tool * * Copyright (c) 2009-2013 CNRS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <inttypes.h> #include <limits.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "wapiti.h" #include "tools.h" #include "options.h" #include "vmath.h" /****************************************************************************** * Command line parsing * * This module handle command line parsing and put all things defined by the * user in a special structure in order to make them accessible to the * remaining of the program. ******************************************************************************/ /* opt_help: * Just display the help message describing modes and switch. */ static void opt_help(const char *pname) { static const char msg[] = "Global switchs:\n" "\t-h | --help display this help message\n" "\t | --version display version information\n" "\n" "Train mode:\n" " %1$s train [options] [input data] [model file]\n" "\t | --me force maxent mode\n" "\t-T | --type STRING type of model to train\n" "\t-a | --algo STRING training algorithm to use\n" "\t-p | --pattern FILE patterns for extracting features\n" "\t-m | --model FILE model file to preload\n" "\t-d | --devel FILE development dataset\n" "\t | --rstate FILE optimizer state to restore\n" "\t | --sstate FILE optimizer state to save\n" "\t-c | --compact compact model after training\n" "\t-t | --nthread INT number of worker threads\n" "\t-j | --jobsize INT job size for worker threads\n" "\t-s | --sparse enable sparse forward/backward\n" "\t-i | --maxiter INT maximum number of iterations\n" "\t-1 | --rho1 FLOAT l1 penalty parameter\n" "\t-2 | --rho2 FLOAT l2 penalty parameter\n" "\t-o | --objwin INT convergence window size\n" "\t-w | --stopwin INT stop window size\n" "\t-e | --stopeps FLOAT stop epsilon value\n" "\t | --clip (l-bfgs) clip gradient\n" "\t | --histsz INT (l-bfgs) history size\n" "\t | --maxls INT (l-bfgs) max linesearch iters\n" "\t | --eta0 FLOAT (sgd-l1) learning rate\n" "\t | --alpha FLOAT (sgd-l1) exp decay parameter\n" "\t | --kappa FLOAT (bcd) stability parameter\n" "\t | --stpmin FLOAT (rprop) minimum step size\n" "\t | --stpmax FLOAT (rprop) maximum step size\n" "\t | --stpinc FLOAT (rprop) step increment factor\n" "\t | --stpdec FLOAT (rprop) step decrement factor\n" "\t | --cutoff (rprop) alternate projection\n" "\n" "Label mode:\n" " %1$s label [options] [input data] [output data]\n" "\t | --me force maxent mode\n" "\t-m | --model FILE model file to load\n" "\t-l | --label output only labels\n" "\t-c | --check input is already labeled\n" "\t-s | --score add scores to output\n" "\t-p | --post label using posteriors\n" "\t-n | --nbest INT output n-best list\n" "\t | --force use forced decoding\n" "\n" "Dump mode\n" " %1$s dump [options] [input model] [output text]\n" "\t-p | --prec INT set weights precision\n" "\t | --all also output 0 weights\n" "\n" "Update mode\n" " %1$s update [options] [patch file] [output model]\n" "\t-m | --model FILE model file to load\n" "\t-c | --compact compact model after training\n" ; fprintf(stderr, msg, pname); } /* opt_defaults: * Default values for all parameters of the model. */ const opt_t opt_defaults = { .mode = -1, .input = NULL, .output = NULL, .type = "crf", .maxent = false, .algo = "l-bfgs", .pattern = NULL, .model = NULL, .devel = NULL, .rstate = NULL, .sstate = NULL, .compact = false, .sparse = false, .nthread = 1, .jobsize = 64, .maxiter = 0, .rho1 = 0.5, .rho2 = 0.0001, .objwin = 5, .stopwin = 5, .stopeps = 0.02, .lbfgs = {.clip = false, .histsz = 5, .maxls = 40}, .sgdl1 = {.eta0 = 0.8, .alpha = 0.85}, .bcd = {.kappa = 1.5}, .rprop = {.stpmin = 1e-8, .stpmax = 50.0, .stpinc = 1.2, .stpdec = 0.5, .cutoff = false}, .label = false, .check = false, .outsc = false, .lblpost = false, .nbest = 1, .force = false, .prec = 5, .all = false, }; /* opt_switch: * Define available switchs for the different modes in a readable way for the * command line argument parser. */ struct { int mode; char *dshort; char *dlong; char kind; size_t offset; } opt_switch[] = { {0, "-T", "--type", 'S', offsetof(opt_t, type )}, {0, "##", "--me", 'B', offsetof(opt_t, maxent )}, {0, "-a", "--algo", 'S', offsetof(opt_t, algo )}, {0, "-p", "--pattern", 'S', offsetof(opt_t, pattern )}, {0, "-m", "--model", 'S', offsetof(opt_t, model )}, {0, "-d", "--devel", 'S', offsetof(opt_t, devel )}, {0, "##", "--rstate", 'S', offsetof(opt_t, rstate )}, {0, "##", "--sstate", 'S', offsetof(opt_t, sstate )}, {0, "-c", "--compact", 'B', offsetof(opt_t, compact )}, {0, "-s", "--sparse", 'B', offsetof(opt_t, sparse )}, {0, "-t", "--nthread", 'U', offsetof(opt_t, nthread )}, {0, "-j", "--jobsize", 'U', offsetof(opt_t, jobsize )}, {0, "-i", "--maxiter", 'U', offsetof(opt_t, maxiter )}, {0, "-1", "--rho1", 'F', offsetof(opt_t, rho1 )}, {0, "-2", "--rho2", 'F', offsetof(opt_t, rho2 )}, {0, "-o", "--objwin", 'U', offsetof(opt_t, objwin )}, {0, "-w", "--stopwin", 'U', offsetof(opt_t, stopwin )}, {0, "-e", "--stopeps", 'F', offsetof(opt_t, stopeps )}, {0, "##", "--clip", 'B', offsetof(opt_t, lbfgs.clip )}, {0, "##", "--histsz", 'U', offsetof(opt_t, lbfgs.histsz)}, {0, "##", "--maxls", 'U', offsetof(opt_t, lbfgs.maxls )}, {0, "##", "--eta0", 'F', offsetof(opt_t, sgdl1.eta0 )}, {0," ##", "--alpha", 'F', offsetof(opt_t, sgdl1.alpha )}, {0, "##", "--kappa", 'F', offsetof(opt_t, bcd.kappa )}, {0, "##", "--stpmin", 'F', offsetof(opt_t, rprop.stpmin)}, {0, "##", "--stpmax", 'F', offsetof(opt_t, rprop.stpmax)}, {0, "##", "--stpinc", 'F', offsetof(opt_t, rprop.stpinc)}, {0, "##", "--stpdec", 'F', offsetof(opt_t, rprop.stpdec)}, {0, "##", "--cutoff", 'B', offsetof(opt_t, rprop.cutoff)}, {1, "##", "--me", 'B', offsetof(opt_t, maxent )}, {1, "-m", "--model", 'S', offsetof(opt_t, model )}, {1, "-l", "--label", 'B', offsetof(opt_t, label )}, {1, "-c", "--check", 'B', offsetof(opt_t, check )}, {1, "-s", "--score", 'B', offsetof(opt_t, outsc )}, {1, "-p", "--post", 'B', offsetof(opt_t, lblpost )}, {1, "-n", "--nbest", 'U', offsetof(opt_t, nbest )}, {1, "##", "--force", 'B', offsetof(opt_t, force )}, {2, "-p", "--prec", 'U', offsetof(opt_t, prec )}, {2, "##", "--all", 'B', offsetof(opt_t, all )}, {3, "-m", "--model", 'S', offsetof(opt_t, model )}, {3, "-c", "--compact", 'B', offsetof(opt_t, compact )}, {-1, NULL, NULL, '\0', 0} }; /* argparse: * This is the main function for command line parsing. It use the previous * table to known how to interpret the switchs and store values in the opt_t * structure. */ void opt_parse(int argc, char *argv[argc], opt_t *opt) { static const char *err_badval = "invalid value for switch '%s'"; const char *pname = argv[0]; argc--, argv++; if (argc == 0) { opt_help(pname); fatal("no mode specified"); } // First special handling for help and version if (!strcmp(argv[0], "-h") || !strcmp(argv[0], "--help")) { opt_help(pname); exit(EXIT_FAILURE); } else if (!strcmp(argv[0], "--version")) { fprintf(stderr, "Wapiti v" VERSION "\n"); fprintf(stderr, " Optimization mode: %s\n", xvm_mode()); exit(EXIT_SUCCESS); } // Get the mode to use if (!strcmp(argv[0], "t") || !strcmp(argv[0], "train")) { opt->mode = 0; } else if (!strcmp(argv[0], "l") || !strcmp(argv[0], "label")) { opt->mode = 1; } else if (!strcmp(argv[0], "d") || !strcmp(argv[0], "dump")) { opt->mode = 2; } else if (!strcmp(argv[0], "u") || !strcmp(argv[0], "update")) { opt->mode = 3; } else { fatal("unknown mode <%s>", argv[0]); } argc--, argv++; // Parse remaining arguments opt->input = NULL; opt->output = NULL; while (argc > 0) { const char *arg = argv[0]; uint32_t idx; // Check if this argument is a filename or an option if (arg[0] != '-') { if (opt->input == NULL) opt->input = argv[0]; else if (opt->output == NULL) opt->output = argv[0]; else fatal("too much input files on command line"); argc--, argv++; continue; } // Search the current switch in the table or fail if it cannot // be found. for (idx = 0; opt_switch[idx].mode != -1; idx++) { if (opt_switch[idx].mode != opt->mode) continue; if (!strcmp(arg, opt_switch[idx].dshort)) break; if (!strcmp(arg, opt_switch[idx].dlong)) break; } if (opt_switch[idx].mode == -1) fatal("unknown option '%s'", arg); // Decode the argument and store it in the structure if (opt_switch[idx].kind != 'B' && argc < 2) fatal("missing argument for switch '%s'", arg); void *ptr = (void *)((char *)opt + opt_switch[idx].offset); switch (opt_switch[idx].kind) { case 'S': *((char **)ptr) = argv[1]; argc -= 2, argv += 2; break; case 'U': if (sscanf(argv[1], "%"SCNu32, (uint32_t *)ptr) != 1) fatal(err_badval, arg); argc -= 2, argv += 2; break; case 'F': { double tmp; if (sscanf(argv[1], "%lf", &tmp) != 1) fatal(err_badval, arg); *((double *)ptr) = tmp; argc -= 2, argv += 2; break; } case 'B': *((bool *)ptr) = true; argc--, argv++; break; } } // Small trick for the maxiter switch if (opt->maxiter == 0) opt->maxiter = INT_MAX; // Check that all options are valid #define argchecksub(name, test) \ if (!(test)) \ fatal("invalid value for <"name">"); argchecksub("--thread", opt->nthread > 0 ); argchecksub("--jobsize", opt->jobsize > 0 ); argchecksub("--rho1", opt->rho1 >= 0.0); argchecksub("--rho2", opt->rho2 >= 0.0); argchecksub("--histsz", opt->lbfgs.histsz > 0 ); argchecksub("--maxls", opt->lbfgs.maxls > 0 ); argchecksub("--eta0", opt->sgdl1.eta0 > 0.0); argchecksub("--alpha", opt->sgdl1.alpha > 0.0); argchecksub("--nbest", opt->nbest > 0 ); #undef argchecksub if ((opt->maxent || !strcmp(opt->type, "maxent")) && !strcmp(opt->algo, "bcd")) fatal("BCD not supported for training maxent models"); if (!strcmp(opt->type, "memm") && !strcmp(opt->algo, "bcd")) fatal("BCD not supported for training MEMM models"); if (opt->check && opt->force) fatal("--check and --force cannot be used together"); }
703
./wapiti/src/vmath.c
/* * Wapiti - A linear-chain CRF tool * * Copyright (c) 2009-2013 CNRS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <assert.h> #include <math.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include "wapiti.h" #include "tools.h" #include "vmath.h" #if defined(__SSE2__) && !defined(XVM_ANSI) #include <emmintrin.h> #endif /* xvm_mode: * Return a string describing the SSE level used in the optimized code paths. */ const char *xvm_mode(void) { #if defined(__SSE2__) && !defined(XVM_ANSI) return "sse2"; #else return "no-sse"; #endif } /* xvm_new: * Allocate a new vector suitable to be used in the SSE code paths. This * ensure that the vector size contains the need padding. You must only use * vector allocated by this function if you use the optimized code paths. */ double *xvm_new(uint64_t N) { #if defined(__SSE2__) && !defined(XVM_ANSI) if (N % 4 != 0) N += 4 - N % 4; void *ptr = _mm_malloc(sizeof(double) * N, 16); if (ptr == NULL) fatal("out of memory"); return ptr; #else return xmalloc(sizeof(double) * N); #endif } /* xvm_free: * Free a vector allocated by xvm_new. */ void xvm_free(double x[]) { #if defined(__SSE2__) && !defined(XVM_ANSI) _mm_free(x); #else free(x); #endif } /* xvm_neg: * Return the component-wise negation of the given vector: * r = -x */ void xvm_neg(double r[], const double x[], uint64_t N) { #if defined(__SSE2__) && !defined(XVM_ANSI) assert(r != NULL && ((uintptr_t)r % 16) == 0); assert(x != NULL && ((uintptr_t)x % 16) == 0); const __m128d vz = _mm_setzero_pd(); for (uint64_t n = 0; n < N; n += 4) { const __m128d x0 = _mm_load_pd(x + n ); const __m128d x1 = _mm_load_pd(x + n + 2); const __m128d r0 = _mm_sub_pd(vz, x0); const __m128d r1 = _mm_sub_pd(vz, x1); _mm_store_pd(r + n, r0); _mm_store_pd(r + n + 2, r1); } #else for (uint64_t n = 0; n < N; n++) r[n] = -x[n]; #endif } /* xvm_sub: * Return the difference of the two given vector: * r = x .- y */ void xvm_sub(double r[], const double x[], const double y[], uint64_t N) { #if defined(__SSE2__) && !defined(XVM_ANSI) assert(r != NULL && ((uintptr_t)r % 16) == 0); assert(x != NULL && ((uintptr_t)x % 16) == 0); assert(y != NULL && ((uintptr_t)y % 16) == 0); for (uint64_t n = 0; n < N; n += 4) { const __m128d x0 = _mm_load_pd(x + n ); const __m128d x1 = _mm_load_pd(x + n + 2); const __m128d y0 = _mm_load_pd(y + n ); const __m128d y1 = _mm_load_pd(y + n + 2); const __m128d r0 = _mm_sub_pd(x0, y0); const __m128d r1 = _mm_sub_pd(x1, y1); _mm_store_pd(r + n, r0); _mm_store_pd(r + n + 2, r1); } #else for (uint64_t n = 0; n < N; n++) r[n] = x[n] - y[n]; #endif } /* xvm_scale: * Return the given vector scaled by a constant: * r = a * x */ void xvm_scale(double r[], const double x[], double a, uint64_t N) { for (uint64_t n = 0; n < N; n++) r[n] = x[n] * a; } /* xvm_norm: * Store a normalized copy of the given vector in r and return the * normalization factor. */ double xvm_unit(double r[], const double x[], uint64_t N) { double sum = 0.0; for (uint64_t n = 0; n < N; n++) sum += x[n]; const double scale = 1.0 / sum; xvm_scale(r, x, scale, N); return scale; } /* xvm_norm: * Return the euclidian norm of the given vector. */ double xvm_norm(const double x[], uint64_t N) { double r = 0.0; #if defined(__SSE2__) && !defined(XVM_ANSI) assert(x != NULL && ((uintptr_t)x % 16) == 0); uint64_t n, d = N % 4; __m128d s0 = _mm_setzero_pd(); __m128d s1 = _mm_setzero_pd(); for (n = 0; n < N - d; n += 4) { const __m128d x0 = _mm_load_pd(x + n ); const __m128d x1 = _mm_load_pd(x + n + 2); const __m128d r0 = _mm_mul_pd(x0, x0); const __m128d r1 = _mm_mul_pd(x1, x1); s0 = _mm_add_pd(s0, r0); s1 = _mm_add_pd(s1, r1); } s0 = _mm_add_pd(s0, s1); s1 = _mm_shuffle_pd(s0, s0, _MM_SHUFFLE2(1, 1)); s0 = _mm_add_pd(s0, s1); _mm_store_sd(&r, s0); for ( ; n < N; n++) r += x[n] * x[n]; #else for (uint64_t n = 0; n < N; n++) r += x[n] * x[n]; #endif return sqrt(r); } /* xvm_dot: * Return the dot product of the two given vectors. */ double xvm_dot(const double x[], const double y[], uint64_t N) { double r = 0.0; #if defined(__SSE2__) && !defined(XVM_ANSI) assert(x != NULL && ((uintptr_t)x % 16) == 0); assert(y != NULL && ((uintptr_t)y % 16) == 0); uint64_t n, d = N % 4; __m128d s0 = _mm_setzero_pd(); __m128d s1 = _mm_setzero_pd(); for (n = 0; n < N - d; n += 4) { const __m128d x0 = _mm_load_pd(x + n ); const __m128d x1 = _mm_load_pd(x + n + 2); const __m128d y0 = _mm_load_pd(y + n ); const __m128d y1 = _mm_load_pd(y + n + 2); const __m128d r0 = _mm_mul_pd(x0, y0); const __m128d r1 = _mm_mul_pd(x1, y1); s0 = _mm_add_pd(s0, r0); s1 = _mm_add_pd(s1, r1); } s0 = _mm_add_pd(s0, s1); s1 = _mm_shuffle_pd(s0, s0, _MM_SHUFFLE2(1, 1)); s0 = _mm_add_pd(s0, s1); _mm_store_sd(&r, s0); for ( ; n < N; n++) r += x[n] * y[n]; #else for (uint64_t n = 0; n < N; n++) r += x[n] * y[n]; #endif return r; } /* xvm_axpy: * Return the sum of x scaled by a and y: * r = a * x + y */ void xvm_axpy(double r[], double a, const double x[], const double y[], uint64_t N) { #if defined(__SSE2__) && !defined(XVM_ANSI) assert(r != NULL && ((uintptr_t)r % 16) == 0); assert(x != NULL && ((uintptr_t)x % 16) == 0); assert(y != NULL && ((uintptr_t)y % 16) == 0); const __m128d va = _mm_set1_pd(a); for (uint64_t n = 0; n < N; n += 4) { const __m128d x0 = _mm_load_pd(x + n ); const __m128d x1 = _mm_load_pd(x + n + 2); const __m128d y0 = _mm_load_pd(y + n ); const __m128d y1 = _mm_load_pd(y + n + 2); const __m128d t0 = _mm_mul_pd(x0, va); const __m128d t1 = _mm_mul_pd(x1, va); const __m128d r0 = _mm_add_pd(t0, y0); const __m128d r1 = _mm_add_pd(t1, y1); _mm_store_pd(r + n, r0); _mm_store_pd(r + n + 2, r1); } #else for (uint64_t n = 0; n < N; n++) r[n] = a * x[n] + y[n]; #endif } /* vms_expma: * Compute the component-wise exponential minus <a>: * r[i] <-- e^x[i] - a * * The following comments apply to the SSE2 version of this code: * * Computation is done four doubles as a time by doing computation in paralell * on two vectors of two doubles using SSE2 intrisics. If size is not a * multiple of 4, the remaining elements are computed using the stdlib exp(). * * The computation is done by first doing a range reduction of the argument of * the type e^x = 2^k * e^f choosing k and f so that f is in [-0.5, 0.5]. * Then 2^k can be computed exactly using bit operations to build the double * result and e^f can be efficiently computed with enough precision using a * polynomial approximation. * * The polynomial approximation is done with 11th order polynomial computed by * Remez algorithm with the Solya suite, instead of the more classical Pade * polynomial form cause it is better suited to parallel execution. In order * to achieve the same precision, a Pade form seems to require three less * multiplications but need a very costly division, so it will be less * efficient. * * The maximum error is less than 1lsb and special cases are correctly * handled: * +inf or +oor --> return +inf * -inf or -oor --> return 0.0 * qNaN or sNaN --> return qNaN * * This code is copyright 2004-2013 Thomas Lavergne and licenced under the * BSD licence like the remaining of Wapiti. */ void xvm_expma(double r[], const double x[], double a, uint64_t N) { #if defined(__SSE2__) && !defined(XVM_ANSI) #define xvm_vconst(v) (_mm_castsi128_pd(_mm_set1_epi64x((v)))) assert(r != NULL && ((uintptr_t)r % 16) == 0); assert(x != NULL && ((uintptr_t)x % 16) == 0); const __m128i vl = _mm_set1_epi64x(0x3ff0000000000000ULL); const __m128d ehi = xvm_vconst(0x4086232bdd7abcd2ULL); const __m128d elo = xvm_vconst(0xc086232bdd7abcd2ULL); const __m128d l2e = xvm_vconst(0x3ff71547652b82feULL); const __m128d hal = xvm_vconst(0x3fe0000000000000ULL); const __m128d nan = xvm_vconst(0xfff8000000000000ULL); const __m128d inf = xvm_vconst(0x7ff0000000000000ULL); const __m128d c1 = xvm_vconst(0x3fe62e4000000000ULL); const __m128d c2 = xvm_vconst(0x3eb7f7d1cf79abcaULL); const __m128d p0 = xvm_vconst(0x3feffffffffffffeULL); const __m128d p1 = xvm_vconst(0x3ff000000000000bULL); const __m128d p2 = xvm_vconst(0x3fe0000000000256ULL); const __m128d p3 = xvm_vconst(0x3fc5555555553a2aULL); const __m128d p4 = xvm_vconst(0x3fa55555554e57d3ULL); const __m128d p5 = xvm_vconst(0x3f81111111362f4fULL); const __m128d p6 = xvm_vconst(0x3f56c16c25f3bae1ULL); const __m128d p7 = xvm_vconst(0x3f2a019fc9310c33ULL); const __m128d p8 = xvm_vconst(0x3efa01825f3cb28bULL); const __m128d p9 = xvm_vconst(0x3ec71e2bd880fdd8ULL); const __m128d p10 = xvm_vconst(0x3e9299068168ac8fULL); const __m128d p11 = xvm_vconst(0x3e5ac52350b60b19ULL); const __m128d va = _mm_set1_pd(a); for (uint64_t n = 0; n < N; n += 4) { __m128d mn1, mn2, mi1, mi2; __m128d t1, t2, d1, d2; __m128d v1, v2, w1, w2; __m128i k1, k2; __m128d f1, f2; // Load the next four values __m128d x1 = _mm_load_pd(x + n ); __m128d x2 = _mm_load_pd(x + n + 2); // Check for out of ranges, infinites and NaN mn1 = _mm_cmpneq_pd(x1, x1); mn2 = _mm_cmpneq_pd(x2, x2); mi1 = _mm_cmpgt_pd(x1, ehi); mi2 = _mm_cmpgt_pd(x2, ehi); x1 = _mm_max_pd(x1, elo); x2 = _mm_max_pd(x2, elo); // Range reduction: we search k and f such that e^x = 2^k * e^f // with f in [-0.5, 0.5] t1 = _mm_mul_pd(x1, l2e); t2 = _mm_mul_pd(x2, l2e); t1 = _mm_add_pd(t1, hal); t2 = _mm_add_pd(t2, hal); k1 = _mm_cvttpd_epi32(t1); k2 = _mm_cvttpd_epi32(t2); d1 = _mm_cvtepi32_pd(k1); d2 = _mm_cvtepi32_pd(k2); t1 = _mm_mul_pd(d1, c1); t2 = _mm_mul_pd(d2, c1); f1 = _mm_sub_pd(x1, t1); f2 = _mm_sub_pd(x2, t2); t1 = _mm_mul_pd(d1, c2); t2 = _mm_mul_pd(d2, c2); f1 = _mm_sub_pd(f1, t1); f2 = _mm_sub_pd(f2, t2); // Evaluation of e^f using a 11th order polynom in Horner form v1 = _mm_mul_pd(f1, p11); v2 = _mm_mul_pd(f2, p11); v1 = _mm_add_pd(v1, p10); v2 = _mm_add_pd(v2, p10); v1 = _mm_mul_pd(v1, f1); v2 = _mm_mul_pd(v2, f2); v1 = _mm_add_pd(v1, p9); v2 = _mm_add_pd(v2, p9); v1 = _mm_mul_pd(v1, f1); v2 = _mm_mul_pd(v2, f2); v1 = _mm_add_pd(v1, p8); v2 = _mm_add_pd(v2, p8); v1 = _mm_mul_pd(v1, f1); v2 = _mm_mul_pd(v2, f2); v1 = _mm_add_pd(v1, p7); v2 = _mm_add_pd(v2, p7); v1 = _mm_mul_pd(v1, f1); v2 = _mm_mul_pd(v2, f2); v1 = _mm_add_pd(v1, p6); v2 = _mm_add_pd(v2, p6); v1 = _mm_mul_pd(v1, f1); v2 = _mm_mul_pd(v2, f2); v1 = _mm_add_pd(v1, p5); v2 = _mm_add_pd(v2, p5); v1 = _mm_mul_pd(v1, f1); v2 = _mm_mul_pd(v2, f2); v1 = _mm_add_pd(v1, p4); v2 = _mm_add_pd(v2, p4); v1 = _mm_mul_pd(v1, f1); v2 = _mm_mul_pd(v2, f2); v1 = _mm_add_pd(v1, p3); v2 = _mm_add_pd(v2, p3); v1 = _mm_mul_pd(v1, f1); v2 = _mm_mul_pd(v2, f2); v1 = _mm_add_pd(v1, p2); v2 = _mm_add_pd(v2, p2); v1 = _mm_mul_pd(v1, f1); v2 = _mm_mul_pd(v2, f2); v1 = _mm_add_pd(v1, p1); v2 = _mm_add_pd(v2, p1); v1 = _mm_mul_pd(v1, f1); v2 = _mm_mul_pd(v2, f2); v1 = _mm_add_pd(v1, p0); v2 = _mm_add_pd(v2, p0); // Evaluation of 2^k using bitops to achieve exact computation k1 = _mm_slli_epi32(k1, 20); k2 = _mm_slli_epi32(k2, 20); k1 = _mm_shuffle_epi32(k1, 0x72); k2 = _mm_shuffle_epi32(k2, 0x72); k1 = _mm_add_epi32(k1, vl); k2 = _mm_add_epi32(k2, vl); w1 = _mm_castsi128_pd(k1); w2 = _mm_castsi128_pd(k2); // Return to full range to substract <a> v1 = _mm_mul_pd(v1, w1); v2 = _mm_mul_pd(v2, w2); v1 = _mm_sub_pd(v1, va); v2 = _mm_sub_pd(v2, va); // Finally apply infinite and NaN where needed v1 = _mm_or_pd(_mm_and_pd(mi1, inf), _mm_andnot_pd(mi1, v1)); v2 = _mm_or_pd(_mm_and_pd(mi2, inf), _mm_andnot_pd(mi2, v2)); v1 = _mm_or_pd(_mm_and_pd(mn1, nan), _mm_andnot_pd(mn1, v1)); v2 = _mm_or_pd(_mm_and_pd(mn2, nan), _mm_andnot_pd(mn2, v2)); // Store the results _mm_store_pd(r + n, v1); _mm_store_pd(r + n + 2, v2); } #else for (uint64_t n = 0; n < N; n++) r[n] = exp(x[n]) - a; #endif }
704
./wapiti/src/tools.c
/* * Wapiti - A linear-chain CRF tool * * Copyright (c) 2009-2013 CNRS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <errno.h> #include <inttypes.h> #include <stdarg.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "tools.h" /******************************************************************************* * Error handling and memory managment * * Wapiti use a very simple system for error handling: violently fail. Errors * can occurs in two cases, when user feed Wapiti with bad datas or when there * is a problem on the system side. In both cases, there is nothing we can do, * so the best thing is to exit with a meaning full error message. * * Memory allocation is one of the possible point of failure and its painfull * to always remeber to check return value of malloc so we provide wrapper * around it and realloc who check and fail in case of error. ******************************************************************************/ /* fatal: * This is the main error function, it will print the given message with same * formating than the printf family and exit program with an error. We let the * OS care about freeing ressources. */ void fatal(const char *msg, ...) { va_list args; fprintf(stderr, "error: "); va_start(args, msg); vfprintf(stderr, msg, args); va_end(args); fprintf(stderr, "\n"); exit(EXIT_FAILURE); } /* pfatal: * This one is very similar to the fatal function but print an additional * system error message depending on the errno. This can be used when a * function who set the errno fail to print more detailed informations. You * must be carefull to not call other functino that might reset it before * calling pfatal. */ void pfatal(const char *msg, ...) { const char *err = strerror(errno); va_list args; fprintf(stderr, "error: "); va_start(args, msg); vfprintf(stderr, msg, args); va_end(args); fprintf(stderr, "\n\t<%s>\n", err); exit(EXIT_FAILURE); } /* warning: * This one is less violent as it just print a warning on stderr, but doesn't * exit the program. It is intended to inform the user that something strange * have happen and the result might be not what it have expected. */ void warning(const char *msg, ...) { va_list args; fprintf(stderr, "warning: "); va_start(args, msg); vfprintf(stderr, msg, args); va_end(args); fprintf(stderr, "\n"); } /* info: * Function used for all progress reports. This is where an eventual verbose * level can be implemented later or redirection to a logfile. For now, it is * just a wrapper for printf to stderr. Note that unlike the previous one, * this function doesn't automatically append a new line character. */ void info(const char *msg, ...) { va_list args; va_start(args, msg); vfprintf(stderr, msg, args); va_end(args); } /* xmalloc: * A simple wrapper around malloc who violently fail if memory cannot be * allocated, so it will never return NULL. */ void *xmalloc(size_t size) { void *ptr = malloc(size); if (ptr == NULL) fatal("out of memory"); return ptr; } /* xrealloc: * As xmalloc, this is a simple wrapper around realloc who fail on memory * error and so never return NULL. */ void *xrealloc(void *ptr, size_t size) { void *new = realloc(ptr, size); if (new == NULL) fatal("out of memory"); return new; } /* xstrdup: * As the previous one, this is a safe version of xstrdup who fail on * allocation error. */ char *xstrdup(const char *str) { const size_t len = strlen(str) + 1; char *res = xmalloc(sizeof(char) * len); memcpy(res, str, len); return res; } /****************************************************************************** * Netstring for persistent storage * * This follow the format proposed by D.J. Bernstein for safe and portable * storage of string in persistent file and networks. This used for storing * strings in saved models. * We just add an additional end-of-line character to make the output files * more readable. * ******************************************************************************/ /* ns_readstr: * Read a string from the given file in netstring format. The string is * returned as a newly allocated bloc of memory 0-terminated. */ char *ns_readstr(FILE *file) { uint32_t len; if (fscanf(file, "%"SCNu32":", &len) != 1) pfatal("cannot read from file"); char *buf = xmalloc(len + 1); if (fread(buf, len, 1, file) != 1) pfatal("cannot read from file"); if (fgetc(file) != ',') fatal("invalid format"); buf[len] = '\0'; fgetc(file); return buf; } /* ns_writestr: * Write a string in the netstring format to the given file. */ void ns_writestr(FILE *file, const char *str) { const uint32_t len = strlen(str); if (fprintf(file, "%"PRIu32":%s,\n", len, str) < 0) pfatal("cannot write to file"); }
705
./wapiti/src/progress.c
/* * Wapiti - A linear-chain CRF tool * * Copyright (c) 2009-2013 CNRS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <inttypes.h> #include <signal.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/time.h> #include <sys/resource.h> #include "wapiti.h" #include "decoder.h" #include "model.h" #include "options.h" #include "progress.h" #include "tools.h" /******************************************************************************* * User interaction during training * * Handle progress reporting during training and clean early stoping. Trainers * have to call uit_progress at the end of each iterations, this will display * various informations for the user. * Timing is also done here, an iteration is assumed to take all the time * between to call to the progress function and evualtion on the devel data * are included. * * This module setup a signal handler for SIGINT. If this signal is catched, * the uit_stop global variable to inform the trainer that it have to stop as * early as possible, discarding the recent computations if they cannot be * integrated very quickly. They must leave the model in a clean state. Any * further signal will terminate the program. So it's simple : * - 1 signal mean "I can wait a little so try to stop as soon as possible * but leave me a working model" * - 2 signal mean "Stop immediatly what you are doing, I can't wait and * don't care about getting a working model" ******************************************************************************/ /* uit_stop: * This value is set to true when the user request the trainer to stop. In * this case, the trainer have to stop as soon as possible in a clean state, * discarding the lasts computations if it cannot integrate them quickly. */ bool uit_stop = false; /* uit_signal: * Signal handler to catch interupt signal. When a signal is received, the * trainer is aksed to stop as soon as possible leaving the model in a clean * state. We don't reinstall the handler so if user send a second interupt * signal, the program will stop imediatly. (to cope with BSD system, we even * reinstall explicitly the default handler) */ static void uit_signal(int sig) { signal(sig, SIG_DFL); uit_stop = true; } /* uit_setup: * Install the signal handler for clean early stop from the user if possible * and start the timer. */ void uit_setup(mdl_t *mdl) { uit_stop = false; if (signal(SIGINT, uit_signal) == SIG_ERR) warning("failed to set signal handler, no clean early stop"); gettimeofday(&mdl->timer, NULL); if (mdl->opt->stopwin != 0) mdl->werr = xmalloc(sizeof(double) * mdl->opt->stopwin); mdl->wcnt = mdl->wpos = 0; } /* uit_cleanup: * Remove the signal handler restoring the defaul behavior in case of * interrupt. */ void uit_cleanup(mdl_t *mdl) { unused(mdl); if (mdl->opt->stopwin != 0) { free(mdl->werr); mdl->werr = NULL; } signal(SIGINT, SIG_DFL); } /* uit_progress: * Display a progress repport to the user consisting of some informations * provided by the trainer: iteration count and objective function value, and * some informations computed here on the current model performances. * This function return true if the trainer have to keep training the model * and false if he must stop, so this is were we will implement the trainer * independant stoping criterion. */ bool uit_progress(mdl_t *mdl, uint32_t it, double obj) { // First we just compute the error rate on devel or train data double te, se; tag_eval(mdl, &te, &se); // Next, we compute the number of active features uint64_t act = 0; for (uint64_t f = 0; f < mdl->nftr; f++) if (mdl->theta[f] != 0.0) act++; // Compute timings. As some training algorithms are multi-threaded, we // cannot use ansi/c function and must rely on posix one to sum time // spent in main thread and in child ones. tms_t now; gettimeofday(&now, NULL); double tm = (now.tv_sec + (double)now.tv_usec * 1.0e-6) - (mdl->timer.tv_sec + (double)mdl->timer.tv_usec * 1.0e-6); mdl->total += tm; mdl->timer = now; // And display progress report info(" [%4"PRIu32"]", it); info(obj >= 0.0 ? " obj=%-10.2f" : " obj=NA", obj); info(" act=%-8"PRIu64, act); info(" err=%5.2f%%/%5.2f%%", te, se); info(" time=%.2fs/%.2fs", tm, mdl->total); info("\n"); // If requested, check the error rate stoping criterion. We check if the // error rate is stable enought over a few iterations. bool res = true; if (mdl->opt->stopwin != 0) { mdl->werr[mdl->wpos] = te; mdl->wpos = (mdl->wpos + 1) % mdl->opt->stopwin; mdl->wcnt++; if (mdl->wcnt >= mdl->opt->stopwin) { double emin = 200.0, emax = -100.0; for (uint32_t i = 0; i < mdl->opt->stopwin; i++) { emin = min(emin, mdl->werr[i]); emax = max(emax, mdl->werr[i]); } if (emax - emin < mdl->opt->stopeps) res = false; } } // And return if (uit_stop) return false; return res; }
706
./wapiti/src/lbfgs.c
/* * Wapiti - A linear-chain CRF tool * * Copyright (c) 2009-2013 CNRS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <inttypes.h> #include <math.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "wapiti.h" #include "gradient.h" #include "model.h" #include "options.h" #include "progress.h" #include "tools.h" #include "thread.h" #include "vmath.h" /****************************************************************************** * Quasi-Newton optimizer * * This section implement the quasi-Newton optimizer. We use the L-BFGS * algorithm described by Liu and Nocedal in [1] and [2]. If an l1-norm must * be applyed we fallback on the OWL-QN variant described in [3] by Galen and * Jianfeng which allow to use L-BFGS for function not differentiable in 0.0. * * [1] Updating quasi-Newton matrices with limited storage, Jorge Nocedal, in * Mathematics of Computation, vol. 35(151) 773-782, July 1980. * [2] On the limited memory BFGS method for large scale optimization, Dong C. * Liu and Jorge Nocedal, in Mathematical Programming, vol. 45(1) 503-528, * January 1989. * [3] Scalable Training of L1-Regularized Log-Linear Models, Andrew Galen and * Gao Jianfeng, in Proceedings of the 24th International Conference on * Machine Learning (ICML), Corvallis, OR, 2007. ******************************************************************************/ void trn_lbfgs(mdl_t *mdl) { const uint64_t F = mdl->nftr; const uint32_t K = mdl->opt->maxiter; const uint32_t C = mdl->opt->objwin; const uint32_t M = mdl->opt->lbfgs.histsz; const bool l1 = mdl->opt->rho1 != 0.0; double *x, *xp; // Current and previous value of the variables double *g, *gp; // Current and previous value of the gradient double *pg; // The pseudo-gradient (only for owl-qn) double *d; // The search direction double *s[M]; // History value s_k = Δ(x,px) double *y[M]; // History value y_k = Δ(g,pg) double p[M]; // ρ_k double fh[C]; // f(x) history // Initialization: Here, we have to allocate memory on the heap as we // cannot request so much memory on the stack as this will have a too // big impact on performance and will be refused by the system on non- // trivial models. x = mdl->theta; xp = xvm_new(F); g = xvm_new(F); gp = xvm_new(F); d = xvm_new(F); for (uint32_t m = 0; m < M; m++) { s[m] = xvm_new(F); y[m] = xvm_new(F); } pg = l1 ? xvm_new(F) : NULL; grd_t *grd = grd_new(mdl, g); // Restore a saved state if user specified one. if (mdl->opt->rstate != NULL) { const char *err = "invalid state file"; FILE *file = fopen(mdl->opt->rstate, "r"); if (file == NULL) fatal("failed to open input state file"); int type, histsz; uint64_t nftr; if (fscanf(file, "#state#%d#%d#%"SCNu64"\n", &type, &histsz, &nftr) != 3) fatal("0 %s", err); if (type != 0 || histsz != (int)M) fatal("state is not compatible"); for (uint64_t i = 0; i < nftr; i++) { uint64_t f; if (fscanf(file, "%"PRIu64, &f) != 1) fatal("1 %s", err); if (fscanf(file, "%la %la", &xp[f], &gp[f]) != 2) fatal("2 %s", err); for (uint32_t m = 0; m < M; m++) { if (fscanf(file, "%la", &s[m][f]) != 1) fatal("3 %s", err); if (fscanf(file, "%la", &y[m][f]) != 1) fatal("4 %s", err); } } for (uint32_t m = 0; m < M; m++) p[m] = 1.0 / xvm_dot(y[m], s[m], F); fclose(file); } // Minimization: This is the heart of the function. (a big heart...) We // will perform iterations until one these conditions is reached // - the maximum iteration count is reached // - we have converged (upto numerical precision) // - the report function return false // - an error happen somewhere double fx = grd_gradient(grd); for (uint32_t k = 0; !uit_stop && k < K; k++) { // We first compute the pseudo-gradient of f for owl-qn. It is // defined in [3, pp 335(4)] // | ∂_i^- f(x) if ∂_i^- f(x) > 0 // ◇_i f(x) = | ∂_i^+ f(x) if ∂_i^+ f(x) < 0 // | 0 otherwise // with // ∂_i^± f(x) = ∂/∂x_i l(x) + | Cσ(x_i) if x_i ≠ 0 // | ±C if x_i = 0 if (l1) { const double rho1 = mdl->opt->rho1; for (uint64_t f = 0; f < F; f++) { if (x[f] < 0.0) pg[f] = g[f] - rho1; else if (x[f] > 0.0) pg[f] = g[f] + rho1; else if (g[f] < -rho1) pg[f] = g[f] + rho1; else if (g[f] > rho1) pg[f] = g[f] - rho1; else pg[f] = 0.0; } } // 1st step: We compute the search direction. We search in the // direction who minimize the second order approximation given // by the Taylor series which give // d_k = - H_k^{-1} g_k // But computing the inverse of the hessian is intractable so // the l-bfgs only approximate it's diagonal. The exact // computation is well described in [1, pp 779]. // The only special thing for owl-qn here is to use the pseudo // gradient instead of the true one. xvm_neg(d, l1 ? pg : g, F); if (k != 0) { const uint32_t km = k % M; const uint32_t bnd = (k <= M) ? k : M; double alpha[M], beta; // α_i = ρ_j s_j^T q_{i+1} // q_i = q_{i+1} - α_i y_i for (uint32_t i = bnd; i > 0; i--) { const uint32_t j = (M + 1 + k - i) % M; alpha[i - 1] = p[j] * xvm_dot(s[j], d, F); xvm_axpy(d, -alpha[i - 1], y[j], d, F); } // r_0 = H_0 q_0 // Scaling is described in [2, pp 515] // for k = 0: H_0 = I // for k > 0: H_0 = I * y_k^T s_k / ||y_k||² // = I * 1 / ρ_k ||y_k||² const double y2 = xvm_dot(y[km], y[km], F); const double v = 1.0 / (p[km] * y2); for (uint64_t f = 0; f < F; f++) d[f] *= v; // β_j = ρ_j y_j^T r_i // r_{i+1} = r_i + s_j (α_i - β_i) for (uint32_t i = 0; i < bnd; i++) { const uint32_t j = (M + k - i) % M; beta = p[j] * xvm_dot(y[j], d, F); xvm_axpy(d, alpha[i] - beta, s[j], d, F); } } // For owl-qn, we must remain in the same orthant than the // pseudo-gradient, so we have to constrain the search // direction as described in [3, pp 35(3)] // d^k = π(d^k ; v^k) // = π(d^k ; -◇f(x^k)) if (l1) for (uint64_t f = 0; f < F; f++) if (d[f] * pg[f] >= 0.0) d[f] = 0.0; // 2nd step: we perform a linesearch in the computed direction, // we search a step value that satisfy the constrains using a // backtracking algorithm. Much elaborated algorithm can perform // better in the general case, but for CRF training, bactracking // is very efficient and simple to implement. // For quasi-Newton, the natural step is 1.0 so we start with // this one and reduce it only if it fail with an exception for // the first step where a better guess can be done. // We have to keep track of the current point and gradient as we // will need to compute the delta between those and the found // point, and perhaps need to restore them if linesearch fail. memcpy(xp, x, sizeof(double) * F); memcpy(gp, g, sizeof(double) * F); double sc = (k == 0) ? 0.1 : 0.5; double stp = (k == 0) ? 1.0 / xvm_norm(d, F) : 1.0; double gd = l1 ? 0.0 : xvm_dot(g, d, F); // gd = g_k^T d_k double fi = fx; bool err = false; for (uint32_t ls = 1; !uit_stop; ls++, stp *= sc) { // We compute the new point using the current step and // search direction xvm_axpy(x, stp, d, xp, F); // For owl-qn, we have to project back the point in the // current orthant [3, pp 35] // x^{k+1} = π(x^k + αp^k ; ξ) if (l1) { for (uint64_t f = 0; f < F; f++) { double or = xp[f]; if (or == 0.0) or = -pg[f]; if (x[f] * or <= 0.0) x[f] = 0.0; } } // And we ask for the value of the objective function // and its gradient. fx = grd_gradient(grd); // Now we check if the step satisfy the conditions. For // l-bfgs, we check the classical decrease and curvature // known as the Wolfe conditions [2, pp 506] // f(x_k + α_k d_k) ≤ f(x_k) + β' α_k g_k^T d_k // g(x_k + α_k d_k)^T d_k ≥ β g_k^T d_k // // And for owl-qn we check a variant of the Armijo rule // described in [3, pp 36] // f(π(x^k+αp^k;ξ)) ≤ f(x^k) - γv^T[π(x^k+αp^k;ξ)-x^k] if (!l1) { if (fx > fi + stp * gd * 1e-4) sc = 0.5; else if (xvm_dot(g, d, F) < gd * 0.9) sc = 2.1; else break; } else { double vp = 0.0; for (uint64_t f = 0; f < F; f++) vp += (x[f] - xp[f]) * d[f]; if (fx < fi + vp * 1e-4) break; } // If we reach the maximum number of linesearsh steps // without finding a good one, we just fail. if (ls == mdl->opt->lbfgs.maxls) { warning("maximum linesearch reached"); err = true; break; } } // If linesearch failed or user interupted training, we return // to the last valid point and stop the training. The model is // probably not fully optimized but we let the user decide what // to do with it. if (err || uit_stop) { memcpy(x, xp, sizeof(double) * F); break; } if (uit_progress(mdl, k + 1, fx) == false) break; // 3rd step: we update the history used for approximating the // inverse of the diagonal of the hessian // s_k = x_{k+1} - x_k // y_k = g_{k+1} - g_k // ρ_k = 1 / y_k^T s_k const uint32_t kn = (k + 1) % M; xvm_sub(s[kn], x, xp, F); xvm_sub(y[kn], g, gp, F); p[kn] = 1.0 / xvm_dot(y[kn], s[kn], F); // And last, we check for convergence. The convergence check is // quite simple [2, pp 508] // ||g|| / max(1, ||x||) ≤ ε // with ε small enough so we stop when numerical precision is // reached. For owl-qn we just have to check against the pseudo- // gradient instead of the true one. const double xn = xvm_norm(x, F); const double gn = xvm_norm(l1 ? pg : g, F); if (gn / max(xn, 1.0) <= 1e-5) break; if (k + 1 == K) break; // Second stoping criterion tested is a check for improvement of // the function value over the past W iteration. When this come // under an epsilon, we also stop the minimization. fh[k % C] = fx; double dlt = 1.0; if (k >= C) { const double of = fh[(k + 1) % C]; dlt = fabs(of - fx) / of; if (dlt < mdl->opt->stopeps) break; } } // Save the optimizer state if requested by the user if (mdl->opt->sstate != NULL) { FILE *file = fopen(mdl->opt->sstate, "w"); if (file == NULL) fatal("failed to open output state file"); fprintf(file, "#state#0#%"PRIu32"#%"PRIu64"\n", M, F); for (uint64_t f = 0; f < F; f++) { fprintf(file, "%"PRIu64, f); fprintf(file, " %la %la", xp[f], gp[f]); for (uint32_t m = 0; m < M; m++) fprintf(file, " %la %la", s[m][f], y[m][f]); fprintf(file, "\n"); } fclose(file); } // Cleanup: We free all the vectors we have allocated. xvm_free(xp); xvm_free(g); xvm_free(gp); xvm_free(d); for (uint32_t m = 0; m < M; m++) { xvm_free(s[m]); xvm_free(y[m]); } if (l1) xvm_free(pg); grd_free(grd); }
707
./wapiti/src/quark.c
/* * Wapiti - A linear-chain CRF tool * * Copyright (c) 2009-2013 CNRS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <inttypes.h> #include <stdbool.h> #include <stddef.h> #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include "quark.h" #include "tools.h" /****************************************************************************** * Map object * * Implement quark object for mapping strings to identifiers through crit-bit * tree (also known as PATRICIA tries). In fact it only store a compressed * version of the trie to reduce memory footprint. The special trick of using * the last bit of the reference to differenciate between nodes and leafs come * from Daniel J. Bernstein implementation of crit-bit tree that can be found * on his web site. * [1] Morrison, Donald R. ; PATRICIA-Practical Algorithm To Retrieve * Information Coded in Alphanumeric, Journal of the ACM 15 (4): pp. 514--534, * 1968. DOI:10.1145/321479.321481 * * This code is copyright 2002-2013 Thomas Lavergne and licenced under the BSD * Licence like the remaining of Wapiti. ******************************************************************************/ typedef struct node_s node_t; typedef struct leaf_s leaf_t; struct qrk_s { struct node_s { node_t *child[2]; uint32_t pos; uint8_t byte; } *root; struct leaf_s { uint64_t id; char key[]; } **leafs; bool lock; uint64_t count; uint64_t size; }; #define qrk_lf2nd(lf) ((node_t *)((intptr_t)(lf) | 1)) #define qrk_nd2lf(nd) ((leaf_t *)((intptr_t)(nd) & ~1)) #define qrk_isleaf(nd) ((intptr_t)(nd) & 1) /* qrk_new: * This initialize the object for holding a new empty trie, with some pre- * allocations. The returned object must be freed with a call to qrk_free when * not needed anymore. */ qrk_t *qrk_new(void) { const uint64_t size = 128; qrk_t *qrk = xmalloc(sizeof(qrk_t)); qrk->root = NULL; qrk->count = 0; qrk->lock = false; qrk->size = size; qrk->leafs = xmalloc(sizeof(leaf_t) * size); return qrk; } /* qrk_free: * Release all the memory used by a qrk_t object allocated with qrk_new. This * will release all key string stored internally so all key returned by * qrk_unmap become invalid and must not be used anymore. */ void qrk_free(qrk_t *qrk) { const uint32_t stkmax = 1024; if (qrk->count != 0) { node_t *stk[stkmax]; uint32_t cnt = 0; stk[cnt++] = qrk->root; while (cnt != 0) { node_t *nd = stk[--cnt]; if (qrk_isleaf(nd)) { free(qrk_nd2lf(nd)); continue; } stk[cnt++] = nd->child[0]; stk[cnt++] = nd->child[1]; free(nd); } } free(qrk->leafs); free(qrk); } /* qrk_insert: * Map a key to a uniq identifier. If the key already exist in the map, return * its identifier, else allocate a new identifier and insert the new (key,id) * pair inside the quark. This function is not thread safe and should not be * called on the same map from different thread without locking. */ uint64_t qrk_str2id(qrk_t *qrk, const char *key) { const uint8_t *raw = (void *)key; const size_t len = strlen(key); // We first take care of the empty trie case so later we can safely // assume that the trie is well formed and so there is no NULL pointers // in it. if (qrk->count == 0) { if (qrk->lock == true) return none; const size_t size = sizeof(char) * (len + 1); leaf_t *lf = xmalloc(sizeof(leaf_t) + size); memcpy(lf->key, key, size); lf->id = 0; qrk->root = qrk_lf2nd(lf); qrk->leafs[0] = lf; qrk->count = 1; return 0; } // If the trie is not empty, we first go down the trie to the leaf like // if we are searching for the key. When at leaf there is two case, // either we have found our key or we have found another key with all // its critical bit identical to our one. So we search for the first // differing bit between them to know where we have to add the new node. const node_t *nd = qrk->root; while (!qrk_isleaf(nd)) { const uint8_t chr = nd->pos < len ? raw[nd->pos] : 0; const int side = ((chr | nd->byte) + 1) >> 8; nd = nd->child[side]; } const char *bst = qrk_nd2lf(nd)->key; size_t pos; for (pos = 0; pos < len; pos++) if (key[pos] != bst[pos]) break; uint8_t byte; if (pos != len) byte = key[pos] ^ bst[pos]; else if (bst[pos] != '\0') byte = bst[pos]; else return qrk_nd2lf(nd)->id; if (qrk->lock == true) return none; // Now we known the two key are different and we know in which byte. It // remain to build the mask for the new critical bit and build the new // internal node and leaf. while (byte & (byte - 1)) byte &= byte - 1; byte ^= 255; const uint8_t chr = bst[pos]; const int side = ((chr | byte) + 1) >> 8; const size_t size = sizeof(char) * (len + 1); node_t *nx = xmalloc(sizeof(node_t)); leaf_t *lf = xmalloc(sizeof(leaf_t) + size); memcpy(lf->key, key, size); lf->id = qrk->count++; nx->pos = pos; nx->byte = byte; nx->child[1 - side] = qrk_lf2nd(lf); if (lf->id == qrk->size) { qrk->size *= 1.4; const size_t size = sizeof(leaf_t *) * qrk->size; qrk->leafs = xrealloc(qrk->leafs, size); } qrk->leafs[lf->id] = lf; // And last thing to do: inserting the new node in the trie. We have to // walk down the trie again as we have to keep the ordering of nodes. So // we search for the good position to insert it. node_t **trg = &qrk->root; while (true) { node_t *nd = *trg; if (qrk_isleaf(nd) || nd->pos > pos) break; if (nd->pos == pos && nd->byte > byte) break; const uint8_t chr = nd->pos < len ? raw[nd->pos] : 0; const int side = ((chr | nd->byte) + 1) >> 8; trg = &nd->child[side]; } nx->child[side] = *trg; *trg = nx; return lf->id; } /* qrk_id2str: * Retrieve the key associated to an identifier. The key is returned as a * constant string that should not be modified or freed by the caller, it is * a pointer to the internal copy of the key kept by the map object and * remain valid only for the life time of the quark, a call to qrk_free will * make this pointer invalid. */ const char *qrk_id2str(const qrk_t *qrk, uint64_t id) { if (id >= qrk->count) fatal("invalid identifier"); return qrk->leafs[id]->key; } /* qrk_save: * Save list of keys present in the map object in the id order to the given * file. We put one key per line so, if no key contains a new line, the line * number correspond to the id. */ void qrk_save(const qrk_t *qrk, FILE *file) { if (fprintf(file, "#qrk#%"PRIu64"\n", qrk->count) < 0) pfatal("cannot write to file"); if (qrk->count == 0) return; for (uint64_t n = 0; n < qrk->count; n++) ns_writestr(file, qrk->leafs[n]->key); } /* qrk_load: * Load a list of key from the given file and add them to the map. Each lines * of the file is taken as a single key and mapped to the next available id if * not already present. If all keys are single lines and the given map is * initilay empty, this will load a map exactly as saved by qrk_save. */ void qrk_load(qrk_t *qrk, FILE *file) { uint64_t cnt = 0; if (fscanf(file, "#qrk#%"SCNu64"\n", &cnt) != 1) { if (ferror(file) != 0) pfatal("cannot read from file"); pfatal("invalid format"); } for (uint64_t n = 0; n < cnt; ++n) { char *str = ns_readstr(file); qrk_str2id(qrk, str); free(str); } } /* qrk_count: * Return the number of mappings stored in the quark. */ uint64_t qrk_count(const qrk_t *qrk) { return qrk->count; } /* qrk_lock: * Set the lock value of the quark and return the old one. */ bool qrk_lock(qrk_t *qrk, bool lock) { bool old = qrk->lock; qrk->lock = lock; return old; }
708
./wapiti/src/sgdl1.c
/* * Wapiti - A linear-chain CRF tool * * Copyright (c) 2009-2013 CNRS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <math.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include "wapiti.h" #include "gradient.h" #include "model.h" #include "options.h" #include "progress.h" #include "sequence.h" #include "tools.h" /****************************************************************************** * The SGD-L1 trainer * * Implementation of the stochatic gradient descend with L1 penalty described * in [1] by Tsurukoa et al. This allow to build really sparse models with the * SGD method. * * [1] Stochastic gradient descent training for L1-regularized log-linear * models with cumulative penalty, Yoshimasa Tsuruoka and Jun'ichi Tsuji * and Sophia Ananiadou, in Proceedings of the ACL and the 4th IJCNLP of * the AFNLP, pages 477-485, August 2009 ******************************************************************************/ typedef struct sgd_idx_s { uint64_t *uobs; uint64_t *bobs; } sgd_idx_t; /* applypenalty: * This macro is quite ugly as it make a lot of things and use local variables * of the function below. I'm sorry for this but this is allow to not * duplicate the code below. Due to the way unigrams and bigrams observation * are stored we must use this two times. As this macro is dangerous when * called outsize of sgd-l1 we undef it just after. * This function match exactly the APPLYPENALTY function defined in [1] pp 481 * and the formula on the middle of the page 480. */ #define applypenalty(f) do { \ const double z = w[f]; \ if (z > 0.0) w[f] = max(0.0, z - (u + q[f])); \ else if (z < 0.0) w[f] = min(0.0, z + (u - q[f])); \ q[f] += w[f] - z; \ } while (false) /* sgd_add: * Add the <new> value in the array <obs> of size <cnt>. If the value is * already present, we do nothing, else we add it. */ static void sgd_add(uint64_t *obs, uint32_t *cnt, uint64_t new) { // First check if value is already in the array, we do a linear probing // as it is simpler and since these array will be very short in // practice, it's efficient enough. for (uint32_t p = 0; p < *cnt; p++) if (obs[p] == new) return; // Insert the new value at the end since we have not found it. obs[*cnt] = new; *cnt = *cnt + 1; } /* trn_sgdl1: * Train the model with the SGD-l1 algorithm described by tsurukoa et al. */ void trn_sgdl1(mdl_t *mdl) { const uint64_t Y = mdl->nlbl; const uint64_t F = mdl->nftr; const uint32_t U = mdl->reader->nuni; const uint32_t B = mdl->reader->nbi; const uint32_t S = mdl->train->nseq; const uint32_t K = mdl->opt->maxiter; double *w = mdl->theta; // First we have to build and index who hold, for each sequences, the // list of actives observations. // The index is a simple table indexed by sequences number. Each entry // point to two lists of observations terminated by <none>, one for // unigrams obss and one for bigrams obss. info(" - Build the index\n"); sgd_idx_t *idx = xmalloc(sizeof(sgd_idx_t) * S); for (uint32_t s = 0; s < S; s++) { const seq_t *seq = mdl->train->seq[s]; const uint32_t T = seq->len; uint64_t uobs[U * T + 1]; uint64_t bobs[B * T + 1]; uint32_t ucnt = 0, bcnt = 0; for (uint32_t t = 0; t < seq->len; t++) { const pos_t *pos = &seq->pos[t]; for (uint32_t p = 0; p < pos->ucnt; p++) sgd_add(uobs, &ucnt, pos->uobs[p]); for (uint32_t p = 0; p < pos->bcnt; p++) sgd_add(bobs, &bcnt, pos->bobs[p]); } uobs[ucnt++] = none; bobs[bcnt++] = none; idx[s].uobs = xmalloc(sizeof(uint64_t) * ucnt); idx[s].bobs = xmalloc(sizeof(uint64_t) * bcnt); memcpy(idx[s].uobs, uobs, ucnt * sizeof(uint64_t)); memcpy(idx[s].bobs, bobs, bcnt * sizeof(uint64_t)); } info(" Done\n"); // We will process sequences in random order in each iteration, so we // will have to permute them. The current permutation is stored in a // vector called <perm> shuffled at the start of each iteration. We // just initialize it with the identity permutation. // As we use the same gradient function than the other trainers, we need // an array to store it. These functions accumulate the gradient so we // need to clear it at start and before each new computation. As we now // which features are active and so which gradient cell are updated, we // can clear them selectively instead of fully clear the gradient each // time. // We also need an aditional vector named <q> who hold the penalty // already applied to each features. uint32_t *perm = xmalloc(sizeof(uint32_t) * S); for (uint32_t s = 0; s < S; s++) perm[s] = s; double *g = xmalloc(sizeof(double) * F); double *q = xmalloc(sizeof(double) * F); for (uint64_t f = 0; f < F; f++) g[f] = q[f] = 0.0; // We can now start training the model, we perform the requested number // of iteration, each of these going through all the sequences. For // computing the decay, we will need to keep track of the number of // already processed sequences, this is tracked by the <i> variable. double u = 0.0; grd_st_t *grd_st = grd_stnew(mdl, g); for (uint32_t k = 0, i = 0; k < K && !uit_stop; k++) { // First we shuffle the sequence by making a lot of random swap // of entry in the permutation index. for (uint32_t s = 0; s < S; s++) { const uint32_t a = rand() % S; const uint32_t b = rand() % S; const uint32_t t = perm[a]; perm[a] = perm[b]; perm[b] = t; } // And so, we can process sequence in a random order for (uint32_t sp = 0; sp < S && !uit_stop; sp++, i++) { const uint32_t s = perm[sp]; const seq_t *seq = mdl->train->seq[s]; grd_dospl(grd_st, seq); // Before applying the gradient, we have to compute the // learning rate to apply to this sequence. For this we // use an exponential decay [1, pp 481(5)] // ╬╖_i = ╬╖_0 * ╬▒^{i/S} // And at the same time, we update the total penalty // that must have been applied to each features. // u <- u + ╬╖ * rho1 / S const double n0 = mdl->opt->sgdl1.eta0; const double alpha = mdl->opt->sgdl1.alpha; const double nk = n0 * pow(alpha, (double)i / S); u = u + nk * mdl->opt->rho1 / S; // Now we apply the update to all unigrams and bigrams // observations actives in the current sequence. We must // not forget to clear the gradient for the next // sequence. for (uint32_t n = 0; idx[s].uobs[n] != none; n++) { uint64_t f = mdl->uoff[idx[s].uobs[n]]; for (uint32_t y = 0; y < Y; y++, f++) { w[f] -= nk * g[f]; applypenalty(f); g[f] = 0.0; } } for (uint32_t n = 0; idx[s].bobs[n] != none; n++) { uint64_t f = mdl->boff[idx[s].bobs[n]]; for (uint32_t d = 0; d < Y * Y; d++, f++) { w[f] -= nk * g[f]; applypenalty(f); g[f] = 0.0; } } } if (uit_stop) break; // Repport progress back to the user if (!uit_progress(mdl, k + 1, -1.0)) break; } grd_stfree(grd_st); // Cleanup allocated memory before returning for (uint32_t s = 0; s < S; s++) { free(idx[s].uobs); free(idx[s].bobs); } free(idx); free(perm); free(g); free(q); } #undef applypenalty
709
./wapiti/src/decoder.c
/* * Wapiti - A linear-chain CRF tool * * Copyright (c) 2009-2013 CNRS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <inttypes.h> #include <float.h> #include <stdint.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include "wapiti.h" #include "gradient.h" #include "model.h" #include "quark.h" #include "reader.h" #include "sequence.h" #include "thread.h" #include "tools.h" #include "decoder.h" #include "vmath.h" /****************************************************************************** * Sequence tagging * * This module implement sequence tagging using a trained model and model * evaluation on devlopment set. * * The viterbi can be quite intensive on the stack if you push in it long * sequence and use large labels set. It's less a problem than in gradient * computations but it can show up in particular cases. The fix is to call it * through the mth_spawn function and request enough stack space, this will be * fixed in next version. ******************************************************************************/ /* tag_expsc: * Compute the score lattice for classical Viterbi decoding. This is the same * as for the first step of the gradient computation with the exception that * we don't need to take the exponential of the scores as the Viterbi decoding * works in log-space. */ static int tag_expsc(mdl_t *mdl, const seq_t *seq, double *vpsi) { const double *x = mdl->theta; const uint32_t Y = mdl->nlbl; const uint32_t T = seq->len; double (*psi)[T][Y][Y] = (void *)vpsi; // We first have to compute the Ψ_t(y',y,x_t) weights defined as // Ψ_t(y',y,x_t) = \exp( ∑_k θ_k f_k(y',y,x_t) ) // So at position 't' in the sequence, for each couple (y',y) we have // to sum weights of all features. // This is the same than what we do for computing the gradient but, as // the viterbi algorithm also work in the logarithmic space, we can // remove the exponential. // // Only the observations present at this position will have a non-nul // weight so we can sum only on thoses. // // As we use only two kind of features: unigram and bigram, we can // rewrite this as // ∑_k μ_k(y, x_t) f_k(y, x_t) + ∑_k λ_k(y', y, x_t) f_k(y', y, x_t) // Where the first sum is over the unigrams features and the second is // over bigrams ones. // // This allow us to compute Ψ efficiently in two steps // 1/ we sum the unigrams features weights by looping over actives // unigrams observations. (we compute this sum once and use it // for each value of y') // 2/ we add the bigrams features weights by looping over actives // bigrams observations (we don't have to do this for t=0 since // there is no bigrams here) for (uint32_t t = 0; t < T; t++) { const pos_t *pos = &(seq->pos[t]); for (uint32_t y = 0; y < Y; y++) { double sum = 0.0; for (uint32_t n = 0; n < pos->ucnt; n++) { const uint64_t o = pos->uobs[n]; sum += x[mdl->uoff[o] + y]; } for (uint32_t yp = 0; yp < Y; yp++) (*psi)[t][yp][y] = sum; } } for (uint32_t t = 1; t < T; t++) { const pos_t *pos = &(seq->pos[t]); for (uint32_t yp = 0, d = 0; yp < Y; yp++) { for (uint32_t y = 0; y < Y; y++, d++) { double sum = 0.0; for (uint32_t n = 0; n < pos->bcnt; n++) { const uint64_t o = pos->bobs[n]; sum += x[mdl->boff[o] + d]; } (*psi)[t][yp][y] += sum; } } } return 0; } /* tag_memmsc: * Compute the score for viterbi decoding of MEMM models. This use the * previous function to compute the classical score and then normalize them * relative to the previous label. This normalization must be done in linear * space, not in logarithm one. */ static int tag_memmsc(mdl_t *mdl, const seq_t *seq, double *vpsi) { const uint32_t Y = mdl->nlbl; const uint32_t T = seq->len; tag_expsc(mdl, seq, vpsi); xvm_expma(vpsi, vpsi, 0.0, T * Y * Y); double (*psi)[T][Y][Y] = (void *)vpsi; for (uint32_t t = 0; t < T; t++) { for (uint32_t yp = 0; yp < Y; yp++) { double sum = 0.0; for (uint32_t y = 0; y < Y; y++) sum += (*psi)[t][yp][y]; for (uint32_t y = 0; y < Y; y++) (*psi)[t][yp][y] /= sum; } } return 1; } /* tag_postsc: * This function compute score lattice with posteriors. This generally result * in a slightly best labelling and allow to output normalized score for the * sequence and for each labels but this is more costly as we have to perform * a full forward backward instead of just the forward pass. */ static int tag_postsc(mdl_t *mdl, const seq_t *seq, double *vpsi) { const uint32_t Y = mdl->nlbl; const uint32_t T = seq->len; double (*psi)[T][Y][Y] = (void *)vpsi; grd_st_t *grd_st = grd_stnew(mdl, NULL); grd_st->first = 0; grd_st->last = T - 1; grd_stcheck(grd_st, seq->len); if (mdl->opt->sparse) { grd_spdopsi(grd_st, seq); grd_spfwdbwd(grd_st, seq); } else { grd_fldopsi(grd_st, seq); grd_flfwdbwd(grd_st, seq); } double (*alpha)[T][Y] = (void *)grd_st->alpha; double (*beta )[T][Y] = (void *)grd_st->beta; double *unorm = grd_st->unorm; for (uint32_t t = 0; t < T; t++) { for (uint32_t y = 0; y < Y; y++) { double e = (*alpha)[t][y] * (*beta)[t][y] * unorm[t]; for (uint32_t yp = 0; yp < Y; yp++) (*psi)[t][yp][y] = e; } } grd_stfree(grd_st); return 1; } /* tag_forced: * This function apply correction to the psi table to take account of already * known labels. If a label is known, all arcs leading or comming from other * labels at this position are NULLified and will not be selected by the * decoder. */ static void tag_forced(mdl_t *mdl, const seq_t *seq, double *vpsi, int op) { const uint32_t Y = mdl->nlbl; const uint32_t T = seq->len; const double v = op ? 0.0 : -HUGE_VAL; double (*psi)[T][Y][Y] = (void *)vpsi; for (uint32_t t = 0; t < T; t++) { const uint32_t yr = seq->pos[t].lbl; if (yr == (uint32_t)-1) continue; if (t != 0) for (uint32_t y = 0; y < Y; y++) if (y != yr) for (uint32_t yp = 0; yp < Y; yp++) (*psi)[t][yp][y] = v; if (t != T - 1) for (uint32_t y = 0; y < Y; y++) if (y != yr) for (uint32_t yn = 0; yn < Y; yn++) (*psi)[t + 1][y][yn] = v; } const uint32_t yr = seq->pos[0].lbl; if (yr != (uint32_t)-1) { for (uint32_t y = 0; y < Y; y++) { if (yr == y) continue; for (uint32_t yp = 0; yp < Y; yp++) (*psi)[0][yp][y] = v; } } } /* tag_viterbi: * This function implement the Viterbi algorithm in order to decode the most * probable sequence of labels according to the model. Some part of this code * is very similar to the computation of the gradient as expected. * * And like for the gradient, the caller is responsible to ensure there is * enough stack space. */ void tag_viterbi(mdl_t *mdl, const seq_t *seq, uint32_t out[], double *sc, double psc[]) { const uint32_t Y = mdl->nlbl; const uint32_t T = seq->len; double *vpsi = xvm_new(T * Y * Y); uint32_t *vback = xmalloc(sizeof(uint32_t) * T * Y); double (*psi) [T][Y][Y] = (void *)vpsi; uint32_t (*back)[T][Y] = (void *)vback; double *cur = xmalloc(sizeof(double) * Y); double *old = xmalloc(sizeof(double) * Y); // We first compute the scores for each transitions in the lattice of // labels. int op; if (mdl->type == 1) op = tag_memmsc(mdl, seq, vpsi); else if (mdl->opt->lblpost) op = tag_postsc(mdl, seq, vpsi); else op = tag_expsc(mdl, seq, vpsi); if (mdl->opt->force) tag_forced(mdl, seq, vpsi, op); // Now we can do the Viterbi algorithm. This is very similar to the // forward pass // | α_1(y) = Ψ_1(y,x_1) // | α_t(y) = max_{y'} α_{t-1}(y') + Ψ_t(y',y,x_t) // We just replace the sum by a max and as we do the computation in the // logarithmic space the product become a sum. (this also mean that we // don't have to worry about numerical problems) // // Next we have to walk backward over the α in order to find the best // path. In order to do this efficiently, we keep in the 'back' array // the indice of the y value selected by the max. This also mean that // we only need the current and previous value of the α vectors, not // the full matrix. for (uint32_t y = 0; y < Y; y++) cur[y] = (*psi)[0][0][y]; for (uint32_t t = 1; t < T; t++) { for (uint32_t y = 0; y < Y; y++) old[y] = cur[y]; for (uint32_t y = 0; y < Y; y++) { double bst = -HUGE_VAL; uint32_t idx = 0; for (uint32_t yp = 0; yp < Y; yp++) { double val = old[yp]; if (op) val *= (*psi)[t][yp][y]; else val += (*psi)[t][yp][y]; if (val > bst) { bst = val; idx = yp; } } (*back)[t][y] = idx; cur[y] = bst; } } // We can now build the sequence of labels predicted by the model. For // this we search in the last α vector the best value. Using this index // as a starting point in the back-pointer array we finally can decode // the best sequence. uint32_t bst = 0; for (uint32_t y = 1; y < Y; y++) if (cur[y] > cur[bst]) bst = y; if (sc != NULL) *sc = cur[bst]; for (uint32_t t = T; t > 0; t--) { const uint32_t yp = (t != 1) ? (*back)[t - 1][bst] : 0; const uint32_t y = bst; out[t - 1] = y; if (psc != NULL) psc[t - 1] = (*psi)[t - 1][yp][y]; bst = yp; } free(old); free(cur); free(vback); xvm_free(vpsi); } /* tag_nbviterbi: * This function implement the Viterbi algorithm in order to decode the N-most * probable sequences of labels according to the model. It can be used to * compute only the best one and will return the same sequence than the * previous function but will be slower to do it. */ void tag_nbviterbi(mdl_t *mdl, const seq_t *seq, uint32_t N, uint32_t out[][N], double sc[], double psc[][N]) { const uint32_t Y = mdl->nlbl; const uint32_t T = seq->len; double *vpsi = xvm_new(T * Y * Y); uint32_t *vback = xmalloc(sizeof(uint32_t) * T * Y * N); double (*psi) [T][Y ][Y] = (void *)vpsi; uint32_t (*back)[T][Y * N] = (void *)vback; double *cur = xmalloc(sizeof(double) * Y * N); double *old = xmalloc(sizeof(double) * Y * N); // We first compute the scores for each transitions in the lattice of // labels. int op; if (mdl->type == 1) op = tag_memmsc(mdl, seq, vpsi); else if (mdl->opt->lblpost) op = tag_postsc(mdl, seq, (double *)psi); else op = tag_expsc(mdl, seq, (double *)psi); if (mdl->opt->force) tag_forced(mdl, seq, vpsi, op); // Here also, it's classical but we have to keep the N best paths // leading to each nodes of the lattice instead of only the best one. // This mean that code is less trivial and the current implementation is // not the most efficient way to do this but it works well and is good // enough for the moment. // We first build the list of all incoming arcs from all paths from all // N-best nodes and next select the N-best one. There is a lot of room // here for later optimisations if needed. for (uint32_t y = 0, d = 0; y < Y; y++) { cur[d++] = (*psi)[0][0][y]; for (uint32_t n = 1; n < N; n++) cur[d++] = -DBL_MAX; } for (uint32_t t = 1; t < T; t++) { for (uint32_t d = 0; d < Y * N; d++) old[d] = cur[d]; for (uint32_t y = 0; y < Y; y++) { // 1st, build the list of all incoming double lst[Y * N]; for (uint32_t yp = 0, d = 0; yp < Y; yp++) { for (uint32_t n = 0; n < N; n++, d++) { lst[d] = old[d]; if (op) lst[d] *= (*psi)[t][yp][y]; else lst[d] += (*psi)[t][yp][y]; } } // 2nd, init the back with the N first uint32_t *bk = &(*back)[t][y * N]; for (uint32_t n = 0; n < N; n++) bk[n] = n; // 3rd, search the N highest values for (uint32_t i = N; i < N * Y; i++) { // Search the smallest current value uint32_t idx = 0; for (uint32_t n = 1; n < N; n++) if (lst[bk[n]] < lst[bk[idx]]) idx = n; // And replace it if needed if (lst[i] > lst[bk[idx]]) bk[idx] = i; } // 4th, get the new scores for (uint32_t n = 0; n < N; n++) cur[y * N + n] = lst[bk[n]]; } } // Retrieving the best paths is similar to classical Viterbi except that // we have to search for the N bet ones and there is N time more // possibles starts. for (uint32_t n = 0; n < N; n++) { uint32_t bst = 0; for (uint32_t d = 1; d < Y * N; d++) if (cur[d] > cur[bst]) bst = d; if (sc != NULL) sc[n] = cur[bst]; cur[bst] = -DBL_MAX; for (uint32_t t = T; t > 0; t--) { const uint32_t yp = (t != 1) ? (*back)[t - 1][bst] / N: 0; const uint32_t y = bst / N; out[t - 1][n] = y; if (psc != NULL) psc[t - 1][n] = (*psi)[t - 1][yp][y]; bst = (*back)[t - 1][bst]; } } free(old); free(cur); free(vback); xvm_free(vpsi); } /* tag_label: * Label a data file using the current model. This output an almost exact copy * of the input file with an additional column with the predicted label. If * the check option is specified, the input file must be labelled and the * predicted labels will be checked against the provided ones. This will * output error rates during the labelling and detailed statistics per label * at the end. */ void tag_label(mdl_t *mdl, FILE *fin, FILE *fout) { qrk_t *lbls = mdl->reader->lbl; const uint32_t Y = mdl->nlbl; const uint32_t N = mdl->opt->nbest; // We start by preparing the statistic collection to be ready if check // option is used. The stat array hold the following for each label // [0] # of reference with this label // [1] # of token we have taged with this label // [2] # of match of the two preceding uint64_t tcnt = 0, terr = 0; uint64_t scnt = 0, serr = 0; uint64_t stat[3][Y]; for (uint32_t y = 0; y < Y; y++) stat[0][y] = stat[1][y] = stat[2][y] = 0; // Next read the input file sequence by sequence and label them, we have // to take care of not discarding the raw input as we want to send it // back to the output with the additional predicted labels. while (!feof(fin)) { // So, first read an input sequence keeping the raw_t object // available, and label it with Viterbi. raw_t *raw = rdr_readraw(mdl->reader, fin); if (raw == NULL) break; seq_t *seq = rdr_raw2seq(mdl->reader, raw, mdl->opt->check | mdl->opt->force); const uint32_t T = seq->len; uint32_t *out = xmalloc(sizeof(uint32_t) * T * N); double *psc = xmalloc(sizeof(double ) * T * N); double *scs = xmalloc(sizeof(double ) * N); if (N == 1) tag_viterbi(mdl, seq, (uint32_t*)out, scs, (double*)psc); else tag_nbviterbi(mdl, seq, N, (void*)out, scs, (void*)psc); // Next we output the raw sequence with an aditional column for // the predicted labels for (uint32_t n = 0; n < N; n++) { if (mdl->opt->outsc) fprintf(fout, "# %d %f\n", (int)n, scs[n]); for (uint32_t t = 0; t < T; t++) { if (!mdl->opt->label) fprintf(fout, "%s\t", raw->lines[t]); uint32_t lbl = out[t * N + n]; const char *lblstr = qrk_id2str(lbls, lbl); fprintf(fout, "%s", lblstr); if (mdl->opt->outsc) { fprintf(fout, "\t%s", lblstr); fprintf(fout, "/%f", psc[t * N + n]); } fprintf(fout, "\n"); } fprintf(fout, "\n"); } fflush(fout); // If user provided reference labels, use them to collect // statistics about how well we have performed here. Labels // unseen at training time are discarded. if (mdl->opt->check) { bool err = false; for (uint32_t t = 0; t < T; t++) { if (seq->pos[t].lbl == (uint32_t)-1) continue; stat[0][seq->pos[t].lbl]++; stat[1][out[t * N]]++; if (seq->pos[t].lbl != out[t * N]) terr++, err = true; else stat[2][out[t * N]]++; } tcnt += T; serr += err; } // Cleanup memory used for this sequence free(scs); free(psc); free(out); rdr_freeseq(seq); rdr_freeraw(raw); // And report our progress, at regular interval we display how // much sequence are labelled and if possible the current tokens // and sequence error rates. if (++scnt % 1000 == 0) { info("%10"PRIu64" sequences labeled", scnt); if (mdl->opt->check) { const double te = (double)terr / tcnt * 100.0; const double se = (double)serr / scnt * 100.0; info("\t%5.2f%%/%5.2f%%", te, se); } info("\n"); } } // If user have provided reference labels, we have collected a lot of // statistics and we can repport global token and sequence error rate as // well as precision recall and f-measure for each labels. if (mdl->opt->check) { const double te = (double)terr / tcnt * 100.0; const double se = (double)serr / scnt * 100.0; info(" Nb sequences : %"PRIu64"\n", scnt); info(" Token error : %5.2f%%\n", te); info(" Sequence error: %5.2f%%\n", se); info("* Per label statistics\n"); for (uint32_t y = 0; y < Y; y++) { const char *lbl = qrk_id2str(lbls, y); const double Rc = (double)stat[2][y] / stat[0][y]; const double Pr = (double)stat[2][y] / stat[1][y]; const double F1 = 2.0 * (Pr * Rc) / (Pr + Rc); info(" %-6s", lbl); info(" Pr=%.2f", Pr); info(" Rc=%.2f", Rc); info(" F1=%.2f\n", F1); } } } /* eval_t: * This a state tracker used to communicate between the main eval function and * its workers threads, the <mdl> and <dat> fields are used to transmit to the * workers informations needed to make the computation, the other fields are * for returning the partial results. */ typedef struct eval_s eval_t; struct eval_s { mdl_t *mdl; dat_t *dat; uint64_t tcnt; // Processed tokens count uint64_t terr; // Tokens error found uint64_t scnt; // Processes sequences count uint64_t serr; // Sequence error found }; /* tag_evalsub: * This is where the real evaluation is done by the workers, we process data * by batch and for each batch do a simple Viterbi and scan the result to find * errors. */ static void tag_evalsub(job_t *job, uint32_t id, uint32_t cnt, eval_t *eval) { unused(id && cnt); mdl_t *mdl = eval->mdl; dat_t *dat = eval->dat; eval->tcnt = 0; eval->terr = 0; eval->scnt = 0; eval->serr = 0; // We just get a job a process all the squence in it. uint32_t count, pos; while (mth_getjob(job, &count, &pos)) { for (uint32_t s = pos; s < pos + count; s++) { // Tag the sequence with the viterbi const seq_t *seq = dat->seq[s]; const uint32_t T = seq->len; uint32_t *out = xmalloc(sizeof(uint32_t) * T); tag_viterbi(mdl, seq, out, NULL, NULL); // And check for eventual (probable ?) errors bool err = false; for (uint32_t t = 0; t < T; t++) if (seq->pos[t].lbl != out[t]) eval->terr++, err = true; eval->tcnt += T; eval->scnt += 1; eval->serr += err; free(out); } } } /* tag_eval: * Compute the token error rate and sequence error rate over the devel set (or * taining set if not available). */ void tag_eval(mdl_t *mdl, double *te, double *se) { const uint32_t W = mdl->opt->nthread; dat_t *dat = (mdl->devel == NULL) ? mdl->train : mdl->devel; // First we prepare the eval state for all the workers threads, we just // have to give them the model and dataset to use. This state will be // used to retrieve partial result they computed. eval_t *eval[W]; for (uint32_t w = 0; w < W; w++) { eval[w] = xmalloc(sizeof(eval_t)); eval[w]->mdl = mdl; eval[w]->dat = dat; } // And next, we call the workers to do the job and reduce the partial // result by summing them and computing the final error rates. mth_spawn((func_t *)tag_evalsub, W, (void *)eval, dat->nseq, mdl->opt->jobsize); uint64_t tcnt = 0, terr = 0; uint64_t scnt = 0, serr = 0; for (uint32_t w = 0; w < W; w++) { tcnt += eval[w]->tcnt; terr += eval[w]->terr; scnt += eval[w]->scnt; serr += eval[w]->serr; free(eval[w]); } *te = (double)terr / tcnt * 100.0; *se = (double)serr / scnt * 100.0; }
710
./wapiti/src/wapiti.c
/* * Wapiti - A linear-chain CRF tool * * Copyright (c) 2009-2013 CNRS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <ctype.h> #include <inttypes.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "decoder.h" #include "model.h" #include "options.h" #include "progress.h" #include "quark.h" #include "reader.h" #include "sequence.h" #include "tools.h" #include "trainers.h" #include "wapiti.h" /******************************************************************************* * Training ******************************************************************************/ static const char *typ_lst[] = { "maxent", "memm", "crf" }; static const uint32_t typ_cnt = sizeof(typ_lst) / sizeof(typ_lst[0]); static const struct { char *name; void (* train)(mdl_t *mdl); } trn_lst[] = { {"l-bfgs", trn_lbfgs}, {"sgd-l1", trn_sgdl1}, {"bcd", trn_bcd }, {"rprop", trn_rprop}, {"rprop+", trn_rprop}, {"rprop-", trn_rprop}, }; static const uint32_t trn_cnt = sizeof(trn_lst) / sizeof(trn_lst[0]); static void dotrain(mdl_t *mdl) { // Check if the user requested the type or trainer list. If this is not // the case, search them in the lists. if (!strcmp(mdl->opt->type, "list")) { info("Available types of models:\n"); for (uint32_t i = 0; i < typ_cnt; i++) info("\t%s\n", typ_lst[i]); exit(EXIT_SUCCESS); } if (!strcmp(mdl->opt->algo, "list")) { info("Available training algorithms:\n"); for (uint32_t i = 0; i < trn_cnt; i++) info("\t%s\n", trn_lst[i].name); exit(EXIT_SUCCESS); } uint32_t typ, trn; for (typ = 0; typ < typ_cnt; typ++) if (!strcmp(mdl->opt->type, typ_lst[typ])) break; if (typ == typ_cnt) fatal("unknown model type '%s'", mdl->opt->type); mdl->type = typ; for (trn = 0; trn < trn_cnt; trn++) if (!strcmp(mdl->opt->algo, trn_lst[trn].name)) break; if (trn == trn_cnt) fatal("unknown algorithm '%s'", mdl->opt->algo); // Load a previous model to train again if specified by the user. if (mdl->opt->model != NULL) { info("* Load previous model\n"); FILE *file = fopen(mdl->opt->model, "r"); if (file == NULL) pfatal("cannot open input model file"); mdl_load(mdl, file); } // Load the pattern file. This will unlock the database if previously // locked by loading a model. if (mdl->opt->pattern != NULL) { info("* Load patterns\n"); FILE *file = fopen(mdl->opt->pattern, "r"); if (file == NULL) pfatal("cannot open pattern file"); rdr_loadpat(mdl->reader, file); fclose(file); qrk_lock(mdl->reader->obs, false); } // Load the training data. When this is done we lock the quarks as we // don't want to put in the model, informations present only in the // devlopment set. info("* Load training data\n"); FILE *file = stdin; if (mdl->opt->input != NULL) { file = fopen(mdl->opt->input, "r"); if (file == NULL) pfatal("cannot open input data file"); } mdl->train = rdr_readdat(mdl->reader, file, true); if (mdl->opt->input != NULL) fclose(file); qrk_lock(mdl->reader->lbl, true); qrk_lock(mdl->reader->obs, true); if (mdl->train == NULL || mdl->train->nseq == 0) fatal("no train data loaded"); // If present, load the development set in the model. If not specified, // the training dataset will be used instead. if (mdl->opt->devel != NULL) { info("* Load development data\n"); FILE *file = fopen(mdl->opt->devel, "r"); if (file == NULL) pfatal("cannot open development file"); mdl->devel = rdr_readdat(mdl->reader, file, true); fclose(file); } // Initialize the model. If a previous model was loaded, this will be // just a resync, else the model structure will be created. if (mdl->theta == NULL) info("* Initialize the model\n"); else info("* Resync the model\n"); mdl_sync(mdl); // Display some statistics as we all love this. info("* Summary\n"); info(" nb train: %"PRIu32"\n", mdl->train->nseq); if (mdl->devel != NULL) info(" nb devel: %"PRIu32"\n", mdl->devel->nseq); info(" nb labels: %"PRIu32"\n", mdl->nlbl); info(" nb blocks: %"PRIu64"\n", mdl->nobs); info(" nb features: %"PRIu64"\n", mdl->nftr); // And train the model... info("* Train the model with %s\n", mdl->opt->algo); uit_setup(mdl); trn_lst[trn].train(mdl); uit_cleanup(mdl); // If requested compact the model. if (mdl->opt->compact) { const uint64_t O = mdl->nobs; const uint64_t F = mdl->nftr; info("* Compacting the model\n"); mdl_compact(mdl); info(" %8"PRIu64" observations removed\n", O - mdl->nobs); info(" %8"PRIu64" features removed\n", F - mdl->nftr); } // And save the trained model info("* Save the model\n"); file = stdout; if (mdl->opt->output != NULL) { file = fopen(mdl->opt->output, "w"); if (file == NULL) pfatal("cannot open output model"); } mdl_save(mdl, file); if (mdl->opt->output != NULL) fclose(file); info("* Done\n"); } /******************************************************************************* * Labeling ******************************************************************************/ static void dolabel(mdl_t *mdl) { // First, load the model provided by the user. This is mandatory to // label new datas ;-) if (mdl->opt->model == NULL) fatal("you must specify a model"); info("* Load model\n"); FILE *file = fopen(mdl->opt->model, "r"); if (file == NULL) pfatal("cannot open input model file"); mdl_load(mdl, file); // Open input and output files FILE *fin = stdin, *fout = stdout; if (mdl->opt->input != NULL) { fin = fopen(mdl->opt->input, "r"); if (fin == NULL) pfatal("cannot open input data file"); } if (mdl->opt->output != NULL) { fout = fopen(mdl->opt->output, "w"); if (fout == NULL) pfatal("cannot open output data file"); } // Do the labelling info("* Label sequences\n"); tag_label(mdl, fin, fout); info("* Done\n"); // And close files if (mdl->opt->input != NULL) fclose(fin); if (mdl->opt->output != NULL) fclose(fout); } /******************************************************************************* * Dumping ******************************************************************************/ static void dodump(mdl_t *mdl) { // Load input model file info("* Load model\n"); FILE *fin = stdin; if (mdl->opt->input != NULL) { fin = fopen(mdl->opt->input, "r"); if (fin == NULL) pfatal("cannot open input data file"); } mdl_load(mdl, fin); if (mdl->opt->input != NULL) fclose(fin); // Open output file FILE *fout = stdout; if (mdl->opt->output != NULL) { fout = fopen(mdl->opt->output, "w"); if (fout == NULL) pfatal("cannot open output data file"); } // Dump model info("* Dump model\n"); const uint32_t Y = mdl->nlbl; const uint64_t O = mdl->nobs; const qrk_t *Qlbl = mdl->reader->lbl; const qrk_t *Qobs = mdl->reader->obs; char fmt[16]; sprintf(fmt, "%%.%df\n", mdl->opt->prec); for (uint64_t o = 0; o < O; o++) { const char *obs = qrk_id2str(Qobs, o); bool empty = true; if (mdl->kind[o] & 1) { const double *w = mdl->theta + mdl->uoff[o]; for (uint32_t y = 0; y < Y; y++) { if (!mdl->opt->all && w[y] == 0.0) continue; const char *ly = qrk_id2str(Qlbl, y); fprintf(fout, "%s\t#\t%s\t", obs, ly); fprintf(fout, fmt, w[y]); empty = false; } } if (mdl->kind[o] & 2) { const double *w = mdl->theta + mdl->boff[o]; for (uint32_t d = 0; d < Y * Y; d++) { if (!mdl->opt->all && w[d] == 0.0) continue; const char *ly = qrk_id2str(Qlbl, d % Y); const char *lyp = qrk_id2str(Qlbl, d / Y); fprintf(fout, "%s\t%s\t%s\t", obs, lyp, ly); fprintf(fout, fmt, w[d]); empty = false; } } if (!empty) fprintf(fout, "\n"); } if (mdl->opt->output != NULL) fclose(fout); } /******************************************************************************* * Updating ******************************************************************************/ static void doupdt(mdl_t *mdl) { // Load input model file info("* Load model\n"); if (mdl->opt->model == NULL) fatal("no model file provided"); FILE *Min = fopen(mdl->opt->model, "r"); if (Min == NULL) pfatal("cannot open model file %s", mdl->opt->model); mdl_load(mdl, Min); fclose(Min); // Open patch file info("* Update model\n"); FILE *fin = stdin; if (mdl->opt->input != NULL) { fin = fopen(mdl->opt->input, "r"); if (fin == NULL) pfatal("cannot open update file"); } int nline = 0; while (!feof(fin)) { char *raw = rdr_readline(fin); if (raw == NULL) break; char *line = raw; nline++; // First we split the line in space separated tokens. We expect // four of them and skip empty lines. char *toks[4]; int ntoks = 0; while (ntoks < 4) { while (isspace(*line)) line++; if (*line == '\0') break; toks[ntoks++] = line; while (*line != '\0' && !isspace(*line)) line++; if (*line == '\0') break; *line++ = '\0'; } if (ntoks == 0) { free(raw); continue; } else if (ntoks != 4) { fatal("invalid line at %d", nline); } // Parse the tokens, the first three should be string maping to // observations and labels and the last should be the weight. uint64_t obs = none, yp = none, y = none; obs = qrk_str2id(mdl->reader->obs, toks[0]); if (obs == none) fatal("bad on observation on line %d", nline); if (strcmp(toks[1], "#")) { yp = qrk_str2id(mdl->reader->lbl, toks[1]); if (yp == none) fatal("bad label <%s> line %d", toks[1], nline); } y = qrk_str2id(mdl->reader->lbl, toks[2]); if (y == none) fatal("bad label <%s> line %d", toks[2], nline); double wgh = 0.0; if (sscanf(toks[3], "%lf", &wgh) != 1) fatal("bad weight on line %d", nline); const uint32_t Y = mdl->nlbl; if (yp == none) { double *w = mdl->theta + mdl->uoff[obs]; w[y] = wgh; } else { double *w = mdl->theta + mdl->boff[obs]; w[yp * Y + y] = wgh; } free(raw); } if (mdl->opt->input != NULL) fclose(fin); // If requested compact the model. if (mdl->opt->compact) { const uint64_t O = mdl->nobs; const uint64_t F = mdl->nftr; info("* Compacting the model\n"); mdl_compact(mdl); info(" %8"PRIu64" observations removed\n", O - mdl->nobs); info(" %8"PRIu64" features removed\n", F - mdl->nftr); } // And save the updated model info("* Save the model\n"); FILE *file = stdout; if (mdl->opt->output != NULL) { file = fopen(mdl->opt->output, "w"); if (file == NULL) pfatal("cannot open output model"); } mdl_save(mdl, file); if (mdl->opt->output != NULL) fclose(file); info("* Done\n"); } /******************************************************************************* * Entry point ******************************************************************************/ int main(int argc, char *argv[argc]) { // We first parse command line switchs opt_t opt = opt_defaults; opt_parse(argc, argv, &opt); // Next we prepare the model mdl_t *mdl = mdl_new(rdr_new(opt.maxent)); mdl->opt = &opt; // And switch to requested mode switch (opt.mode) { case 0: dotrain(mdl); break; case 1: dolabel(mdl); break; case 2: dodump(mdl); break; case 3: doupdt(mdl); break; } // And cleanup mdl_free(mdl); return EXIT_SUCCESS; }
711
./wapiti/src/reader.c
/* * Wapiti - A linear-chain CRF tool * * Copyright (c) 2009-2013 CNRS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <ctype.h> #include <inttypes.h> #include <stdbool.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "wapiti.h" #include "pattern.h" #include "quark.h" #include "reader.h" #include "sequence.h" #include "tools.h" /******************************************************************************* * Datafile reader * * And now come the data file reader which use the previous module to parse * the input data in order to produce seq_t objects representing interned * sequences. * * This is where the sequence will go through the tree steps to build seq_t * objects used internally. There is two way do do this. First the simpler is * to use the rdr_readseq function which directly read a sequence from a file * and convert it to a seq_t object transparently. This is how the training * and development data are loaded. * The second way consist of read a raw sequence with rdr_readraw and next * converting it to a seq_t object with rdr_raw2seq. This allow the caller to * keep the raw sequence and is used by the tagger to produce a clean output. * * There is no public interface to the tok_t object as it is intended only for * internal use in the reader as an intermediate step to apply patterns. ******************************************************************************/ /* rdr_new: * Create a new empty reader object. If no patterns are loaded before you * start using the reader the input data are assumed to be already prepared * list of features. They must either start with a prefix 'u', 'b', or '*', or * you must set autouni to true in order to automatically add a 'u' prefix. */ rdr_t *rdr_new(bool autouni) { rdr_t *rdr = xmalloc(sizeof(rdr_t)); rdr->autouni = autouni; rdr->npats = rdr->nuni = rdr->nbi = 0; rdr->ntoks = 0; rdr->pats = NULL; rdr->lbl = qrk_new(); rdr->obs = qrk_new(); return rdr; } /* rdr_free: * Free all memory used by a reader object including the quark database, so * any string returned by them must not be used after this call. */ void rdr_free(rdr_t *rdr) { for (uint32_t i = 0; i < rdr->npats; i++) pat_free(rdr->pats[i]); free(rdr->pats); qrk_free(rdr->lbl); qrk_free(rdr->obs); free(rdr); } /* rdr_freeraw: * Free all memory used by a raw_t object. */ void rdr_freeraw(raw_t *raw) { for (uint32_t t = 0; t < raw->len; t++) free(raw->lines[t]); free(raw); } /* rdr_freeseq: * Free all memory used by a seq_t object. */ void rdr_freeseq(seq_t *seq) { free(seq->raw); free(seq); } /* rdr_freedat: * Free all memory used by a dat_t object. */ void rdr_freedat(dat_t *dat) { for (uint32_t i = 0; i < dat->nseq; i++) rdr_freeseq(dat->seq[i]); free(dat->seq); free(dat); } /* rdr_readline: * Read an input line from <file>. The line can be of any size limited only by * available memory, a buffer large enough is allocated and returned. The * caller is responsible to free it. On end-of-file, NULL is returned. */ char *rdr_readline(FILE *file) { if (feof(file)) return NULL; // Initialize the buffer uint32_t len = 0, size = 16; char *buffer = xmalloc(size); // We read the line chunk by chunk until end of line, file or error while (!feof(file)) { if (fgets(buffer + len, size - len, file) == NULL) { // On NULL return there is two possible cases, either an // error or the end of file if (ferror(file)) pfatal("cannot read from file"); // On end of file, we must check if we have already read // some data or not if (len == 0) { free(buffer); return NULL; } break; } // Check for end of line, if this is not the case enlarge the // buffer and go read more data len += strlen(buffer + len); if (len == size - 1 && buffer[len - 1] != '\n') { size = size * 1.4; buffer = xrealloc(buffer, size); continue; } break; } // At this point empty line should have already catched so we just // remove the end of line if present and resize the buffer to fit the // data if (buffer[len - 1] == '\n') buffer[--len] = '\0'; return xrealloc(buffer, len + 1); } /* rdr_loadpat: * Load and compile patterns from given file and store them in the reader. As * we compile patterns, syntax errors in them will be raised at this time. */ void rdr_loadpat(rdr_t *rdr, FILE *file) { while (!feof(file)) { // Read raw input line char *line = rdr_readline(file); if (line == NULL) break; // Remove comments and trailing spaces int end = strcspn(line, "#"); while (end != 0 && isspace(line[end - 1])) end--; if (end == 0) { free(line); continue; } line[end] = '\0'; line[0] = tolower(line[0]); // Compile pattern and add it to the list pat_t *pat = pat_comp(line); rdr->npats++; switch (line[0]) { case 'u': rdr->nuni++; break; case 'b': rdr->nbi++; break; case '*': rdr->nuni++; rdr->nbi++; break; default: fatal("unknown pattern type '%c'", line[0]); } rdr->pats = xrealloc(rdr->pats, sizeof(char *) * rdr->npats); rdr->pats[rdr->npats - 1] = pat; rdr->ntoks = max(rdr->ntoks, pat->ntoks); } } /* rdr_readraw: * Read a raw sequence from given file: a set of lines terminated by end of * file or by an empty line. Return NULL if file end was reached before any * sequence was read. */ raw_t *rdr_readraw(rdr_t *rdr, FILE *file) { if (feof(file)) return NULL; // Prepare the raw sequence object uint32_t size = 32, cnt = 0; raw_t *raw = xmalloc(sizeof(raw_t) + sizeof(char *) * size); // And read the next sequence in the file, this will skip any blank line // before reading the sequence stoping at end of file or on a new blank // line. while (!feof(file)) { char *line = rdr_readline(file); if (line == NULL) break; // Check for empty line marking the end of the current sequence int len = strlen(line); while (len != 0 && isspace(line[len - 1])) len--; if (len == 0) { free(line); // Special case when no line was already read, we try // again. This allow multiple blank lines beetwen // sequences. if (cnt == 0) continue; break; } // Next, grow the buffer if needed and add the new line in it if (size == cnt) { size *= 1.4; raw = xrealloc(raw, sizeof(raw_t) + sizeof(char *) * size); } raw->lines[cnt++] = line; // In autouni mode, there will be only unigram features so we // can use small sequences to improve multi-theading. if (rdr->autouni) break; } // If no lines was read, we just free allocated memory and return NULL // to signal the end of file to the caller. Else, we adjust the object // size and return it. if (cnt == 0) { free(raw); return NULL; } raw = xrealloc(raw, sizeof(raw_t) + sizeof(char *) * cnt); raw->len = cnt; return raw; } /* rdr_mapobs: * Map an observation to its identifier, automatically adding a 'u' prefix in * 'autouni' mode. */ static uint64_t rdr_mapobs(rdr_t *rdr, const char *str) { if (!rdr->autouni) return qrk_str2id(rdr->obs, str); char tmp[strlen(str) + 2]; tmp[0] = 'u'; strcpy(tmp + 1, str); return qrk_str2id(rdr->obs, tmp); } /* rdr_rawtok2seq: * Convert a tok_t to a seq_t object taking each tokens as a feature without * applying patterns. */ static seq_t *rdr_rawtok2seq(rdr_t *rdr, const tok_t *tok) { const uint32_t T = tok->len; uint32_t size = 0; if (rdr->autouni) { size = tok->cnts[0]; } else { for (uint32_t t = 0; t < T; t++) { for (uint32_t n = 0; n < tok->cnts[t]; n++) { const char *o = tok->toks[t][n]; switch (o[0]) { case 'u': size += 1; break; case 'b': size += 1; break; case '*': size += 2; break; default: fatal("invalid feature: %s", o); } } } } seq_t *seq = xmalloc(sizeof(seq_t) + sizeof(pos_t) * T); seq->raw = xmalloc(sizeof(uint64_t) * size); seq->len = T; uint64_t *raw = seq->raw; for (uint32_t t = 0; t < T; t++) { seq->pos[t].lbl = (uint32_t)-1; seq->pos[t].ucnt = 0; seq->pos[t].uobs = raw; for (uint32_t n = 0; n < tok->cnts[t]; n++) { if (!rdr->autouni && tok->toks[t][n][0] == 'b') continue; uint64_t id = rdr_mapobs(rdr, tok->toks[t][n]); if (id != none) { (*raw++) = id; seq->pos[t].ucnt++; } } seq->pos[t].bcnt = 0; if (rdr->autouni) continue; seq->pos[t].bobs = raw; for (uint32_t n = 0; n < tok->cnts[t]; n++) { if (tok->toks[t][n][0] == 'u') continue; uint64_t id = rdr_mapobs(rdr, tok->toks[t][n]); if (id != none) { (*raw++) = id; seq->pos[t].bcnt++; } } } // And finally, if the user specified it, populate the labels if (tok->lbl != NULL) { for (uint32_t t = 0; t < T; t++) { const char *lbl = tok->lbl[t]; uint64_t id = qrk_str2id(rdr->lbl, lbl); seq->pos[t].lbl = id; } } return seq; } /* rdr_pattok2seq: * Convert a tok_t to a seq_t object by applying the patterns of the reader. */ static seq_t *rdr_pattok2seq(rdr_t *rdr, const tok_t *tok) { const uint32_t T = tok->len; // So now the tok object is ready, we can start building the seq_t // object by appling patterns. First we allocate the seq_t object. The // sequence itself as well as the sub array are allocated in one time. seq_t *seq = xmalloc(sizeof(seq_t) + sizeof(pos_t) * T); seq->raw = xmalloc(sizeof(uint64_t) * (rdr->nuni + rdr->nbi) * T); seq->len = T; uint64_t *tmp = seq->raw; for (uint32_t t = 0; t < T; t++) { seq->pos[t].lbl = (uint32_t)-1; seq->pos[t].uobs = tmp; tmp += rdr->nuni; seq->pos[t].bobs = tmp; tmp += rdr->nbi; } // Next, we can build the observations list by applying the patterns on // the tok_t sequence. for (uint32_t t = 0; t < T; t++) { pos_t *pos = &seq->pos[t]; pos->ucnt = 0; pos->bcnt = 0; for (uint32_t x = 0; x < rdr->npats; x++) { // Get the observation and map it to an identifier char *obs = pat_exec(rdr->pats[x], tok, t); uint64_t id = rdr_mapobs(rdr, obs); if (id == none) { free(obs); continue; } // If the observation is ok, add it to the lists char kind = 0; switch (obs[0]) { case 'u': kind = 1; break; case 'b': kind = 2; break; case '*': kind = 3; break; } if (kind & 1) pos->uobs[pos->ucnt++] = id; if (kind & 2) pos->bobs[pos->bcnt++] = id; free(obs); } } // And finally, if the user specified it, populate the labels if (tok->lbl != NULL) { for (uint32_t t = 0; t < T; t++) { const char *lbl = tok->lbl[t]; uint64_t id = qrk_str2id(rdr->lbl, lbl); seq->pos[t].lbl = id; } } return seq; } /* rdr_raw2seq: * Convert a raw sequence to a seq_t object suitable for training or * labelling. If lbl is true, the last column is assumed to be a label and * interned also. */ seq_t *rdr_raw2seq(rdr_t *rdr, const raw_t *raw, bool lbl) { const uint32_t T = raw->len; // Allocate the tok_t object, the label array is allocated only if they // are requested by the user. tok_t *tok = xmalloc(sizeof(tok_t) + T * sizeof(char **)); tok->cnts = xmalloc(sizeof(uint32_t) * T); tok->lbl = NULL; if (lbl == true) tok->lbl = xmalloc(sizeof(char *) * T); // We now take the raw sequence line by line and split them in list of // tokens. To reduce memory fragmentation, the raw line is copied and // his reference is kept by the first tokens, next tokens are pointer to // this copy. for (uint32_t t = 0; t < T; t++) { // Get a copy of the raw line skiping leading space characters const char *src = raw->lines[t]; while (isspace(*src)) src++; char *line = xstrdup(src); // Split it in tokens char *toks[strlen(line) / 2 + 1]; uint32_t cnt = 0; while (*line != '\0') { toks[cnt++] = line; while (*line != '\0' && !isspace(*line)) line++; if (*line == '\0') break; *line++ = '\0'; while (*line != '\0' && isspace(*line)) line++; } // If user specified that data are labelled, move the last token // to the label array. if (lbl == true) { tok->lbl[t] = toks[cnt - 1]; cnt--; } // And put the remaining tokens in the tok_t object tok->cnts[t] = cnt; tok->toks[t] = xmalloc(sizeof(char *) * cnt); memcpy(tok->toks[t], toks, sizeof(char *) * cnt); } tok->len = T; // Convert the tok_t to a seq_t seq_t *seq = NULL; if (rdr->npats == 0) seq = rdr_rawtok2seq(rdr, tok); else seq = rdr_pattok2seq(rdr, tok); // Before returning the sequence, we have to free the tok_t for (uint32_t t = 0; t < T; t++) { if (tok->cnts[t] == 0) continue; free(tok->toks[t][0]); free(tok->toks[t]); } free(tok->cnts); if (lbl == true) free(tok->lbl); free(tok); return seq; } /* rdr_readseq: * Simple wrapper around rdr_readraw and rdr_raw2seq to directly read a * sequence as a seq_t object from file. This take care of all the process * and correctly free temporary data. If lbl is true the sequence is assumed * to be labeled. * Return NULL if end of file occure before anything as been read. */ seq_t *rdr_readseq(rdr_t *rdr, FILE *file, bool lbl) { raw_t *raw = rdr_readraw(rdr, file); if (raw == NULL) return NULL; seq_t *seq = rdr_raw2seq(rdr, raw, lbl); rdr_freeraw(raw); return seq; } /* rdr_readdat: * Read a full dataset at once and return it as a dat_t object. This function * take and interpret his parameters like the single sequence reading * function. */ dat_t *rdr_readdat(rdr_t *rdr, FILE *file, bool lbl) { // Prepare dataset uint32_t size = 1000; dat_t *dat = xmalloc(sizeof(dat_t)); dat->nseq = 0; dat->mlen = 0; dat->lbl = lbl; dat->seq = xmalloc(sizeof(seq_t *) * size); // Load sequences while (!feof(file)) { // Read the next sequence seq_t *seq = rdr_readseq(rdr, file, lbl); if (seq == NULL) break; // Grow the buffer if needed if (dat->nseq == size) { size *= 1.4; dat->seq = xrealloc(dat->seq, sizeof(seq_t *) * size); } // And store the sequence dat->seq[dat->nseq++] = seq; dat->mlen = max(dat->mlen, seq->len); if (dat->nseq % 1000 == 0) info("%7"PRIu32" sequences loaded\n", dat->nseq); } // If no sequence readed, cleanup and repport if (dat->nseq == 0) { free(dat->seq); free(dat); return NULL; } // Adjust the dataset size and return if (size > dat->nseq) dat->seq = xrealloc(dat->seq, sizeof(seq_t *) * dat->nseq); return dat; } /* rdr_load: * Read from the given file a reader saved previously with rdr_save. The given * reader must be empty, comming fresh from rdr_new. Be carefull that this * function performs almost no checks on the input data, so if you modify the * reader and make a mistake, it will probably result in a crash. */ void rdr_load(rdr_t *rdr, FILE *file) { const char *err = "broken file, invalid reader format"; int autouni = rdr->autouni; fpos_t pos; fgetpos(file, &pos); if (fscanf(file, "#rdr#%"PRIu32"/%"PRIu32"/%d\n", &rdr->npats, &rdr->ntoks, &autouni) != 3) { // This for compatibility with previous file format fsetpos(file, &pos); if (fscanf(file, "#rdr#%"PRIu32"/%"PRIu32"\n", &rdr->npats, &rdr->ntoks) != 2) fatal(err); } rdr->autouni = autouni; rdr->nuni = rdr->nbi = 0; if (rdr->npats != 0) { rdr->pats = xmalloc(sizeof(pat_t *) * rdr->npats); for (uint32_t p = 0; p < rdr->npats; p++) { char *pat = ns_readstr(file); rdr->pats[p] = pat_comp(pat); switch (tolower(pat[0])) { case 'u': rdr->nuni++; break; case 'b': rdr->nbi++; break; case '*': rdr->nuni++; rdr->nbi++; break; } } } qrk_load(rdr->lbl, file); qrk_load(rdr->obs, file); } /* rdr_save: * Save the reader to the given file so it can be loaded back. The save format * is plain text and portable accros computers. */ void rdr_save(const rdr_t *rdr, FILE *file) { if (fprintf(file, "#rdr#%"PRIu32"/%"PRIu32"/%d\n", rdr->npats, rdr->ntoks, rdr->autouni) < 0) pfatal("cannot write to file"); for (uint32_t p = 0; p < rdr->npats; p++) ns_writestr(file, rdr->pats[p]->src); qrk_save(rdr->lbl, file); qrk_save(rdr->obs, file); }
712
./wapiti/src/rprop.c
/* * Wapiti - A linear-chain CRF tool * * Copyright (c) 2009-2013 CNRS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <inttypes.h> #include <float.h> #include <math.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "wapiti.h" #include "gradient.h" #include "model.h" #include "options.h" #include "progress.h" #include "tools.h" #include "thread.h" #include "vmath.h" #define EPSILON (DBL_EPSILON * 64.0) #define sign(v) ((v) < -EPSILON ? -1.0 : ((v) > EPSILON ? 1.0 : 0.0)) #define sqr(v) ((v) * (v)) /****************************************************************************** * Resilient propagation optimizer * * This is an implementation of the RPROP algorithm (resilient propagation) * described by Riedmiller and Braun in [1] with an adaptation to be useable * with l1 regularization. * The adaptation consist of using a pseudo-gradient similar to the one used * in OWL-QN to choose an orthant at iterations steps and projecting the step * in this orthant before the weight update. * * [1] A direct adaptive method for faster backpropagation learning: The RPROP * algorithm, Martin Riedmiller and Heinrich Braun, IEEE International * Conference on Neural Networks, San Francisco, USA, 586-591, March 1993. ******************************************************************************/ typedef struct rprop_s rprop_t; struct rprop_s { mdl_t *mdl; double *xp; double *stp; double *g; double *gp; }; /* trn_rpropsub: * Partial update of the weight vector including partial gradient in case of * l1 regularisation. The sub vector updated depend on the id and cnt * parameter given, the job scheduling system is not used here as we can * easily split processing in equals parts. */ static void trn_rpropsub(job_t *job, uint32_t id, uint32_t cnt, rprop_t *st) { unused(job); mdl_t *mdl = st->mdl; const uint64_t F = mdl->nftr; const double stpmin = mdl->opt->rprop.stpmin; const double stpmax = mdl->opt->rprop.stpmax; const double stpinc = mdl->opt->rprop.stpinc; const double stpdec = mdl->opt->rprop.stpdec; const bool wbt = strcmp(mdl->opt->algo, "rprop-"); const double rho1 = mdl->opt->rho1; const int l1 = (rho1 != 0.0) ? mdl->opt->rprop.cutoff + 1: 0; double *x = mdl->theta; double *xp = st->xp, *stp = st->stp; double *g = st->g, *gp = st->gp; const uint64_t from = F * id / cnt; const uint64_t to = F * (id + 1) / cnt; for (uint64_t f = from; f < to; f++) { double pg = g[f]; // If there is a l1 component in the regularization component, // we either project the gradient in the current orthant or // check for cutdown depending on the projection scheme wanted. if (l1 == 1) { if (x[f] < -EPSILON) pg -= rho1; else if (x[f] > EPSILON) pg += rho1; else if (g[f] < -rho1) pg += rho1; else if (g[f] > rho1) pg -= rho1; else pg = 0.0; } else if (l1 && sqr(g[f] + rho1 * sign(x[f])) < sqr(rho1)) { if (x[f] == 0.0 || ( gp[f] * g[f] < 0.0 && xp[f] * x[f] < 0.0)) { if (wbt) xp[f] = x[f]; x[f] = 0.0; gp[f] = g[f]; continue; } } const double sgp = sign(gp[f]); const double spg = sign(pg); // Next we adjust the step depending of the new and // previous gradient values. if (sgp * spg > 0.0) stp[f] = min(stp[f] * stpinc, stpmax); else if (sgp * spg < 0.0) stp[f] = max(stp[f] * stpdec, stpmin); // Finally update the weight. if there is l1 penalty // and the pseudo gradient projection is used, we have to // project back the update in the choosen orthant. if (!wbt || sgp * spg > 0.0) { double dlt = stp[f] * -sign(g[f]); if (l1 == 1 && dlt * spg >= 0.0) dlt = 0.0; if (wbt) xp[f] = x[f]; x[f] += dlt; } else if (sgp * spg < -0.0) { x[f] = xp[f]; g[f] = 0.0; } else { xp[f] = x[f]; if (l1 != 1) x[f] += stp[f] * -spg; } gp[f] = g[f]; } } void trn_rprop(mdl_t *mdl) { const uint64_t F = mdl->nftr; const uint32_t K = mdl->opt->maxiter; const uint32_t W = mdl->opt->nthread; const bool wbt = strcmp(mdl->opt->algo, "rprop-"); const int cut = mdl->opt->rprop.cutoff; // Allocate state memory and initialize it double *xp = NULL, *stp = xvm_new(F); double *g = xvm_new(F), *gp = xvm_new(F); if (wbt && !cut) xp = xvm_new(F); for (uint64_t f = 0; f < F; f++) { if (wbt && !cut) xp[f] = 0.0; gp[f] = 0.0; stp[f] = 0.1; } // Restore a saved state if given by the user if (mdl->opt->rstate != NULL) { const char *err = "invalid state file"; FILE *file = fopen(mdl->opt->rstate, "r"); if (file == NULL) fatal("failed to open input state file"); int type; uint64_t nftr; if (fscanf(file, "#state#%d#%"SCNu64"\n", &type, &nftr) != 2) fatal(err); if (type != 3) fatal("state is not for rprop model"); for (uint64_t i = 0; i < nftr; i++) { uint64_t f; double vxp, vstp, vgp; if (fscanf(file, "%"PRIu64" %la %la %la\n", &f, &vxp, &vstp, &vgp) != 4) fatal(err); if (wbt && !cut) xp[f] = vxp; gp[f] = vgp; stp[f] = vstp; } fclose(file); } // Prepare the rprop state used to send information to the rprop worker // about updating weight using the gradient. rprop_t *st = xmalloc(sizeof(rprop_t)); st->mdl = mdl; st->xp = xp; st->stp = stp; st->g = g; st->gp = gp; rprop_t *rprop[W]; for (uint32_t w = 0; w < W; w++) rprop[w] = st; // Prepare the gradient state for the distributed gradient computation. grd_t *grd = grd_new(mdl, g); // And iterate the gradient computation / weight update process until // convergence or stop request for (uint32_t k = 0; !uit_stop && k < K; k++) { double fx = grd_gradient(grd); if (uit_stop) break; mth_spawn((func_t *)trn_rpropsub, W, (void **)rprop, 0, 0); if (uit_progress(mdl, k + 1, fx) == false) break; } // Save state if user requested it if (mdl->opt->sstate != NULL) { FILE *file = fopen(mdl->opt->sstate, "w"); if (file == NULL) fatal("failed to open output state file"); fprintf(file, "#state#3#%"PRIu64"\n", F); for (uint64_t f = 0; f < F; f++) { double vxp = xp != NULL ? xp[f] : 0.0; double vstp = stp[f], vgp = gp[f]; fprintf(file, "%"PRIu64" ", f); fprintf(file, "%la %la %la\n", vxp, vstp, vgp); } fclose(file); } // Free all allocated memory if (wbt && !cut) xvm_free(xp); xvm_free(g); xvm_free(gp); xvm_free(stp); grd_free(grd); free(st); }
713
./wapiti/src/model.c
/* * Wapiti - A linear-chain CRF tool * * Copyright (c) 2009-2013 CNRS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <inttypes.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "wapiti.h" #include "model.h" #include "options.h" #include "quark.h" #include "reader.h" #include "tools.h" #include "vmath.h" /******************************************************************************* * Linear chain CRF model * * There is three concept that must be well understand here, the labels, * observations, and features. The labels are the values predicted by the * model at each point of the sequence and denoted by Y. The observations are * the values, at each point of the sequence, given to the model in order to * predict the label and denoted by O. A feature is a test on both labels and * observations, denoted by F. In linear chain CRF there is two kinds of * features : * - unigram feature who represent a test on the observations at the current * point and the label at current point. * - bigram feature who represent a test on the observation at the current * point and two labels : the current one and the previous one. * So for each observation, there Y possible unigram features and Y*Y possible * bigram features. The kind of features used by the model for a given * observation depend on the pattern who generated it. ******************************************************************************/ /* mdl_new: * Allocate a new empty model object linked with the given reader. The model * have to be synchronized before starting training or labelling. If you not * provide a reader (as it will loaded from file for example) you must be sure * to set one in the model before any attempts to synchronize it. */ mdl_t *mdl_new(rdr_t *rdr) { mdl_t *mdl = xmalloc(sizeof(mdl_t)); mdl->nlbl = mdl->nobs = mdl->nftr = 0; mdl->kind = NULL; mdl->uoff = mdl->boff = NULL; mdl->theta = NULL; mdl->train = mdl->devel = NULL; mdl->reader = rdr; mdl->werr = NULL; mdl->total = 0.0; return mdl; } /* mdl_free: * Free all memory used by a model object inculding the reader and datasets * loaded in the model. */ void mdl_free(mdl_t *mdl) { free(mdl->kind); free(mdl->uoff); free(mdl->boff); if (mdl->theta != NULL) xvm_free(mdl->theta); if (mdl->train != NULL) rdr_freedat(mdl->train); if (mdl->devel != NULL) rdr_freedat(mdl->devel); if (mdl->reader != NULL) rdr_free(mdl->reader); if (mdl->werr != NULL) free(mdl->werr); free(mdl); } /* mdl_sync: * Synchronize the model with its reader. As the model is just a placeholder * for features weights and interned sequences, it know very few about the * labels and observations, all the informations are kept in the reader. A * sync will get the labels and observations count as well as the observation * kind from the reader and build internal structures representing the model. * * If the model was already synchronized before, there is an existing model * incompatible with the new one to be created. In this case there is two * possibility : * - If only new observations was added, the weights of the old ones remain * valid and are kept as they form a probably good starting point for * training the new model, the new observation get a 0 weight ; * - If new labels was added, the old model are trully meaningless so we * have to fully discard them and build a new empty model. * In any case, you must never change existing labels or observations, if this * happen, you need to create a new model and destroy this one. * * After synchronization, the labels and observations databases are locked to * prevent new one to be created. You must unlock them explicitly if needed. * This reduce the risk of mistakes. */ void mdl_sync(mdl_t *mdl) { const uint32_t Y = qrk_count(mdl->reader->lbl); const uint64_t O = qrk_count(mdl->reader->obs); // If model is already synchronized, do nothing and just return if (mdl->nlbl == Y && mdl->nobs == O) return; if (Y == 0 || O == 0) fatal("cannot synchronize an empty model"); // If new labels was added, we have to discard all the model. In this // case we also display a warning as this is probably not expected by // the user. If only new observations was added, we will try to expand // the model. uint64_t oldF = mdl->nftr; uint64_t oldO = mdl->nobs; if (mdl->nlbl != Y && mdl->nlbl != 0) { warning("labels count changed, discarding the model"); free(mdl->kind); mdl->kind = NULL; free(mdl->uoff); mdl->uoff = NULL; free(mdl->boff); mdl->boff = NULL; if (mdl->theta != NULL) { xvm_free(mdl->theta); mdl->theta = NULL; } oldF = oldO = 0; } mdl->nlbl = Y; mdl->nobs = O; // Allocate the observations datastructure. If the model is empty or // discarded, a new one iscreated, else the old one is expanded. char *kind = xrealloc(mdl->kind, sizeof(char ) * O); uint64_t *uoff = xrealloc(mdl->uoff, sizeof(uint64_t) * O); uint64_t *boff = xrealloc(mdl->boff, sizeof(uint64_t) * O); mdl->kind = kind; mdl->uoff = uoff; mdl->boff = boff; // Now, we can setup the features. For each new observations we fill the // kind and offsets arrays and count total number of features as well. uint64_t F = oldF; for (uint64_t o = oldO; o < O; o++) { const char *obs = qrk_id2str(mdl->reader->obs, o); switch (obs[0]) { case 'u': kind[o] = 1; break; case 'b': kind[o] = 2; break; case '*': kind[o] = 3; break; } if (kind[o] & 1) uoff[o] = F, F += Y; if (kind[o] & 2) boff[o] = F, F += Y * Y; } mdl->nftr = F; // We can finally grow the features weights vector itself. We set all // the new features to 0.0 but don't touch the old ones. // This is a bit tricky as aligned malloc cannot be simply grown so we // have to allocate a new vector and copy old values ourself. if (oldF != 0) { double *new = xvm_new(F); for (uint64_t f = 0; f < oldF; f++) new[f] = mdl->theta[f]; xvm_free(mdl->theta); mdl->theta = new; } else { mdl->theta = xvm_new(F); } for (uint64_t f = oldF; f < F; f++) mdl->theta[f] = 0.0; // And lock the databases qrk_lock(mdl->reader->lbl, true); qrk_lock(mdl->reader->obs, true); } /* mdl_compact: * Comapct the given model by removing from it all observation who lead to * zero actives features. On model trained with l1 regularization this can * lead to a drastic model size reduction and so to faster loading, training * and labeling. */ void mdl_compact(mdl_t *mdl) { const uint32_t Y = mdl->nlbl; // We first build the new observation list with only observations which // lead to at least one active feature. At the same time we build the // translation table which map the new observations index to the old // ones. info(" - Scan the model\n"); qrk_t *old_obs = mdl->reader->obs; qrk_t *new_obs = qrk_new(); uint64_t *trans = xmalloc(sizeof(uint64_t) * mdl->nobs); for (uint64_t oldo = 0; oldo < mdl->nobs; oldo++) { bool active = false; if (mdl->kind[oldo] & 1) for (uint32_t y = 0; y < Y; y++) if (mdl->theta[mdl->uoff[oldo] + y] != 0.0) active = true; if (mdl->kind[oldo] & 2) for (uint32_t d = 0; d < Y * Y; d++) if (mdl->theta[mdl->boff[oldo] + d] != 0.0) active = true; if (!active) continue; const char *str = qrk_id2str(old_obs, oldo); const uint64_t newo = qrk_str2id(new_obs, str); trans[newo] = oldo; } mdl->reader->obs = new_obs; // Now we save the old model features informations and build a new one // corresponding to the compacted model. uint64_t *old_uoff = mdl->uoff; mdl->uoff = NULL; uint64_t *old_boff = mdl->boff; mdl->boff = NULL; double *old_theta = mdl->theta; mdl->theta = NULL; free(mdl->kind); mdl->kind = NULL; mdl->nlbl = mdl->nobs = mdl->nftr = 0; mdl_sync(mdl); // The model is now ready, so we copy in it the features weights from // the old model for observations we have kept. info(" - Compact it\n"); for (uint64_t newo = 0; newo < mdl->nobs; newo++) { const uint64_t oldo = trans[newo]; if (mdl->kind[newo] & 1) { double *src = old_theta + old_uoff[oldo]; double *dst = mdl->theta + mdl->uoff[newo]; for (uint32_t y = 0; y < Y; y++) dst[y] = src[y]; } if (mdl->kind[newo] & 2) { double *src = old_theta + old_boff[oldo]; double *dst = mdl->theta + mdl->boff[newo]; for (uint32_t d = 0; d < Y * Y; d++) dst[d] = src[d]; } } // And cleanup free(trans); qrk_free(old_obs); free(old_uoff); free(old_boff); xvm_free(old_theta); } /* mdl_save: * Save a model to be restored later in a platform independant way. */ void mdl_save(mdl_t *mdl, FILE *file) { uint64_t nact = 0; for (uint64_t f = 0; f < mdl->nftr; f++) if (mdl->theta[f] != 0.0) nact++; fprintf(file, "#mdl#%d#%"PRIu64"\n", mdl->type, nact); rdr_save(mdl->reader, file); for (uint64_t f = 0; f < mdl->nftr; f++) if (mdl->theta[f] != 0.0) fprintf(file, "%"PRIu64"=%la\n", f, mdl->theta[f]); } /* mdl_load: * Read back a previously saved model to continue training or start labeling. * The returned model is synced and the quarks are locked. You must give to * this function an empty model fresh from mdl_new. */ void mdl_load(mdl_t *mdl, FILE *file) { const char *err = "invalid model format"; uint64_t nact = 0; int type; if (fscanf(file, "#mdl#%d#%"SCNu64"\n", &type, &nact) == 2) { mdl->type = type; } else { rewind(file); if (fscanf(file, "#mdl#%"SCNu64"\n", &nact) == 1) mdl->type = 0; else fatal(err); } rdr_load(mdl->reader, file); mdl_sync(mdl); for (uint64_t i = 0; i < nact; i++) { uint64_t f; double v; if (fscanf(file, "%"SCNu64"=%la\n", &f, &v) != 2) fatal(err); mdl->theta[f] = v; } }
714
./wapiti/src/pattern.c
/* * Wapiti - A linear-chain CRF tool * * Copyright (c) 2009-2013 CNRS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <ctype.h> #include <inttypes.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "pattern.h" #include "sequence.h" #include "tools.h" /****************************************************************************** * A simple regular expression matcher * * This module implement a simple regular expression matcher, it implement * just a subset of the classical regexp simple to implement but sufficient * for most usages and avoid to add a dependency to a full regexp library. * * The recognized subset is quite simple. First for matching characters : * . -> match any characters * \x -> match a character class (in uppercase, match the complement) * \d : digit \a : alpha \w : alpha + digit * \l : lowercase \u : uppercase \p : punctuation * \s : space * or escape a character * x -> any other character match itself * And the constructs : * ^ -> at the begining of the regexp, anchor it at start of string * $ -> at the end of regexp, anchor it at end of string * * -> match any number of repetition of the previous character * ? -> optionally match the previous character * * This subset is implemented quite efficiently using recursion. All recursive * calls are tail-call so they should be optimized by the compiler. As we do * direct interpretation, we have to backtrack so performance can be very poor * on specialy designed regexp. This is not a problem as the regexp as well as * the string is expected to be very simple here. If this is not the case, you * better have to prepare your data better. ******************************************************************************/ /* rex_matchit: * Match a single caracter at the start fo the string. The character might be * a plain char, a dot or char class. */ static bool rex_matchit(const char *ch, const char *str) { if (str[0] == '\0') return false; if (ch[0] == '.') return true; if (ch[0] == '\\') { switch (ch[1]) { case 'a': return isalpha(str[0]); case 'd': return isdigit(str[0]); case 'l': return islower(str[0]); case 'p': return ispunct(str[0]); case 's': return isspace(str[0]); case 'u': return isupper(str[0]); case 'w': return isalnum(str[0]); case 'A': return !isalpha(str[0]); case 'D': return !isdigit(str[0]); case 'L': return !islower(str[0]); case 'P': return !ispunct(str[0]); case 'S': return !isspace(str[0]); case 'U': return !isupper(str[0]); case 'W': return !isalnum(str[0]); } return ch[1] == str[0]; } return ch[0] == str[0]; } /* rex_matchme: * Match a regular expresion at the start of the string. If a match is found, * is length is returned in len. The mathing is done through tail-recursion * for good performances. */ static bool rex_matchme(const char *re, const char *str, uint32_t *len) { // Special check for end of regexp if (re[0] == '\0') return true; if (re[0] == '$' && re[1] == '\0') return (str[0] == '\0'); // Get first char of regexp const char *ch = re; const char *nxt = re + 1 + (ch[0] == '\\'); // Special check for the following construct "x**" where the first star // is consumed normally but lead the second (which is wrong) to be // interpreted as a char to mach as if it was escaped (and same for the // optional construct) if (*ch == '*' || *ch == '?') fatal("unescaped * or ? in regexp: %s", re); // Handle star repetition if (nxt[0] == '*') { nxt++; do { const uint32_t save = *len; if (rex_matchme(nxt, str, len)) return true; *len = save + 1; } while (rex_matchit(ch, str++)); return false; } // Handle optional if (nxt[0] == '?') { nxt++; if (rex_matchit(ch, str)) { (*len)++; if (rex_matchme(nxt, str + 1, len)) return true; (*len)--; } return rex_matchme(nxt, str, len); } // Classical char matching (*len)++; if (rex_matchit(ch, str)) return rex_matchme(nxt, str + 1, len); return false; } /* rex_match: * Match a regular expresion in the given string. If a match is found, the * position of the start of the match is returned and is len is returned in * len, else -1 is returned. */ static int32_t rex_match(const char *re, const char *str, uint32_t *len) { // Special case for anchor at start if (*re == '^') { *len = 0; if (rex_matchme(re + 1, str, len)) return 0; return -1; } // And general case for any position int32_t pos = 0; do { *len = 0; if (rex_matchme(re, str + pos, len)) return pos; } while (str[pos++] != '\0'); // Matching failed return -1; } /******************************************************************************* * Pattern handling * * Patterns are the heart the data input process, they provide a way to tell * Wapiti how the interesting information can be extracted from the input * data. A pattern is simply a string who embed special commands about tokens * to extract from the input sequence. They are compiled to a special form * used during data loading. * For training, each position of a sequence hold a list of observation made * at this position, pattern give a way to specify these observations. * * During sequence loading, all patterns are applied at each position to * produce a list of string representing the observations which will be in * turn transformed to numerical identifiers. This module take care of * building the string representation. * * As said, a patern is a string with specific commands in the forms %c[...] * where 'c' is the command with arguments between the bracket. All commands * take at least to numerical arguments which define a token in the input * sequence. The first one is an offset from the current position and the * second one is a column number. With these two parameters, we get a string * in the input sequence on which we apply the command. * * All command are specified with a character and result in a string which * will replace the command in the pattern string. If the command character is * lower case, the result is copied verbatim, if it is uppercase, the result * is copied with casing removed. The following commands are available: * 'x' -- result is the token itself * 't' -- test if a regular expression match the token. Result will be * either "true" or "false" * 'm' -- match a regular expression on the token. Result is the first * substring matched. ******************************************************************************/ /* pat_comp: * Compile the pattern to a form more suitable to easily apply it on tokens * list during data reading. The given pattern string is interned in the * compiled pattern and will be freed with it, so you don't have to take care * of it and must not modify it after the compilation. */ pat_t *pat_comp(char *p) { pat_t *pat = NULL; // Allocate memory for the compiled pattern, the allocation is based // on an over-estimation of the number of required item. As compiled // pattern take a neglectible amount of memory, this waste is not // important. uint32_t mitems = 0; for (uint32_t pos = 0; p[pos] != '\0'; pos++) if (p[pos] == '%') mitems++; mitems = mitems * 2 + 1; pat = xmalloc(sizeof(pat_t) + sizeof(pat->items[0]) * mitems); pat->src = p; // Next, we go through the pattern compiling the items as they are // found. Commands are parsed and put in a corresponding item, and // segment of char not in a command are put in a 's' item. uint32_t nitems = 0; uint32_t ntoks = 0; uint32_t pos = 0; while (p[pos] != '\0') { pat_item_t *item = &(pat->items[nitems++]); item->value = NULL; if (p[pos] == '%') { // This is a command, so first parse its type and check // its a valid one. Next prepare the item. const char type = tolower(p[pos + 1]); if (type != 'x' && type != 't' && type != 'm') fatal("unknown command type: '%c'", type); item->type = type; item->caps = (p[pos + 1] != type); pos += 2; // Next we parse the offset and column and store them in // the item. const char *at = p + pos; uint32_t col; int32_t off; int nch; item->absolute = false; if (sscanf(at, "[@%"SCNi32",%"SCNu32"%n", &off, &col, &nch) == 2) item->absolute = true; else if (sscanf(at, "[%"SCNi32",%"SCNu32"%n", &off, &col, &nch) != 2) fatal("invalid pattern: %s", p); item->offset = off; item->column = col; ntoks = max(ntoks, col); pos += nch; // And parse the end of the argument list, for 'x' there // is nothing to read but for 't' and 'm' we have to get // read the regexp. if (type == 't' || type == 'm') { if (p[pos] != ',' && p[pos + 1] != '"') fatal("missing arg in pattern: %s", p); const int32_t start = (pos += 2); while (p[pos] != '\0') { if (p[pos] == '"') break; if (p[pos] == '\\' && p[pos+1] != '\0') pos++; pos++; } if (p[pos] != '"') fatal("unended argument: %s", p); const int32_t len = pos - start; item->value = xmalloc(sizeof(char) * (len + 1)); memcpy(item->value, p + start, len); item->value[len] = '\0'; pos++; } // Just check the end of the arg list and loop. if (p[pos] != ']') fatal("missing end of pattern: %s", p); pos++; } else { // No command here, so build an 's' item with the chars // until end of pattern or next command and put it in // the list. const int32_t start = pos; while (p[pos] != '\0' && p[pos] != '%') pos++; const int32_t len = pos - start; item->type = 's'; item->caps = false; item->value = xmalloc(sizeof(char) * (len + 1)); memcpy(item->value, p + start, len); item->value[len] = '\0'; } } pat->ntoks = ntoks; pat->nitems = nitems; return pat; } /* pat_exec: * Execute a compiled pattern at position 'at' in the given tokens sequences * in order to produce an observation string. The string is returned as a * newly allocated memory block and the caller is responsible to free it when * not needed anymore. */ char *pat_exec(const pat_t *pat, const tok_t *tok, uint32_t at) { static char *bval[] = {"_x-1", "_x-2", "_x-3", "_x-4", "_x-#"}; static char *eval[] = {"_x+1", "_x+2", "_x+3", "_x+4", "_x+#"}; const uint32_t T = tok->len; // Prepare the buffer who will hold the result uint32_t size = 16, pos = 0; char *buffer = xmalloc(sizeof(char) * size); // And loop over the compiled items for (uint32_t it = 0; it < pat->nitems; it++) { const pat_item_t *item = &(pat->items[it]); char *value = NULL; uint32_t len = 0; // First, if needed, we retrieve the token at the referenced // position in the sequence. We store it in value and let the // command handler do what it need with it. if (item->type != 's') { int pos = item->offset; if (item->absolute) { if (item->offset < 0) pos += T; else pos--; } else { pos += at; } uint32_t col = item->column; if (pos < 0) value = bval[min(-pos - 1, 4)]; else if (pos >= (int32_t)T) value = eval[min( pos - (int32_t)T, 4)]; else if (col >= tok->cnts[pos]) fatal("missing tokens, cannot apply pattern"); else value = tok->toks[pos][col]; } // Next, we handle the command, 's' and 'x' are very simple but // 't' and 'm' require us to call the regexp matcher. if (item->type == 's') { value = item->value; len = strlen(value); } else if (item->type == 'x') { len = strlen(value); } else if (item->type == 't') { if (rex_match(item->value, value, &len) == -1) value = "false"; else value = "true"; len = strlen(value); } else if (item->type == 'm') { int32_t pos = rex_match(item->value, value, &len); if (pos == -1) len = 0; value += pos; } // And we add it to the buffer, growing it if needed. If the // user requested it, we also remove caps from the string. if (pos + len >= size - 1) { while (pos + len >= size - 1) size = size * 1.4; buffer = xrealloc(buffer, sizeof(char) * size); } memcpy(buffer + pos, value, len); if (item->caps) for (uint32_t i = pos; i < pos + len; i++) buffer[i] = tolower(buffer[i]); pos += len; } // Adjust the result and return it. buffer[pos++] = '\0'; buffer = xrealloc(buffer, sizeof(char) * pos); return buffer; } /* pat_free: * Free all memory used by a compiled pattern object. Note that this will free * the pointer to the source string given to pat_comp so you must be sure to * not use this pointer again. */ void pat_free(pat_t *pat) { for (uint32_t it = 0; it < pat->nitems; it++) free(pat->items[it].value); free(pat->src); free(pat); }
715
./wapiti/src/bcd.c
/* * Wapiti - A linear-chain CRF tool * * Copyright (c) 2009-2013 CNRS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <assert.h> #include <math.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include "wapiti.h" #include "gradient.h" #include "model.h" #include "options.h" #include "progress.h" #include "sequence.h" #include "tools.h" #include "vmath.h" /****************************************************************************** * Blockwise Coordinates descent trainer * The gradient and hessian computation used for the BCD is very similar to * the generic one define below but there is some important differences: * - The forward and backward recursions doesn't have to be performed fully * but just in the range of activity of the considered block. So if the * block is active only at position t, the alpha recusion is done from 1 * to t and the beta one from T to t, dividing the amount of computations * by 2. * - Samely the update of the gradient and hessian have to be done only at * position where the block is active, so in the common case where the * block is active only once in the sequence, the improvement can be huge. * - And finally, there is no need to compute the logloss, which can take a * long time due to the computation of the log()s. ******************************************************************************/ typedef struct bcd_s bcd_t; struct bcd_s { double *ugrd; // [Y] double *uhes; // [Y] double *bgrd; // [Y][Y] double *bhes; // [Y][Y] uint32_t *actpos; // [T] uint32_t actcnt; grd_st_t *grd_st; }; /* bcd_soft: * The softmax function. */ static double bcd_soft(double z, double r) { if (z > r) return z - r; if (z < -r) return z + r; return 0.0; } /* bcd_actpos: * List position where the given block is active in the sequence and setup the * limits for the fwd/bwd. */ static void bcd_actpos(mdl_t *mdl, bcd_t *bcd, const seq_t *seq, uint64_t o) { const uint32_t T = seq->len; uint32_t *actpos = bcd->actpos; uint32_t actcnt = 0; for (uint32_t t = 0; t < T; t++) { const pos_t *pos = &(seq->pos[t]); bool ok = false; if (mdl->kind[o] & 1) for (uint32_t n = 0; !ok && n < pos->ucnt; n++) if (pos->uobs[n] == o) ok = true; if (mdl->kind[o] & 2) for (uint32_t n = 0; !ok && n < pos->bcnt; n++) if (pos->bobs[n] == o) ok = true; if (!ok) continue; actpos[actcnt++] = t; } assert(actcnt != 0); bcd->actcnt = actcnt; bcd->grd_st->first = actpos[0]; bcd->grd_st->last = actpos[actcnt - 1]; } /* bct_flgradhes: * Update the gradient and hessian for <blk> on sequence <seq>. This one is * very similar than the trn_spupgrad function but does the computation only * at active pos and approximate also the hessian. */ static void bcd_flgradhes(mdl_t *mdl, bcd_t *bcd, const seq_t *seq, uint64_t o) { const grd_st_t *grd_st = bcd->grd_st; const uint32_t Y = mdl->nlbl; const uint32_t T = seq->len; const double (*psi )[T][Y][Y] = (void *)grd_st->psi; const double (*alpha)[T][Y] = (void *)grd_st->alpha; const double (*beta )[T][Y] = (void *)grd_st->beta; const double *unorm = grd_st->unorm; const double *bnorm = grd_st->bnorm; const uint32_t *actpos = bcd->actpos; const uint32_t actcnt = bcd->actcnt; double *ugrd = bcd->ugrd; double *uhes = bcd->uhes; double *bgrd = bcd->bgrd; double *bhes = bcd->bhes; // Update the gradient and the hessian but here we sum only on the // positions where the block is active for unigrams features if (mdl->kind[o] & 1) { for (uint32_t n = 0; n < actcnt; n++) { const uint32_t t = actpos[n]; for (uint32_t y = 0; y < Y; y++) { const double e = (*alpha)[t][y] * (*beta)[t][y] * unorm[t]; ugrd[y] += e; uhes[y] += e * (1.0 - e); } const uint32_t y = seq->pos[t].lbl; ugrd[y] -= 1.0; } } if ((mdl->kind[o] & 2) == 0) return; // for bigrams features for (uint32_t n = 0; n < actcnt; n++) { const uint32_t t = actpos[n]; if (t == 0) continue; for (uint32_t yp = 0, d = 0; yp < Y; yp++) { for (uint32_t y = 0; y < Y; y++, d++) { double e = (*alpha)[t - 1][yp] * (*beta)[t][y] * (*psi)[t][yp][y] * bnorm[t]; bgrd[d] += e; bhes[d] += e * (1.0 - e); } } const uint32_t yp = seq->pos[t - 1].lbl; const uint32_t y = seq->pos[t ].lbl; bgrd[yp * Y + y] -= 1.0; } } /* bct_spgradhes: * Update the gradient and hessian for <blk> on sequence <seq>. This one is * very similar than the trn_spupgrad function but does the computation only * at active pos and approximate also the hessian. */ static void bcd_spgradhes(mdl_t *mdl, bcd_t *bcd, const seq_t *seq, uint64_t o) { const grd_st_t *grd_st = bcd->grd_st; const uint32_t Y = mdl->nlbl; const uint32_t T = seq->len; const double (*psiuni)[T][Y] = (void *)grd_st->psiuni; const double *psival = grd_st->psi; const uint32_t *psiyp = grd_st->psiyp; const uint32_t (*psiidx)[T][Y] = (void *)grd_st->psiidx; const uint32_t *psioff = grd_st->psioff; const double (*alpha)[T][Y] = (void *)grd_st->alpha; const double (*beta )[T][Y] = (void *)grd_st->beta; const double *unorm = grd_st->unorm; const double *bnorm = grd_st->bnorm; const uint32_t *actpos = bcd->actpos; const uint32_t actcnt = bcd->actcnt; double *ugrd = bcd->ugrd; double *uhes = bcd->uhes; double *bgrd = bcd->bgrd; double *bhes = bcd->bhes; // Update the gradient and the hessian but here we sum only on the // positions where the block is active for unigrams features if (mdl->kind[o] & 1) { for (uint32_t n = 0; n < actcnt; n++) { const uint32_t t = actpos[n]; for (uint32_t y = 0; y < Y; y++) { const double e = (*alpha)[t][y] * (*beta)[t][y] * unorm[t]; ugrd[y] += e; uhes[y] += e * (1.0 - e); } const uint32_t y = seq->pos[t].lbl; ugrd[y] -= 1.0; } } if ((mdl->kind[o] & 2) == 0) return; // for bigrams features for (uint32_t n = 0; n < actcnt; n++) { const uint32_t t = actpos[n]; if (t == 0) continue; // We build the expectation matrix double e[Y][Y]; for (uint32_t yp = 0; yp < Y; yp++) for (uint32_t y = 0; y < Y; y++) e[yp][y] = (*alpha)[t - 1][yp] * (*beta)[t][y] * (*psiuni)[t][y] * bnorm[t]; const uint32_t off = psioff[t]; for (uint32_t n = 0, y = 0; n < (*psiidx)[t][Y - 1]; ) { while (n >= (*psiidx)[t][y]) y++; while (n < (*psiidx)[t][y]) { const uint32_t yp = psiyp [off + n]; const double v = psival[off + n]; e[yp][y] += e[yp][y] * v; n++; } } // And use it for (uint32_t yp = 0, d = 0; yp < Y; yp++) { for (uint32_t y = 0; y < Y; y++, d++) { bgrd[d] += e[yp][y]; bhes[d] += e[yp][y] * (1.0 - e[yp][y]); } } const uint32_t yp = seq->pos[t - 1].lbl; const uint32_t y = seq->pos[t ].lbl; bgrd[yp * Y + y] -= 1.0; } } /* bct_update: * Update the model with the computed gradient and hessian. */ static void bcd_update(mdl_t *mdl, bcd_t *bcd, uint64_t o) { const double rho1 = mdl->opt->rho1; const double rho2 = mdl->opt->rho2; const double kappa = mdl->opt->bcd.kappa; const uint32_t Y = mdl->nlbl; const double *ugrd = bcd->ugrd; const double *bgrd = bcd->bgrd; double *uhes = bcd->uhes; double *bhes = bcd->bhes; if (mdl->kind[o] & 1) { // Adjust the hessian double a = 1.0; for (uint32_t y = 0; y < Y; y++) a = max(a, fabs(ugrd[y] / uhes[y])); xvm_scale(uhes, uhes, a * kappa, Y); // Update the model double *w = mdl->theta + mdl->uoff[o]; for (uint32_t y = 0; y < Y; y++) { double z = uhes[y] * w[y] - ugrd[y]; double d = uhes[y] + rho2; w[y] = bcd_soft(z, rho1) / d; } } if (mdl->kind[o] & 2) { // Adjust the hessian double a = 1.0; for (uint32_t i = 0; i < Y * Y; i++) a = max(a, fabs(bgrd[i] / bhes[i])); xvm_scale(bhes, bhes, a * kappa, Y * Y); // Update the model double *bw = mdl->theta + mdl->boff[o]; for (uint32_t i = 0; i < Y * Y; i++) { double z = bhes[i] * bw[i] - bgrd[i]; double d = bhes[i] + rho2; bw[i] = bcd_soft(z, rho1) / d; } } } /* trn_bcd * Train the model using the blockwise coordinates descend method. */ void trn_bcd(mdl_t *mdl) { const uint32_t Y = mdl->nlbl; const uint64_t O = mdl->nobs; const uint32_t S = mdl->train->nseq; const uint32_t T = mdl->train->mlen; const uint32_t K = mdl->opt->maxiter; // Build the index: // Count active sequences per blocks info(" - Build the index\n"); info(" 1/2 -- scan the sequences\n"); uint64_t tot = 0; uint32_t cnt[O], lcl[O]; for (uint64_t o = 0; o < O; o++) cnt[o] = 0, lcl[o] = (uint32_t)-1; for (uint32_t s = 0; s < S; s++) { // List actives blocks const seq_t *seq = mdl->train->seq[s]; for (uint32_t t = 0; t < seq->len; t++) { for (uint32_t b = 0; b < seq->pos[t].ucnt; b++) lcl[seq->pos[t].uobs[b]] = s; for (uint32_t b = 0; b < seq->pos[t].bcnt; b++) lcl[seq->pos[t].bobs[b]] = s; } // Updates blocks count for (uint64_t o = 0; o < O; o++) cnt[o] += (lcl[o] == s); } for (uint64_t o = 0; o < O; o++) tot += cnt[o]; // Allocate memory uint32_t *idx_cnt = xmalloc(sizeof(uint32_t ) * O); uint32_t **idx_lst = xmalloc(sizeof(uint32_t *) * O); for (uint64_t o = 0; o < O; o++) { idx_cnt[o] = cnt[o]; idx_lst[o] = xmalloc(sizeof(uint32_t) * cnt[o]); } // Populate the index info(" 2/2 -- Populate the index\n"); for (uint64_t o = 0; o < O; o++) cnt[o] = 0, lcl[o] = (uint32_t)-1; for (uint32_t s = 0; s < S; s++) { // List actives blocks const seq_t *seq = mdl->train->seq[s]; for (uint32_t t = 0; t < seq->len; t++) { for (uint32_t b = 0; b < seq->pos[t].ucnt; b++) lcl[seq->pos[t].uobs[b]] = s; for (uint32_t b = 0; b < seq->pos[t].bcnt; b++) lcl[seq->pos[t].bobs[b]] = s; } // Build index for (uint64_t o = 0; o < O; o++) if (lcl[o] == s) idx_lst[o][cnt[o]++] = s; } info(" Done\n"); // Allocate the specific trainer of BCD bcd_t *bcd = xmalloc(sizeof(bcd_t)); bcd->ugrd = xvm_new(Y); bcd->uhes = xvm_new(Y); bcd->bgrd = xvm_new(Y * Y); bcd->bhes = xvm_new(Y * Y); bcd->actpos = xmalloc(sizeof(int) * T); bcd->grd_st = grd_stnew(mdl, NULL); // And train the model for (uint32_t i = 1; i <= K; i++) { for (uint64_t o = 0; o < O; o++) { // Clear the gradient and the hessian for (uint32_t y = 0, d = 0; y < Y; y++) { bcd->ugrd[y] = 0.0; bcd->uhes[y] = 0.0; for (uint32_t yp = 0; yp < Y; yp++, d++) { bcd->bgrd[d] = 0.0; bcd->bhes[d] = 0.0; } } // Process active sequences for (uint32_t s = 0; s < idx_cnt[o]; s++) { const uint32_t id = idx_lst[o][s]; const seq_t *seq = mdl->train->seq[id]; bcd_actpos(mdl, bcd, seq, o); grd_stcheck(bcd->grd_st, seq->len); if (mdl->opt->sparse) { grd_spdopsi(bcd->grd_st, seq); grd_spfwdbwd(bcd->grd_st, seq); bcd_spgradhes(mdl, bcd, seq, o); } else { grd_fldopsi(bcd->grd_st, seq); grd_flfwdbwd(bcd->grd_st, seq); bcd_flgradhes(mdl, bcd, seq, o); } } // And update the model bcd_update(mdl, bcd, o); } if (!uit_progress(mdl, i, -1.0)) break; } // Cleanup memory grd_stfree(bcd->grd_st); xvm_free(bcd->ugrd); xvm_free(bcd->uhes); xvm_free(bcd->bgrd); xvm_free(bcd->bhes); free(bcd->actpos); free(bcd); for (uint64_t o = 0; o < O; o++) free(idx_lst[o]); free(idx_lst); free(idx_cnt); }
716
./wapiti/src/thread.c
/* * Wapiti - A linear-chain CRF tool * * Copyright (c) 2009-2013 CNRS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdint.h> #include "model.h" #include "tools.h" #include "thread.h" #include "wapiti.h" /****************************************************************************** * Multi-threading code * * This module handle the thread managment code using POSIX pthreads, on * non-POSIX systems you will have to rewrite this using your systems threads. * all code who depend on threads is located here so this process must not be * too difficult. * If you don't want to use multithreading on non-POSIX system, just enable * the definition of MTH_ANSI in wapiti.h. This will disable multithreading. * * The jobs system is a simple scheduling system, you have to provide the * number of jobs to be done and the size of each batch, a call to getjob will * return the index of the first available and the size of the batch, and mark * these jobs as done. This is usefull if your jobs are numbered but you can't * do a trivial split as each of them may require different amount of time to * be completed like gradient computation which depend on the length of the * sequences. * If you provide a count of 0, the job system is disabled. ******************************************************************************/ #ifdef MTH_ANSI struct job_s { uint32_t size; }; bool mth_getjob(job_t *job, uint32_t *cnt, uint32_t *pos) { if (job->size == 0) return false; *cnt = job->size; *pos = 0; job->size = 0; return true; } void mth_spawn(func_t *f, uint32_t W, void *ud[W], uint32_t size, uint32_t batch) { unused(batch); if (size == 0) { f(NULL, 0, 1, ud[0]); } else { job_t job = {size}; f(&job, 0, 1, ud[0]); } } #else #include <pthread.h> struct job_s { uint32_t size; uint32_t send; uint32_t batch; pthread_mutex_t lock; }; typedef struct mth_s mth_t; struct mth_s { job_t *job; uint32_t id; uint32_t cnt; func_t *f; void *ud; }; /* mth_getjob: * Get a new bunch of sequence to process. This function will return a new * batch of sequence to process starting at position <pos> and with size * <cnt> and return true. If no more batch are available, return false. * This function use a lock to ensure thread safety as it will be called by * the multiple workers threads. */ bool mth_getjob(job_t *job, uint32_t *cnt, uint32_t *pos) { if (job == NULL) return false; if (job->send == job->size) return false; pthread_mutex_lock(&job->lock); *cnt = min(job->batch, job->size - job->send); *pos = job->send; job->send += *cnt; pthread_mutex_unlock(&job->lock); return true; } static void *mth_stub(void *ud) { mth_t *mth = (mth_t *)ud; mth->f(mth->job, mth->id, mth->cnt, mth->ud); return NULL; } /* mth_spawn: * This function spawn W threads for calling the 'f' function. The function * will get a unique identifier between 0 and W-1 and a user data from the * 'ud' array. */ void mth_spawn(func_t *f, uint32_t W, void *ud[W], uint32_t size, uint32_t batch) { // First prepare the jobs scheduler job_t job, *pjob = NULL; if (size != 0) { pjob = &job; job.size = size; job.send = 0; job.batch = batch; if (pthread_mutex_init(&job.lock, NULL) != 0) fatal("failed to create mutex"); } // We handle differently the case where user requested a single thread // for efficiency. if (W == 1) { f(&job, 0, 1, ud[0]); return; } // We prepare the parameters structures that will be send to the threads // with informations for calling the user function. mth_t p[W]; for (uint32_t w = 0; w < W; w++) { p[w].job = pjob; p[w].id = w; p[w].cnt = W; p[w].f = f; p[w].ud = ud[w]; } // We are now ready to spawn the threads and wait for them to finish // their jobs. So we just create all the thread and try to join them // waiting for there return. pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_t th[W]; for (uint32_t w = 0; w < W; w++) if (pthread_create(&th[w], &attr, &mth_stub, &p[w]) != 0) fatal("failed to create thread"); for (uint32_t w = 0; w < W; w++) if (pthread_join(th[w], NULL) != 0) fatal("failed to join thread"); pthread_attr_destroy(&attr); } #endif
717
./cc65/samples/mandelbrot.c
/***************************************************************************** * mandelbrot sample program for cc65. * * * * (w)2002 by groepaz/hitmen, TGI support by Stefan Haubenthal * *****************************************************************************/ #include <stdlib.h> #include <time.h> #include <conio.h> #include <tgi.h> /* Graphics definitions */ #define SCREEN_X (tgi_getxres()) #define SCREEN_Y (tgi_getyres()) #define MAXCOL (tgi_getcolorcount()) #define maxiterations 32 #define fpshift (10) #define tofp(_x) ((_x)<<fpshift) #define fromfp(_x) ((_x)>>fpshift) #define fpabs(_x) (abs(_x)) #define mulfp(_a,_b) ((((signed long)_a)*(_b))>>fpshift) #define divfp(_a,_b) ((((signed long)_a)<<fpshift)/(_b)) /* Workaround missing clock stuff */ #ifdef __APPLE2__ # define clock() 0 # define CLK_TCK 1 #endif /* Use dynamically loaded driver by default */ #ifndef DYN_DRV # define DYN_DRV 1 #endif /* Use static local variables for speed */ #pragma static-locals (1); void mandelbrot (signed short x1, signed short y1, signed short x2, signed short y2) { register unsigned char count; register signed short r, r1, i; register signed short xs, ys, xx, yy; register signed short x, y; /* calc stepwidth */ xs = ((x2 - x1) / (SCREEN_X)); ys = ((y2 - y1) / (SCREEN_Y)); yy = y1; for (y = 0; y < (SCREEN_Y); y++) { yy += ys; xx = x1; for (x = 0; x < (SCREEN_X); x++) { xx += xs; /* do iterations */ r = 0; i = 0; for (count = 0; (count < maxiterations) && (fpabs (r) < tofp (2)) && (fpabs (i) < tofp (2)); ++count) { r1 = (mulfp (r, r) - mulfp (i, i)) + xx; /* i = (mulfp(mulfp(r,i),tofp(2)))+yy; */ i = (((signed long) r * i) >> (fpshift - 1)) + yy; r = r1; } if (count == maxiterations) { tgi_setcolor (0); } else { if (MAXCOL == 2) tgi_setcolor (1); else tgi_setcolor (count % MAXCOL); } /* set pixel */ tgi_setpixel (x, y); } } } int main (void) { clock_t t; unsigned long sec; unsigned sec10; unsigned char err; clrscr (); #if DYN_DRV /* Load the graphics driver */ cprintf ("initializing... mompls\r\n"); tgi_load_driver (tgi_stddrv); #else /* Install the graphics driver */ tgi_install (tgi_static_stddrv); #endif err = tgi_geterror (); if (err != TGI_ERR_OK) { cprintf ("Error #%d initializing graphics.\r\n%s\r\n", err, tgi_geterrormsg (err)); exit (EXIT_FAILURE); }; cprintf ("ok.\n\r"); /* Initialize graphics */ tgi_init (); tgi_clear (); t = clock (); /* calc mandelbrot set */ mandelbrot (tofp (-2), tofp (-2), tofp (2), tofp (2)); t = clock () - t; /* Fetch the character from the keyboard buffer and discard it */ (void) cgetc (); /* shut down gfx mode and return to textmode */ tgi_done (); /* Calculate stats */ sec = (t * 10) / CLK_TCK; sec10 = sec % 10; sec /= 10; /* Output stats */ cprintf ("time : %lu.%us\n\r", sec, sec10); /* Wait for a key, then end */ cputs ("Press any key when done...\n\r"); (void) cgetc (); /* Done */ return EXIT_SUCCESS; }
718
./cc65/samples/mousedemo.c
/* * Demo program for mouse usage. Will work for the C64/C128/CBM510/Atari/Apple2 * * Ullrich von Bassewitz, 13.09.2001 * */ #include <stdlib.h> #include <string.h> #include <mouse.h> #include <conio.h> #include <ctype.h> #include <dbg.h> #if defined(__C64__) || defined(__C128__) /* Address of data for sprite 0 */ #if defined(__C64__) # define SPRITE0_DATA 0x0340 # define SPRITE0_PTR 0x07F8 #elif defined(__C128__) # define SPRITE0_DATA 0x0E00 # define SPRITE0_PTR 0x07F8 #endif /* The mouse sprite (an arrow) */ static const unsigned char MouseSprite[64] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xE0, 0x00, 0x0F, 0xC0, 0x00, 0x0F, 0x80, 0x00, 0x0F, 0xC0, 0x00, 0x0D, 0xE0, 0x00, 0x08, 0xF0, 0x00, 0x00, 0x78, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x07, 0x80, 0x00, 0x03, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; #endif /* __C64__ or __C128__ */ /* Dynamically loaded driver by default */ #ifndef DYN_DRV # define DYN_DRV 1 #endif #define max(a,b) (((a) > (b)) ? (a) : (b)) #define min(a,b) (((a) < (b)) ? (a) : (b)) static void CheckError (const char* S, unsigned char Error) { if (Error != MOUSE_ERR_OK) { cprintf ("%s: %s(%d)\r\n", S, mouse_geterrormsg (Error), Error); exit (EXIT_FAILURE); } } static void DoWarning (void) /* Warn the user that a mouse driver is needed for this program */ { cprintf ("Warning: This program needs the mouse\r\n" "driver with the name\r\n" " %s\r\n" "on disk! Press 'y' if you have it or\r\n" "any other key to exit.\r\n", mouse_stddrv); if (tolower (cgetc ()) != 'y') { exit (EXIT_SUCCESS); } cprintf ("Ok. Please wait patiently...\r\n"); } static void ShowState (unsigned char Jailed, unsigned char Invisible) /* Display jail and cursor state */ { gotoxy (0, 6); cclear (40); gotoxy (0, 6); cprintf ("Mouse cursor %svisible%s", Invisible? "in" : "", Jailed? ", jailed" : ""); } int main (void) { struct mouse_info info; struct mouse_box full_box; struct mouse_box small_box; unsigned char Invisible; unsigned char Done; unsigned char Jailed; /* Initialize the debugger */ DbgInit (0); /* Clear the screen, set white on black */ (void) bordercolor (COLOR_BLACK); (void) bgcolor (COLOR_BLACK); (void) textcolor (COLOR_GRAY3); cursor (0); clrscr (); #if defined(__C64__) || defined(__C128__) || defined(__CBM510__) /* Copy the sprite data */ memcpy ((void*) SPRITE0_DATA, MouseSprite, sizeof (MouseSprite)); /* Set the VIC sprite pointer */ *(unsigned char*)SPRITE0_PTR = SPRITE0_DATA / 64; /* Set the color of sprite 0 */ #ifdef __CBM510__ pokebsys ((unsigned) &VIC.spr0_color, COLOR_WHITE); #else VIC.spr0_color = COLOR_WHITE; #endif #endif #if DYN_DRV /* Output a warning about the driver that is needed */ DoWarning (); /* Load and install the mouse driver */ CheckError ("mouse_load_driver", mouse_load_driver (&mouse_def_callbacks, mouse_stddrv)); #else /* Install the mouse driver */ CheckError ("mouse_install", mouse_install (&mouse_def_callbacks, mouse_static_stddrv)); #endif /* Get the initial mouse bounding box */ mouse_getbox (&full_box); /* Print a help line */ clrscr (); revers (1); cputsxy (0, 0, "d)ebug h)ide q)uit s)how j)ail "); revers (0); /* Test loop */ Done = 0; Jailed = 0; Invisible = 1; ShowState (Jailed, Invisible); while (!Done) { /* Get the current mouse coordinates and button states and print them */ mouse_info (&info); gotoxy (0, 2); cprintf ("X = %3d", info.pos.x); gotoxy (0, 3); cprintf ("Y = %3d", info.pos.y); gotoxy (0, 4); cprintf ("LB = %c", (info.buttons & MOUSE_BTN_LEFT)? '1' : '0'); gotoxy (0, 5); cprintf ("RB = %c", (info.buttons & MOUSE_BTN_RIGHT)? '1' : '0'); /* Handle user input */ if (kbhit ()) { switch (tolower (cgetc ())) { case 'd': BREAK(); break; case 'h': ShowState (Jailed, ++Invisible); mouse_hide (); break; case 'j': if (Jailed) { Jailed = 0; mouse_setbox (&full_box); } else { Jailed = 1; small_box.minx = max (info.pos.x - 10, full_box.minx); small_box.miny = max (info.pos.y - 10, full_box.miny); small_box.maxx = min (info.pos.x + 10, full_box.maxx); small_box.maxy = min (info.pos.y + 10, full_box.maxy); mouse_setbox (&small_box); } ShowState (Jailed, Invisible); break; case 's': if (Invisible) { ShowState (Jailed, --Invisible); mouse_show (); } break; case 'q': Done = 1; break; } } } #if DYN_DRV /* Uninstall and unload the mouse driver */ CheckError ("mouse_unload", mouse_unload ()); #else /* Uninstall the mouse driver */ CheckError ("mouse_uninstall", mouse_uninstall ()); #endif /* Say goodbye */ clrscr (); cputs ("Goodbye!\r\n"); return EXIT_SUCCESS; }
719
./cc65/samples/tgidemo.c
#include <stdio.h> #include <stdlib.h> #include <cc65.h> #include <conio.h> #include <ctype.h> #include <modload.h> #include <tgi.h> #include <tgi/tgi-kernel.h> #ifndef DYN_DRV # define DYN_DRV 1 #endif #define COLOR_BACK TGI_COLOR_BLACK #define COLOR_FORE TGI_COLOR_WHITE /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Driver stuff */ static unsigned MaxX; static unsigned MaxY; static unsigned AspectRatio; /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void CheckError (const char* S) { unsigned char Error = tgi_geterror (); if (Error != TGI_ERR_OK) { printf ("%s: %d\n", S, Error); exit (EXIT_FAILURE); } } static void DoWarning (void) /* Warn the user that the TGI driver is needed for this program */ { printf ("Warning: This program needs the TGI\n" "driver on disk! Press 'y' if you have\n" "it - any other key exits.\n"); if (tolower (cgetc ()) != 'y') { exit (EXIT_SUCCESS); } printf ("Ok. Please wait patiently...\n"); } static void DoCircles (void) { static const unsigned char Palette[2] = { TGI_COLOR_WHITE, TGI_COLOR_ORANGE }; unsigned char I; unsigned char Color = COLOR_FORE; unsigned X = MaxX / 2; unsigned Y = MaxY / 2; tgi_setpalette (Palette); while (!kbhit ()) { tgi_setcolor (COLOR_FORE); tgi_line (0, 0, MaxX, MaxY); tgi_line (0, MaxY, MaxX, 0); tgi_setcolor (Color); for (I = 10; I < 240; I += 10) { tgi_ellipse (X, Y, I, tgi_imulround (I, AspectRatio)); } Color = Color == COLOR_FORE ? COLOR_BACK : COLOR_FORE; } cgetc (); tgi_clear (); } static void DoCheckerboard (void) { static const unsigned char Palette[2] = { TGI_COLOR_WHITE, TGI_COLOR_BLACK }; unsigned X, Y; unsigned char Color; tgi_setpalette (Palette); Color = COLOR_BACK; while (1) { for (Y = 0; Y <= MaxY; Y += 10) { for (X = 0; X <= MaxX; X += 10) { tgi_setcolor (Color); tgi_bar (X, Y, X+9, Y+9); Color = Color == COLOR_FORE ? COLOR_BACK : COLOR_FORE; if (kbhit ()) { cgetc (); tgi_clear (); return; } } Color = Color == COLOR_FORE ? COLOR_BACK : COLOR_FORE; } Color = Color == COLOR_FORE ? COLOR_BACK : COLOR_FORE; } } static void DoDiagram (void) { static const unsigned char Palette[2] = { TGI_COLOR_WHITE, TGI_COLOR_BLACK }; int XOrigin, YOrigin; int Amp; int X, Y; unsigned I; tgi_setpalette (Palette); tgi_setcolor (COLOR_FORE); /* Determine zero and aplitude */ YOrigin = MaxY / 2; XOrigin = 10; Amp = (MaxY - 19) / 2; /* Y axis */ tgi_line (XOrigin, 10, XOrigin, MaxY-10); tgi_line (XOrigin-2, 12, XOrigin, 10); tgi_lineto (XOrigin+2, 12); /* X axis */ tgi_line (XOrigin, YOrigin, MaxX-10, YOrigin); tgi_line (MaxX-12, YOrigin-2, MaxX-10, YOrigin); tgi_lineto (MaxX-12, YOrigin+2); /* Sine */ tgi_gotoxy (XOrigin, YOrigin); for (I = 0; I <= 360; I += 5) { /* Calculate the next points */ X = (int) (((long) (MaxX - 19) * I) / 360); Y = (int) (((long) Amp * -cc65_sin (I)) / 256); /* Draw the line */ tgi_lineto (XOrigin + X, YOrigin + Y); } cgetc (); tgi_clear (); } static void DoLines (void) { static const unsigned char Palette[2] = { TGI_COLOR_WHITE, TGI_COLOR_BLACK }; unsigned X; tgi_setpalette (Palette); tgi_setcolor (COLOR_FORE); for (X = 0; X <= MaxY; X += 10) { tgi_line (0, 0, MaxY, X); tgi_line (0, 0, X, MaxY); tgi_line (MaxY, MaxY, 0, MaxY-X); tgi_line (MaxY, MaxY, MaxY-X, 0); } cgetc (); tgi_clear (); } int main (void) { unsigned char Border; #if DYN_DRV /* Warn the user that the tgi driver is needed */ DoWarning (); /* Load and initialize the driver */ tgi_load_driver (tgi_stddrv); CheckError ("tgi_load_driver"); #else /* Install the driver */ tgi_install (tgi_static_stddrv); CheckError ("tgi_install"); #endif tgi_init (); CheckError ("tgi_init"); tgi_clear (); /* Get stuff from the driver */ MaxX = tgi_getmaxx (); MaxY = tgi_getmaxy (); AspectRatio = tgi_getaspectratio (); /* Set the palette, set the border color */ Border = bordercolor (COLOR_BLACK); /* Do graphics stuff */ DoCircles (); DoCheckerboard (); DoDiagram (); DoLines (); #if DYN_DRV /* Unload the driver */ tgi_unload (); #else /* Uninstall the driver */ tgi_uninstall (); #endif /* Reset the border */ (void) bordercolor (Border); /* Done */ printf ("Done\n"); return EXIT_SUCCESS; }
720
./cc65/samples/multidemo.c
/* * Extended memory overlay demo program. * * 2012-17-07, Oliver Schmidt (ol.sc@web.de) * */ #include <string.h> #include <conio.h> #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <em.h> #ifndef __CBM__ #include <fcntl.h> #include <unistd.h> #else #include <device.h> #endif /* The symbols _OVERLAY?_LOAD__ and _OVERLAY?_SIZE__ were generated by the * linker. They contain the overlay area address and size specific to a * certain program. */ extern void _OVERLAY1_LOAD__[], _OVERLAY1_SIZE__[]; extern void _OVERLAY2_LOAD__[], _OVERLAY2_SIZE__[]; extern void _OVERLAY3_LOAD__[], _OVERLAY3_SIZE__[]; struct { char *name; int page; void *addr; unsigned size; } overlay[] = {{"multdemo.1", -1, _OVERLAY1_LOAD__, (unsigned)_OVERLAY1_SIZE__}, {"multdemo.2", -1, _OVERLAY2_LOAD__, (unsigned)_OVERLAY2_SIZE__}, {"multdemo.3", -1, _OVERLAY3_LOAD__, (unsigned)_OVERLAY3_SIZE__}}; /* Functions resident in an overlay can call back functions resident in the * main program at any time without any precautions. The function log() is * an example for such a function resident in the main program. */ void log (char *msg) { /* Functions resident in an overlay can access all program variables and * constants at any time without any precautions because those are never * placed in overlays. The string constant below is an example for such * a constant resident in the main program. */ printf ("Log: %s\n", msg); } /* In a real-world overlay program one would probably not use a #pragma but * rather place all the code of certain source files into the overlay by * compiling them with --code-name OVERLAY1. */ #pragma code-name (push, "OVERLAY1"); void foo (void) { log ("Calling main from overlay 1"); } #pragma code-name (pop); #pragma code-name (push, "OVERLAY2"); void bar (void) { log ("Calling main from overlay 2"); } #pragma code-name (pop); #pragma code-name (push, "OVERLAY3"); void foobar (void) { log ("Calling main from overlay 3"); } #pragma code-name(pop); unsigned char loademdriver (void) { DIR *dir; struct dirent *ent; char *emd = NULL; unsigned char max = 0; unsigned char num; printf ("Dbg: Searching for emdrivers\n"); dir = opendir ("."); if (!dir) { log ("Opening directory failed"); return 0; } while (ent = readdir (dir)) { char *ext; if (!_DE_ISREG (ent->d_type)) { continue; } ext = strrchr (ent->d_name, '.'); if (!ext || strcasecmp (ext, ".emd")) { printf ("Dbg: Skipping file %s\n", ent->d_name); continue; } printf ("Dbg: Memorizing file %s\n", ent->d_name); emd = realloc (emd, FILENAME_MAX * (max + 1)); strcpy (emd + FILENAME_MAX * max++, ent->d_name); } closedir (dir); for (num = 0; num < max; ++num) { char *drv; drv = emd + FILENAME_MAX * num; printf ("Dbg: Trying emdriver %s\n", drv); if (em_load_driver (drv) == EM_ERR_OK) { printf ("Dbg: Loaded emdriver %s\n", drv); free (emd); return 1; } printf ("Dbg: Emdriver %s failed\n", drv); } free (emd); return 0; } unsigned char loadoverlay (unsigned char num) { if (overlay[num - 1].page < 0) { #ifndef __CBM__ int file; printf ("Dbg: Loading overlay %u from file\n", num); file = open (overlay[num - 1].name, O_RDONLY); if (file == -1) { log ("Opening overlay file failed"); return 0; } read (file, overlay[num - 1].addr, overlay[num - 1].size); close (file); #else if (cbm_load (overlay[num - 1].name, getcurrentdevice (), NULL) == 0) { log ("Loading overlay file failed"); return 0; } #endif return 1; } else { struct em_copy copyinfo; printf ("Dbg: Loading overlay %u from memory\n", num); copyinfo.offs = 0; copyinfo.page = overlay[num - 1].page; copyinfo.buf = overlay[num - 1].addr; copyinfo.count = overlay[num - 1].size; em_copyfrom (&copyinfo); return 1; } } void copyoverlays (void) { unsigned page = 0; unsigned char num; for (num = 0; num < sizeof (overlay) / sizeof (overlay[0]); ++num) { struct em_copy copyinfo; unsigned size = (overlay[num].size + EM_PAGE_SIZE - 1) / EM_PAGE_SIZE; if (size > em_pagecount () - page) { printf ("Dbg: Not enough memory for overlay %u\n", num + 1); continue; } if (loadoverlay (num + 1) == 0) continue; copyinfo.offs = 0; copyinfo.page = page; copyinfo.buf = overlay[num].addr; copyinfo.count = overlay[num].size; em_copyto (&copyinfo); overlay[num].page = page; page += size; printf ("Dbg: Stored overlay %u in pages %u-%u\n", num + 1, overlay[num].page, page - 1); } } void main (void) { log ("Loading extended memory driver"); if (loademdriver ()) { log ("Copying overlays into ext. memory"); copyoverlays (); } else { log ("No extended memory driver found"); } log ("Press any key..."); cgetc (); if (loadoverlay (1)) { log ("Calling overlay 1 from main"); /* The linker makes sure that the call to foo() ends up at the right mem * addr. However it's up to user to make sure that the - right - overlay * is actually loaded before making the the call. */ foo (); } /* Replacing one overlay with another one can only happen from the main * program. This implies that an overlay can never load another overlay. */ if (loadoverlay (2)) { log ("Calling overlay 2 from main"); bar (); } if (loadoverlay (3)) { log ("Calling overlay 3 from main"); foobar (); } log ("Press any key..."); cgetc (); }
721
./cc65/samples/hello.c
/* * Fancy hello world program using cc65. * * Ullrich von Bassewitz (ullrich@von-bassewitz.de) * */ #include <stdlib.h> #include <string.h> #include <conio.h> #include <dbg.h> /*****************************************************************************/ /* Data */ /*****************************************************************************/ static const char Text [] = "Hello world!"; /*****************************************************************************/ /* Code */ /*****************************************************************************/ int main (void) { unsigned char XSize, YSize; /* Set screen colors, hide the cursor */ textcolor (COLOR_WHITE); bordercolor (COLOR_BLACK); bgcolor (COLOR_BLACK); cursor (0); /* Clear the screen, put cursor in upper left corner */ clrscr (); /* Ask for the screen size */ screensize (&XSize, &YSize); /* Draw a border around the screen */ /* Top line */ cputc (CH_ULCORNER); chline (XSize - 2); cputc (CH_URCORNER); /* Vertical line, left side */ cvlinexy (0, 1, YSize - 2); /* Bottom line */ cputc (CH_LLCORNER); chline (XSize - 2); cputc (CH_LRCORNER); /* Vertical line, right side */ cvlinexy (XSize - 1, 1, YSize - 2); /* Write the greeting in the mid of the screen */ gotoxy ((XSize - strlen (Text)) / 2, YSize / 2); cprintf ("%s", Text); /* Wait for the user to press a key */ (void) cgetc (); /* Clear the screen again */ clrscr (); /* Done */ return EXIT_SUCCESS; }
722
./cc65/samples/nachtm.c
/* * "Eine kleine Nachtmusik" by Wolfgang Amadeus Mozart, KV 525 * * First version in 1987 by * Joachim von Bassewitz (joachim@von-bassewitz.de) and * Ullrich von Bassewitz (ullrich@von-bassewitz.de). * * C conversion in 1998 by * Ullrich von Bassewitz (ullrich@von-bassewitz.de) * */ #include <stdio.h> #include <string.h> #include <time.h> #include <conio.h> #include <cbm.h> #include <dbg.h> /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Tables with voice data. * * Bit Description * ------------------------------------------- * 15 Pause bit. * 12-14 Octave * 8-11 Tone (index into frequency table) * 7 Unused. Was thought as a control bit in the original version to * change SID parameters, but this was never implemented. * 0-6 Length of the tone in ticks. * */ static unsigned Voice1 [] = { 0x5708,0x8004,0x5204,0x5708,0x8004,0x5204,0x5704,0x5204,0x5704,0x5B04, 0x6208,0x8008,0x6008,0x8004,0x5904,0x6008,0x8004,0x5904,0x6004,0x5904, 0x5604,0x5904,0x5208,0x8008,0x5704,0x8004,0x570C,0x5B01,0x5B01,0x5B01, 0x5B01,0x5904,0x5704,0x5704,0x5604,0x560C,0x5901,0x5901,0x5901,0x5901, 0x6004,0x5604,0x5901,0x5901,0x5901,0x5901,0x5704,0x570C,0x5B01,0x5B01, 0x5B01,0x5B01,0x5904,0x5704,0x5701,0x5701,0x5701,0x5701,0x5604,0x560C, 0x5901,0x5901,0x5901,0x5901,0x6004,0x5604,0x5704,0x5704,0x5601,0x5601, 0x5601,0x5601,0x5401,0x5401,0x5602,0x5704,0x5704,0x5901,0x5901,0x5901, 0x5901,0x5701,0x5701,0x5902,0x5B04,0x5B04,0x6001,0x6001,0x6001,0x6001, 0x5B01,0x5B01,0x6001,0x6001,0x6208,0x8008,0x5201,0x5201,0x5201,0x5201, 0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201, 0x5201,0x5201,0x5410,0x5008,0x5008,0x4B08,0x4B08,0x4908,0x4908,0x4701, 0x4701,0x4701,0x4701,0x4604,0x4404,0x4604,0x4704,0x8004,0x4904,0x8004, 0x4B04,0x800C,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201, 0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5410,0x5201, 0x5201,0x5201,0x5201,0x5004,0x5004,0x5004,0x5001,0x5001,0x5001,0x5001, 0x4B04,0x4B04,0x4B04,0x4B01,0x4B01,0x4B01,0x4B01,0x4904,0x4904,0x4904, 0x4701,0x4701,0x4701,0x4701,0x4601,0x4601,0x4601,0x4601,0x4401,0x4401, 0x4401,0x4401,0x4604,0x4701,0x4701,0x4701,0x4701,0x4701,0x4701,0x4701, 0x4701,0x4701,0x4701,0x4701,0x4701,0x4701,0x4701,0x4701,0x4701,0x4704, 0x4701,0x4701,0x4601,0x4701,0x4901,0x4901,0x4901,0x4901,0x4604,0x4B01, 0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01, 0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B04,0x4B01,0x4B01,0x4901,0x4B01, 0x5001,0x5001,0x5001,0x5001,0x4904,0x5210,0x5408,0x5608,0x5708,0x5908, 0x5B08,0x6108,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201, 0x6201,0x6201,0x6201,0x6201,0x5904,0x6101,0x6101,0x6101,0x6101,0x6101, 0x6101,0x5902,0x6101,0x6101,0x6101,0x6101,0x6101,0x6101,0x5902,0x6201, 0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201, 0x6201,0x5904,0x6101,0x6101,0x6101,0x6101,0x6101,0x6101,0x5902,0x6101, 0x6101,0x6101,0x6101,0x6101,0x6101,0x5902,0x6204,0x6208,0x6208,0x6208, 0x6201,0x6201,0x6201,0x6201,0x6204,0x6208,0x6208,0x6208,0x6204,0x6104, 0x5904,0x6204,0x5904,0x6004,0x5904,0x6204,0x5904,0x6104,0x4904,0x4904, 0x4904,0x4908,0x8008,0x590A,0x5702,0x5602,0x5402,0x5204,0x8004,0x5B04, 0x8004,0x5704,0x8004,0x5404,0x8004,0x5B04,0x800C,0x5601,0x5601,0x5601, 0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5401,0x5401,0x5201, 0x5201,0x5101,0x5101,0x4B04,0x8004,0x5704,0x8004,0x5601,0x5601,0x5601, 0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601, 0x5601,0x5601,0x5601,0x5408,0x8008,0x5901,0x5901,0x5901,0x5901,0x5901, 0x5901,0x5901,0x5901,0x5901,0x5901,0x5701,0x5701,0x5601,0x5601,0x5401, 0x5401,0x5204,0x8004,0x5B04,0x8004,0x5704,0x8004,0x5404,0x8004,0x5908, 0x8004,0x5704,0x6104,0x6204,0x8004,0x5B04,0x5B01,0x5B01,0x5B01,0x5B01, 0x5904,0x8004,0x5104,0x5208,0x8004,0x5904,0x6201,0x6201,0x6201,0x6201, 0x6101,0x6101,0x6101,0x6101,0x5B01,0x5B01,0x5B01,0x5B01,0x5904,0x5B01, 0x5B01,0x5B01,0x5B01,0x5904,0x8004,0x5904,0x5904,0x5904,0x5904,0x5904, 0x5B01,0x5B01,0x5B01,0x5B01,0x5904,0x8004,0x5904,0x6204,0x6104,0x5B04, 0x5904,0x5B01,0x5B01,0x5B01,0x5B01,0x5904,0x8004,0x5904,0x5904,0x5904, 0x5904,0x5904,0x5B01,0x5B01,0x5B01,0x5B01,0x5904,0x8008,0x5B0A,0x5901, 0x5901,0x5701,0x5701,0x5601,0x5601,0x5708,0x8008,0x590A,0x5701,0x5701, 0x5601,0x5601,0x5401,0x5401,0x5608,0x8008,0x5B01,0x5B01,0x5B01,0x5B01, 0x6101,0x6101,0x6201,0x6201,0x6104,0x5B04,0x5B01,0x5B01,0x5B01,0x5B01, 0x5904,0x5604,0x5904,0x5901,0x5901,0x5901,0x5901,0x5704,0x5604,0x5404, 0x5208,0x8004,0x5904,0x6201,0x6201,0x6201,0x6201,0x6101,0x6101,0x6101, 0x6101,0x5B01,0x5B01,0x5B01,0x5B01,0x5904,0x5B01,0x5B01,0x5B01,0x5B01, 0x5904,0x8004,0x5904,0x5904,0x5904,0x5904,0x5904,0x5B01,0x5B01,0x5B01, 0x5B01,0x5904,0x8004,0x5904,0x6201,0x6201,0x6201,0x6201,0x6101,0x6101, 0x6101,0x6101,0x5B01,0x5B01,0x5B01,0x5B01,0x5904,0x5B01,0x5B01,0x5B01, 0x5B01,0x5904,0x8004,0x5904,0x5904,0x5904,0x5904,0x5904,0x5B01,0x5B01, 0x5B01,0x5B01,0x5904,0x8008,0x5B0A,0x5901,0x5901,0x5701,0x5701,0x5601, 0x5601,0x5708,0x8008,0x590A,0x5701,0x5701,0x5601,0x5601,0x5401,0x5401, 0x5608,0x8008,0x5B01,0x5B01,0x5B01,0x5B01,0x6101,0x6101,0x6201,0x6201, 0x6104,0x5B04,0x5B01,0x5B01,0x5B01,0x5B01,0x5904,0x5604,0x5904,0x5901, 0x5901,0x5901,0x5901,0x5704,0x5604,0x5404,0x5204,0x4904,0x4B04,0x5104, 0x5204,0x5204,0x5401,0x5401,0x5401,0x5401,0x5201,0x5201,0x5401,0x5401, 0x5604,0x5104,0x5204,0x5404,0x5604,0x5604,0x5701,0x5701,0x5701,0x5701, 0x5601,0x5601,0x5701,0x5701,0x5904,0x5904,0x5A04,0x5802,0x5A02,0x5B08, 0x8008,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01, 0x4B01,0x4B01,0x4B01,0x5404,0x5201,0x5201,0x5201,0x5201,0x5101,0x5101, 0x5101,0x5101,0x5B01,0x5B01,0x5B01,0x5B01,0x5901,0x5901,0x5901,0x5901, 0x6204,0x8004,0x6604,0x8004,0x6204,0x800C,0x5708,0x8004,0x5204,0x5708, 0x8004,0x5204,0x5704,0x5204,0x5704,0x5B04,0x6208,0x8008,0x6008,0x8004, 0x5904,0x6008,0x8004,0x5904,0x6004,0x5904,0x5604,0x5904,0x5208,0x8008, 0x5704,0x8004,0x570C,0x5B01,0x5B01,0x5B01,0x5B01,0x5904,0x5704,0x5704, 0x5604,0x560C,0x5901,0x5901,0x5901,0x5901,0x6004,0x5604,0x5901,0x5901, 0x5901,0x5901,0x5704,0x570C,0x5B01,0x5B01,0x5B01,0x5B01,0x5904,0x5704, 0x5701,0x5701,0x5701,0x5701,0x5604,0x560C,0x5901,0x5901,0x5901,0x5901, 0x6004,0x5604,0x5704,0x5704,0x5601,0x5601,0x5601,0x5601,0x5401,0x5401, 0x5602,0x5704,0x5704,0x5901,0x5901,0x5901,0x5901,0x5701,0x5701,0x5902, 0x5B04,0x5B04,0x6001,0x6001,0x6001,0x6001,0x5B01,0x5B01,0x6001,0x6001, 0x6208,0x8008,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201, 0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5410,0x5008, 0x5008,0x4B08,0x4B08,0x4908,0x4908,0x4701,0x4701,0x4701,0x4701,0x4604, 0x4404,0x4604,0x4704,0x8004,0x4904,0x8004,0x4B04,0x800C,0x5201,0x5201, 0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201, 0x5201,0x5201,0x5201,0x5201,0x5410,0x5201,0x5201,0x5201,0x5201,0x5004, 0x5004,0x5004,0x5001,0x5001,0x5001,0x5001,0x4B04,0x4B04,0x4B04,0x4B01, 0x4B01,0x4B01,0x4B01,0x4904,0x4904,0x4904,0x4701,0x4701,0x4701,0x4701, 0x4601,0x4601,0x4601,0x4601,0x4401,0x4401,0x4401,0x4401,0x4604,0x4701, 0x4701,0x4701,0x4701,0x4701,0x4701,0x4701,0x4701,0x4701,0x4701,0x4701, 0x4701,0x4701,0x4701,0x4701,0x4701,0x4704,0x4701,0x4701,0x4601,0x4701, 0x4901,0x4901,0x4901,0x4901,0x4604,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01, 0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01, 0x4B01,0x4B04,0x4B01,0x4B01,0x4901,0x4B01,0x5001,0x5001,0x5001,0x5001, 0x4904,0x5210,0x5408,0x5608,0x5708,0x5908,0x5B08,0x6108,0x6201,0x6201, 0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201, 0x5904,0x6101,0x6101,0x6101,0x6101,0x6101,0x6101,0x5902,0x6101,0x6101, 0x6101,0x6101,0x6101,0x6101,0x5902,0x6201,0x6201,0x6201,0x6201,0x6201, 0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x5904,0x6101,0x6101, 0x6101,0x6101,0x6101,0x6101,0x5902,0x6101,0x6101,0x6101,0x6101,0x6101, 0x6101,0x5902,0x6204,0x6208,0x6208,0x6208,0x6201,0x6201,0x6201,0x6201, 0x6204,0x6208,0x6208,0x6208,0x6204,0x6104,0x5904,0x6204,0x5904,0x6004, 0x5904,0x6204,0x5904,0x6104,0x4904,0x4904,0x4904,0x4908,0x8008,0x590A, 0x5702,0x5602,0x5402,0x5204,0x8004,0x5B04,0x8004,0x5704,0x8004,0x5404, 0x8004,0x5B04,0x800C,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601, 0x5601,0x5601,0x5601,0x5401,0x5401,0x5201,0x5201,0x5101,0x5101,0x4B04, 0x8004,0x5704,0x8004,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601, 0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5408, 0x8008,0x5901,0x5901,0x5901,0x5901,0x5901,0x5901,0x5901,0x5901,0x5901, 0x5901,0x5701,0x5701,0x5601,0x5601,0x5401,0x5401,0x5204,0x8004,0x5B04, 0x8004,0x5704,0x8004,0x5404,0x8004,0x5908,0x8004,0x5704,0x6104,0x6204, 0x8004,0x5B04,0x5B01,0x5B01,0x5B01,0x5B01,0x5904,0x8004,0x5104,0x5208, 0x8004,0x5904,0x6201,0x6201,0x6201,0x6201,0x6101,0x6101,0x6101,0x6101, 0x5B01,0x5B01,0x5B01,0x5B01,0x5904,0x5B01,0x5B01,0x5B01,0x5B01,0x5904, 0x8004,0x5904,0x5904,0x5904,0x5904,0x5904,0x5B01,0x5B01,0x5B01,0x5B01, 0x5904,0x8004,0x5904,0x6204,0x6104,0x5B04,0x5904,0x5B01,0x5B01,0x5B01, 0x5B01,0x5904,0x8004,0x5904,0x5904,0x5904,0x5904,0x5904,0x5B01,0x5B01, 0x5B01,0x5B01,0x5904,0x8008,0x5B0A,0x5901,0x5901,0x5701,0x5701,0x5601, 0x5601,0x5708,0x8008,0x590A,0x5701,0x5701,0x5601,0x5601,0x5401,0x5401, 0x5608,0x8008,0x5B01,0x5B01,0x5B01,0x5B01,0x6101,0x6101,0x6201,0x6201, 0x6104,0x5B04,0x5B01,0x5B01,0x5B01,0x5B01,0x5904,0x5604,0x5904,0x5901, 0x5901,0x5901,0x5901,0x5704,0x5604,0x5404,0x5208,0x8004,0x5904,0x6201, 0x6201,0x6201,0x6201,0x6101,0x6101,0x6101,0x6101,0x5B01,0x5B01,0x5B01, 0x5B01,0x5904,0x5B01,0x5B01,0x5B01,0x5B01,0x5904,0x8004,0x5904,0x5904, 0x5904,0x5904,0x5904,0x5B01,0x5B01,0x5B01,0x5B01,0x5904,0x8004,0x5904, 0x6201,0x6201,0x6201,0x6201,0x6101,0x6101,0x6101,0x6101,0x5B01,0x5B01, 0x5B01,0x5B01,0x5904,0x5B01,0x5B01,0x5B01,0x5B01,0x5904,0x8004,0x5904, 0x5904,0x5904,0x5904,0x5904,0x5B01,0x5B01,0x5B01,0x5B01,0x5904,0x8008, 0x5B0A,0x5901,0x5901,0x5701,0x5701,0x5601,0x5601,0x5708,0x8008,0x590A, 0x5701,0x5701,0x5601,0x5601,0x5401,0x5401,0x5608,0x8008,0x5B01,0x5B01, 0x5B01,0x5B01,0x6101,0x6101,0x6201,0x6201,0x6104,0x5B04,0x5B01,0x5B01, 0x5B01,0x5B01,0x5904,0x5604,0x5904,0x5901,0x5901,0x5901,0x5901,0x5704, 0x5604,0x5404,0x5204,0x4904,0x4B04,0x5104,0x5204,0x5204,0x5401,0x5401, 0x5401,0x5401,0x5201,0x5201,0x5401,0x5401,0x5604,0x5104,0x5204,0x5404, 0x5604,0x5604,0x5701,0x5701,0x5701,0x5701,0x5601,0x5601,0x5701,0x5701, 0x5904,0x5904,0x5A04,0x5802,0x5A02,0x5B08,0x8008,0x4B01,0x4B01,0x4B01, 0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x5404, 0x5201,0x5201,0x5201,0x5201,0x5101,0x5101,0x5101,0x5101,0x5B01,0x5B01, 0x5B01,0x5B01,0x5901,0x5901,0x5901,0x5901,0x6204,0x8004,0x6604,0x8004, 0x6204,0x800C,0x5208,0x8004,0x4904,0x5208,0x8004,0x4904,0x5204,0x4904, 0x5204,0x5604,0x5908,0x8008,0x5908,0x8004,0x5604,0x5908,0x8004,0x5604, 0x5904,0x5604,0x5304,0x5604,0x4B08,0x8014,0x5704,0x6001,0x6001,0x6001, 0x6001,0x5B01,0x5B01,0x5B01,0x5B01,0x5901,0x5901,0x5901,0x5901,0x5704, 0x5901,0x5901,0x5901,0x5901,0x5704,0x8004,0x5704,0x5704,0x5704,0x5704, 0x5704,0x5901,0x5901,0x5901,0x5901,0x5704,0x8004,0x5704,0x6001,0x6001, 0x6001,0x6001,0x5B01,0x5B01,0x5B01,0x5B01,0x5901,0x5901,0x5901,0x5901, 0x5704,0x5901,0x5901,0x5901,0x5901,0x5704,0x8004,0x5704,0x5704,0x5704, 0x5704,0x5704,0x5901,0x5901,0x5901,0x5901,0x5704,0x8004,0x5704,0x6001, 0x6001,0x6001,0x6001,0x5B01,0x5B01,0x5B01,0x5B01,0x5901,0x5901,0x5901, 0x5901,0x5704,0x5901,0x5901,0x5901,0x5901,0x5804,0x8004,0x5804,0x5804, 0x5804,0x5804,0x5804,0x5B01,0x5B01,0x5B01,0x5B01,0x5904,0x8004,0x5904, 0x6001,0x6001,0x6001,0x6001,0x5A01,0x5A01,0x5A01,0x5A01,0x5901,0x5901, 0x5901,0x5901,0x5704,0x5701,0x5701,0x5701,0x5701,0x5604,0x8004,0x5604, 0x5604,0x5604,0x5604,0x5604,0x5901,0x5901,0x5901,0x5901,0x5704,0x8004, 0x5304,0x5704,0x5504,0x5304,0x5204,0x5201,0x5201,0x5201,0x5201,0x5104, 0x8004,0x5104,0x5104,0x5104,0x5104,0x5104,0x5401,0x5401,0x5401,0x5401, 0x5204,0x8004,0x4201,0x4201,0x4201,0x4201,0x4401,0x4401,0x4401,0x4401, 0x4601,0x4601,0x4601,0x4601,0x4701,0x4701,0x4701,0x4701,0x4901,0x4901, 0x4901,0x4901,0x5001,0x5001,0x5001,0x5001,0x4A04,0x8004,0x4601,0x4601, 0x4601,0x4601,0x4701,0x4701,0x4701,0x4701,0x4901,0x4901,0x4901,0x4901, 0x4A01,0x4A01,0x4A01,0x4A01,0x5101,0x5101,0x5101,0x5101,0x5401,0x5401, 0x5401,0x5401,0x5204,0x8004,0x5201,0x5201,0x5201,0x5201,0x5401,0x5401, 0x5401,0x5401,0x5601,0x5601,0x5601,0x5601,0x5701,0x5701,0x5701,0x5701, 0x5901,0x5901,0x5901,0x5901,0x5A01,0x5A01,0x5A01,0x5A01,0x5A01,0x5A01, 0x5A01,0x5A01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01, 0x6001,0x6001,0x6001,0x6001,0x6001,0x6001,0x6001,0x6001,0x6108,0x6201, 0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201, 0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201, 0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201, 0x6201,0x6210,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601, 0x5601,0x5601,0x5601,0x5601,0x5401,0x5401,0x5602,0x5708,0x8004,0x5204, 0x5708,0x8004,0x5204,0x5704,0x5204,0x5704,0x5B04,0x6208,0x8008,0x6008, 0x8004,0x5904,0x6008,0x8004,0x5904,0x6004,0x5904,0x5604,0x5904,0x5208, 0x8008,0x5704,0x8004,0x570C,0x5B01,0x5B01,0x5B01,0x5B01,0x5904,0x5704, 0x5701,0x5701,0x5701,0x5701,0x5604,0x560C,0x5901,0x5901,0x5901,0x5901, 0x6004,0x5604,0x5901,0x5901,0x5901,0x5901,0x5704,0x570C,0x5B01,0x5B01, 0x5B01,0x5B01,0x5904,0x5704,0x5701,0x5701,0x5701,0x5701,0x5604,0x560C, 0x5901,0x5901,0x5901,0x5901,0x6004,0x5604,0x5704,0x5704,0x5601,0x5601, 0x5601,0x5601,0x5401,0x5401,0x5602,0x5704,0x5704,0x5901,0x5901,0x5901, 0x5901,0x5701,0x5701,0x5902,0x5B04,0x5B04,0x6001,0x6001,0x6001,0x6001, 0x5B01,0x5B01,0x6001,0x6001,0x6208,0x8008,0x5201,0x5201,0x5201,0x5201, 0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201, 0x5201,0x5201,0x5410,0x5008,0x5008,0x4B08,0x4B08,0x4908,0x4908,0x4701, 0x4701,0x4701,0x4701,0x4604,0x4404,0x4604,0x4704,0x8004,0x4904,0x8004, 0x4B04,0x800C,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201, 0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5410,0x5201, 0x5201,0x5201,0x5201,0x5004,0x5004,0x5004,0x5001,0x5001,0x5001,0x5001, 0x4B04,0x4B04,0x4B04,0x4B01,0x4B01,0x4B01,0x4B01,0x4904,0x4904,0x4904, 0x4701,0x4701,0x4701,0x4701,0x4604,0x4404,0x4604,0x4714,0x4701,0x4701, 0x4601,0x4701,0x4901,0x4901,0x4901,0x4901,0x4604,0x4B14,0x4B01,0x4B01, 0x4901,0x4B01,0x5001,0x5001,0x5001,0x5001,0x4904,0x5210,0x5408,0x5608, 0x5708,0x5908,0x5B08,0x5108,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201, 0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x5904,0x6101,0x6101,0x6101, 0x6101,0x6101,0x6101,0x5902,0x5101,0x5101,0x5101,0x5101,0x5101,0x5101, 0x5902,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201, 0x6201,0x6201,0x6201,0x5904,0x6101,0x6101,0x6101,0x6101,0x6101,0x6101, 0x5902,0x5101,0x5101,0x5101,0x5101,0x5101,0x5101,0x5902,0x6204,0x5904, 0x6104,0x5904,0x6204,0x5904,0x6104,0x5904,0x6204,0x4204,0x4204,0x4204, 0x4208,0x8008,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201, 0x5201,0x5201,0x5001,0x5001,0x4B01,0x4B01,0x4901,0x4901,0x4704,0x8004, 0x5404,0x8004,0x5004,0x8004,0x4904,0x8004,0x5204,0x800C,0x5B01,0x5B01, 0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5901,0x5901, 0x5701,0x5701,0x5601,0x5601,0x5404,0x8004,0x6004,0x8004,0x5B01,0x5B01, 0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01, 0x5B01,0x5B01,0x5B01,0x5B01,0x5908,0x8008,0x8004,0x6204,0x6204,0x6204, 0x6204,0x6204,0x6204,0x6204,0x6204,0x6204,0x6204,0x6204,0x6201,0x6201, 0x6201,0x6201,0x6001,0x6001,0x6001,0x6001,0x5901,0x5901,0x5901,0x5901, 0x5604,0x5601,0x5601,0x5601,0x5601,0x5704,0x8004,0x5404,0x5401,0x5401, 0x5401,0x5401,0x5204,0x8004,0x4604,0x4708,0x8004,0x5204,0x5701,0x5701, 0x5701,0x5701,0x5601,0x5601,0x5601,0x5601,0x5401,0x5401,0x5401,0x5401, 0x5204,0x5401,0x5401,0x5401,0x5401,0x5204,0x8004,0x5204,0x5204,0x5204, 0x5204,0x5204,0x5401,0x5401,0x5401,0x5401,0x5204,0x8004,0x5204,0x5704, 0x5604,0x5404,0x5204,0x5401,0x5401,0x5401,0x5401,0x5204,0x8004,0x5204, 0x5204,0x5204,0x5204,0x5204,0x5401,0x5401,0x5401,0x5401,0x5204,0x8008, 0x540A,0x5201,0x5201,0x5001,0x5001,0x4B01,0x4B01,0x5008,0x8008,0x520A, 0x5001,0x5001,0x4B01,0x4B01,0x4901,0x4901,0x4B08,0x8008,0x5401,0x5401, 0x5401,0x5401,0x5601,0x5601,0x5701,0x5701,0x5604,0x5404,0x5401,0x5401, 0x5401,0x5401,0x5204,0x4B04,0x5204,0x5201,0x5201,0x5201,0x5201,0x5004, 0x4B04,0x4904,0x4708,0x8004,0x5204,0x5701,0x5701,0x5701,0x5701,0x5601, 0x5601,0x5601,0x5601,0x5401,0x5401,0x5401,0x5401,0x5204,0x5401,0x5401, 0x5401,0x5401,0x5204,0x8004,0x5204,0x5204,0x5204,0x5204,0x5204,0x5401, 0x5401,0x5401,0x5401,0x5204,0x8004,0x5204,0x5701,0x5701,0x5701,0x5701, 0x5601,0x5601,0x5601,0x5601,0x5401,0x5401,0x5401,0x5401,0x5204,0x5401, 0x5401,0x5401,0x5401,0x5204,0x8004,0x5204,0x5204,0x5204,0x5204,0x5204, 0x5401,0x5401,0x5401,0x5401,0x5204,0x8008,0x640A,0x6201,0x6201,0x6001, 0x6001,0x5B01,0x5B01,0x6008,0x8008,0x620A,0x6001,0x6001,0x5B01,0x5B01, 0x5901,0x5901,0x5B08,0x8008,0x5401,0x5401,0x5401,0x5401,0x5601,0x5601, 0x5701,0x5701,0x5604,0x5404,0x5204,0x5704,0x5B04,0x6204,0x6201,0x6201, 0x6201,0x6201,0x6004,0x5B04,0x5904,0x5704,0x4204,0x4404,0x4604,0x4704, 0x4704,0x4901,0x4901,0x4901,0x4901,0x4701,0x4701,0x4901,0x4901,0x4B04, 0x4604,0x4704,0x4904,0x4B04,0x4B04,0x5001,0x5001,0x5001,0x5001,0x4B01, 0x4B01,0x5001,0x5001,0x5204,0x5204,0x5301,0x5301,0x5301,0x5301,0x5101, 0x5101,0x5301,0x5301,0x5408,0x8008,0x440C,0x4904,0x4704,0x4604,0x4404, 0x4204,0x5201,0x5201,0x5201,0x5201,0x5101,0x5101,0x5101,0x5101,0x5001, 0x5001,0x5001,0x5001,0x4B01,0x4B01,0x4B01,0x4B01,0x5201,0x5201,0x5201, 0x5201,0x5101,0x5101,0x5101,0x5101,0x5001,0x5001,0x5001,0x5001,0x4B04, 0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401, 0x4401,0x4401,0x4904,0x4701,0x4701,0x4701,0x4701,0x4601,0x4601,0x4601, 0x4601,0x4401,0x4401,0x4401,0x4401,0x4204,0x5201,0x5201,0x5201,0x5201, 0x5401,0x5401,0x5401,0x5401,0x5601,0x5601,0x5601,0x5601,0x5701,0x5701, 0x5701,0x5701,0x5201,0x5201,0x5201,0x5201,0x5401,0x5401,0x5401,0x5401, 0x5601,0x5601,0x5601,0x5601,0x5704,0x5908,0x8008,0x6208,0x8008,0x5708, 0x8004,0x5204,0x4B04,0x4704,0x4B04,0x5204,0x5704,0x5204,0x5704,0x5B04, 0x6208,0x5608,0x5708,0x8004,0x5204,0x4B04,0x4704,0x4B04,0x5204,0x5704, 0x5204,0x5704,0x5B04,0x6208,0x5608,0x5708,0x8008,0x5708,0x8008,0x5708, 0x4706,0x4702,0x4708,0x8008,0x5208,0x8004,0x4904,0x5208,0x8004,0x4904, 0x5204,0x4904,0x5204,0x5604,0x5908,0x8008,0x5908,0x8004,0x5604,0x5908, 0x8004,0x5604,0x5904,0x5604,0x5304,0x5604,0x4B08,0x8014,0x5704,0x6001, 0x6001,0x6001,0x6001,0x5B01,0x5B01,0x5B01,0x5B01,0x5901,0x5901,0x5901, 0x5901,0x5704,0x5901,0x5901,0x5901,0x5901,0x5704,0x8004,0x5704,0x5704, 0x5704,0x5704,0x5704,0x5901,0x5901,0x5901,0x5901,0x5704,0x8004,0x5704, 0x6001,0x6001,0x6001,0x6001,0x5B01,0x5B01,0x5B01,0x5B01,0x5901,0x5901, 0x5901,0x5901,0x5704,0x5901,0x5901,0x5901,0x5901,0x5704,0x8004,0x5704, 0x5704,0x5704,0x5704,0x5704,0x5901,0x5901,0x5901,0x5901,0x5704,0x8004, 0x5704,0x6001,0x6001,0x6001,0x6001,0x5B01,0x5B01,0x5B01,0x5B01,0x5901, 0x5901,0x5901,0x5901,0x5704,0x5901,0x5901,0x5901,0x5901,0x5804,0x8004, 0x5804,0x5804,0x5804,0x5804,0x5804,0x5B01,0x5B01,0x5B01,0x5B01,0x5904, 0x8004,0x5904,0x6001,0x6001,0x6001,0x6001,0x5A01,0x5A01,0x5A01,0x5A01, 0x5901,0x5901,0x5901,0x5901,0x5704,0x5701,0x5701,0x5701,0x5701,0x5604, 0x8004,0x5604,0x5604,0x5604,0x5604,0x5604,0x5901,0x5901,0x5901,0x5901, 0x5704,0x8004,0x5304,0x5704,0x5504,0x5304,0x5204,0x5201,0x5201,0x5201, 0x5201,0x5104,0x8004,0x5104,0x5104,0x5104,0x5104,0x5104,0x5401,0x5401, 0x5401,0x5401,0x5204,0x8004,0x4201,0x4201,0x4201,0x4201,0x4401,0x4401, 0x4401,0x4401,0x4601,0x4601,0x4601,0x4601,0x4701,0x4701,0x4701,0x4701, 0x4901,0x4901,0x4901,0x4901,0x5001,0x5001,0x5001,0x5001,0x4A04,0x8004, 0x4601,0x4601,0x4601,0x4601,0x4701,0x4701,0x4701,0x4701,0x4901,0x4901, 0x4901,0x4901,0x4A01,0x4A01,0x4A01,0x4A01,0x5101,0x5101,0x5101,0x5101, 0x5401,0x5401,0x5401,0x5401,0x5204,0x8004,0x5201,0x5201,0x5201,0x5201, 0x5401,0x5401,0x5401,0x5401,0x5601,0x5601,0x5601,0x5601,0x5701,0x5701, 0x5701,0x5701,0x5901,0x5901,0x5901,0x5901,0x5A01,0x5A01,0x5A01,0x5A01, 0x5A01,0x5A01,0x5A01,0x5A01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01, 0x5B01,0x5B01,0x6001,0x6001,0x6001,0x6001,0x6001,0x6001,0x6001,0x6001, 0x6108,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201, 0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201, 0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201, 0x6201,0x6201,0x6201,0x6210,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601, 0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5401,0x5401,0x5602,0x5708, 0x8004,0x5204,0x5708,0x8004,0x5204,0x5704,0x5204,0x5704,0x5B04,0x6208, 0x8008,0x6008,0x8004,0x5904,0x6008,0x8004,0x5904,0x6004,0x5904,0x5604, 0x5904,0x5208,0x8008,0x5704,0x8004,0x570C,0x5B01,0x5B01,0x5B01,0x5B01, 0x5904,0x5704,0x5701,0x5701,0x5701,0x5701,0x5604,0x560C,0x5901,0x5901, 0x5901,0x5901,0x6004,0x5604,0x5901,0x5901,0x5901,0x5901,0x5704,0x570C, 0x5B01,0x5B01,0x5B01,0x5B01,0x5904,0x5704,0x5701,0x5701,0x5701,0x5701, 0x5604,0x560C,0x5901,0x5901,0x5901,0x5901,0x6004,0x5604,0x5704,0x5704, 0x5601,0x5601,0x5601,0x5601,0x5401,0x5401,0x5602,0x5704,0x5704,0x5901, 0x5901,0x5901,0x5901,0x5701,0x5701,0x5902,0x5B04,0x5B04,0x6001,0x6001, 0x6001,0x6001,0x5B01,0x5B01,0x6001,0x6001,0x6208,0x8008,0x5201,0x5201, 0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201, 0x5201,0x5201,0x5201,0x5201,0x5410,0x5008,0x5008,0x4B08,0x4B08,0x4908, 0x4908,0x4701,0x4701,0x4701,0x4701,0x4604,0x4404,0x4604,0x4704,0x8004, 0x4904,0x8004,0x4B04,0x800C,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201, 0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201, 0x5410,0x5201,0x5201,0x5201,0x5201,0x5004,0x5004,0x5004,0x5001,0x5001, 0x5001,0x5001,0x4B04,0x4B04,0x4B04,0x4B01,0x4B01,0x4B01,0x4B01,0x4904, 0x4904,0x4904,0x4701,0x4701,0x4701,0x4701,0x4604,0x4404,0x4604,0x4714, 0x4701,0x4701,0x4601,0x4701,0x4901,0x4901,0x4901,0x4901,0x4604,0x4B14, 0x4B01,0x4B01,0x4901,0x4B01,0x5001,0x5001,0x5001,0x5001,0x4904,0x5210, 0x5408,0x5608,0x5708,0x5908,0x5B08,0x5108,0x6201,0x6201,0x6201,0x6201, 0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x5904,0x6101, 0x6101,0x6101,0x6101,0x6101,0x6101,0x5902,0x5101,0x5101,0x5101,0x5101, 0x5101,0x5101,0x5902,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201,0x6201, 0x6201,0x6201,0x6201,0x6201,0x6201,0x5904,0x6101,0x6101,0x6101,0x6101, 0x6101,0x6101,0x5902,0x5101,0x5101,0x5101,0x5101,0x5101,0x5101,0x5902, 0x6204,0x5904,0x6104,0x5904,0x6204,0x5904,0x6104,0x5904,0x6204,0x4204, 0x4204,0x4204,0x4208,0x8008,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201, 0x5201,0x5201,0x5201,0x5201,0x5001,0x5001,0x4B01,0x4B01,0x4901,0x4901, 0x4704,0x8004,0x5404,0x8004,0x5004,0x8004,0x4904,0x8004,0x5204,0x800C, 0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01, 0x5901,0x5901,0x5701,0x5701,0x5601,0x5601,0x5404,0x8004,0x6004,0x8004, 0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01, 0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5B01,0x5908,0x8008,0x8004,0x6204, 0x6204,0x6204,0x6204,0x6204,0x6204,0x6204,0x6204,0x6204,0x6204,0x6204, 0x6201,0x6201,0x6201,0x6201,0x6001,0x6001,0x6001,0x6001,0x5901,0x5901, 0x5901,0x5901,0x5604,0x5601,0x5601,0x5601,0x5601,0x5704,0x8004,0x5404, 0x5401,0x5401,0x5401,0x5401,0x5204,0x8004,0x4604,0x4708,0x8004,0x5204, 0x5701,0x5701,0x5701,0x5701,0x5601,0x5601,0x5601,0x5601,0x5401,0x5401, 0x5401,0x5401,0x5204,0x5401,0x5401,0x5401,0x5401,0x5204,0x8004,0x5204, 0x5204,0x5204,0x5204,0x5204,0x5401,0x5401,0x5401,0x5401,0x5204,0x8004, 0x5204,0x5704,0x5604,0x5404,0x5204,0x5401,0x5401,0x5401,0x5401,0x5204, 0x8004,0x5204,0x5204,0x5204,0x5204,0x5204,0x5401,0x5401,0x5401,0x5401, 0x5204,0x8008,0x540A,0x5201,0x5201,0x5001,0x5001,0x4B01,0x4B01,0x5008, 0x8008,0x520A,0x5001,0x5001,0x4B01,0x4B01,0x4901,0x4901,0x4B08,0x8008, 0x5401,0x5401,0x5401,0x5401,0x5601,0x5601,0x5701,0x5701,0x5604,0x5404, 0x5401,0x5401,0x5401,0x5401,0x5204,0x4B04,0x5204,0x5201,0x5201,0x5201, 0x5201,0x5004,0x4B04,0x4904,0x4708,0x8004,0x5204,0x5701,0x5701,0x5701, 0x5701,0x5601,0x5601,0x5601,0x5601,0x5401,0x5401,0x5401,0x5401,0x5204, 0x5401,0x5401,0x5401,0x5401,0x5204,0x8004,0x5204,0x5204,0x5204,0x5204, 0x5204,0x5401,0x5401,0x5401,0x5401,0x5204,0x8004,0x5204,0x5701,0x5701, 0x5701,0x5701,0x5601,0x5601,0x5601,0x5601,0x5401,0x5401,0x5401,0x5401, 0x5204,0x5401,0x5401,0x5401,0x5401,0x5204,0x8004,0x5204,0x5204,0x5204, 0x5204,0x5204,0x5401,0x5401,0x5401,0x5401,0x5204,0x8008,0x640A,0x6201, 0x6201,0x6001,0x6001,0x5B01,0x5B01,0x6008,0x8008,0x620A,0x6001,0x6001, 0x5B01,0x5B01,0x5901,0x5901,0x5B08,0x8008,0x5401,0x5401,0x5401,0x5401, 0x5601,0x5601,0x5701,0x5701,0x5604,0x5404,0x5204,0x5704,0x5B04,0x6204, 0x6201,0x6201,0x6201,0x6201,0x6004,0x5B04,0x5904,0x5704,0x4204,0x4404, 0x4604,0x4704,0x4704,0x4901,0x4901,0x4901,0x4901,0x4701,0x4701,0x4901, 0x4901,0x4B04,0x4604,0x4704,0x4904,0x4B04,0x4B04,0x5001,0x5001,0x5001, 0x5001,0x4B01,0x4B01,0x5001,0x5001,0x5204,0x5204,0x5301,0x5301,0x5301, 0x5301,0x5101,0x5101,0x5301,0x5301,0x5408,0x8008,0x440C,0x4904,0x4704, 0x4604,0x4404,0x4204,0x5201,0x5201,0x5201,0x5201,0x5101,0x5101,0x5101, 0x5101,0x5001,0x5001,0x5001,0x5001,0x4B01,0x4B01,0x4B01,0x4B01,0x5201, 0x5201,0x5201,0x5201,0x5101,0x5101,0x5101,0x5101,0x5001,0x5001,0x5001, 0x5001,0x4B04,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401, 0x4401,0x4401,0x4401,0x4401,0x4904,0x4701,0x4701,0x4701,0x4701,0x4601, 0x4601,0x4601,0x4601,0x4401,0x4401,0x4401,0x4401,0x4204,0x5201,0x5201, 0x5201,0x5201,0x5401,0x5401,0x5401,0x5401,0x5601,0x5601,0x5601,0x5601, 0x5701,0x5701,0x5701,0x5701,0x5201,0x5201,0x5201,0x5201,0x5401,0x5401, 0x5401,0x5401,0x5601,0x5601,0x5601,0x5601,0x5704,0x5908,0x8008,0x6208, 0x8008,0x5708,0x8004,0x5204,0x4B04,0x4704,0x4B04,0x5204,0x5704,0x5204, 0x5704,0x5B04,0x6208,0x5608,0x5708,0x8004,0x5204,0x4B04,0x4704,0x4B04, 0x5204,0x5704,0x5204,0x5704,0x5B04,0x6208,0x5608,0x5708,0x8008,0x5708, 0x8008,0x5708,0x4706,0x4702,0x4708,0x8008, 0x0000 }; static unsigned Voice2 [] = { 0x4708,0x8004,0x4204,0x4708,0x8004,0x4204,0x4704,0x4204,0x4704,0x4B04, 0x5208,0x8008,0x5008,0x8004,0x4904,0x5008,0x8004,0x4904,0x5004,0x4904, 0x4604,0x4904,0x4208,0x8008,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704, 0x4704,0x4704,0x4904,0x4904,0x4904,0x4904,0x4901,0x4901,0x4901,0x4901, 0x5004,0x4601,0x4601,0x4601,0x4601,0x4904,0x4704,0x4704,0x4704,0x4704, 0x4704,0x4704,0x4704,0x4704,0x4904,0x4904,0x4904,0x4904,0x4901,0x4901, 0x4901,0x4901,0x5004,0x4601,0x4601,0x4601,0x4601,0x4904,0x4210,0x4210, 0x4210,0x4208,0x8028,0x3610,0x3710,0x4008,0x4008,0x3908,0x3208,0x3204, 0x8004,0x4204,0x8004,0x4208,0x8028,0x4601,0x4601,0x4601,0x4601,0x4601, 0x4601,0x4601,0x4601,0x4601,0x4601,0x4601,0x4601,0x4601,0x4601,0x4601, 0x4601,0x4710,0x4008,0x4004,0x4004,0x3908,0x3904,0x3904,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x3704,0x4704,0x4704,0x4704,0x4704,0x4704, 0x4904,0x4904,0x4704,0x4704,0x4604,0x4604,0x4704,0x4704,0x4404,0x4404, 0x4210,0x4410,0x4210,0x4410,0x4604,0x4704,0x4904,0x4704,0x4604,0x4704, 0x4904,0x4604,0x4B04,0x4904,0x4704,0x4904,0x4B04,0x4904,0x4804,0x4B04, 0x4904,0x4904,0x4904,0x4904,0x4904,0x4904,0x4904,0x4904,0x4904,0x3904, 0x3904,0x3904,0x3908,0x8020,0x4604,0x8004,0x3B04,0x8004,0x4704,0x8004, 0x4404,0x8004,0x4104,0x800C,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401, 0x4401,0x4401,0x4204,0x8004,0x4404,0x8004,0x4201,0x4201,0x4201,0x4201, 0x4201,0x4201,0x4201,0x4201,0x4201,0x4201,0x4201,0x4201,0x4201,0x4201, 0x4201,0x4201,0x4108,0x8010,0x4101,0x4101,0x4101,0x4101,0x4101,0x4101, 0x4101,0x4101,0x4204,0x8004,0x4604,0x8004,0x3B04,0x8004,0x3704,0x8004, 0x3408,0x8004,0x4404,0x4704,0x4604,0x8004,0x5704,0x5701,0x5701,0x5701, 0x5701,0x5604,0x8004,0x4704,0x4204,0x4204,0x4404,0x4404,0x4604,0x4604, 0x4204,0x4204,0x4104,0x4104,0x4204,0x4204,0x4404,0x4404,0x4104,0x4104, 0x4204,0x4204,0x4404,0x4404,0x4604,0x4604,0x4204,0x4204,0x4104,0x4104, 0x4204,0x4204,0x4404,0x4404,0x4104,0x4104,0x4204,0x4204,0x4604,0x4404, 0x4304,0x3B04,0x4104,0x4304,0x4404,0x4704,0x4404,0x4204,0x4104,0x3904, 0x3B04,0x4104,0x5204,0x5204,0x5204,0x5204,0x5204,0x5204,0x5204,0x5204, 0x5204,0x4904,0x4904,0x4904,0x4904,0x4904,0x4904,0x4704,0x4604,0x4204, 0x4404,0x4404,0x4604,0x4604,0x4204,0x4204,0x4104,0x4104,0x4204,0x4204, 0x4404,0x4404,0x4104,0x4104,0x4204,0x4204,0x4404,0x4404,0x4604,0x4604, 0x4204,0x4204,0x4104,0x4104,0x4204,0x4204,0x4404,0x4404,0x4104,0x4104, 0x4204,0x4204,0x4604,0x4404,0x4304,0x3B04,0x4104,0x4304,0x4404,0x4704, 0x4404,0x4204,0x4104,0x3904,0x3B04,0x4104,0x4204,0x5204,0x5204,0x5204, 0x5204,0x5204,0x5204,0x5204,0x5204,0x4904,0x4904,0x4904,0x4904,0x4904, 0x4904,0x4704,0x4604,0x3904,0x3B04,0x4104,0x4204,0x4204,0x4404,0x4404, 0x4604,0x4104,0x4204,0x4404,0x4604,0x4604,0x4704,0x4704,0x4904,0x4904, 0x4A04,0x4A04,0x4B08,0x8008,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401, 0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401, 0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4201,0x4201, 0x4201,0x4201,0x4104,0x5204,0x8004,0x5204,0x8004,0x5204,0x800C,0x4708, 0x8004,0x4204,0x4708,0x8004,0x4204,0x4704,0x4204,0x4704,0x4B04,0x5208, 0x8008,0x5008,0x8004,0x4904,0x5008,0x8004,0x4904,0x5004,0x4904,0x4604, 0x4904,0x4208,0x8008,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704, 0x4704,0x4904,0x4904,0x4904,0x4904,0x4901,0x4901,0x4901,0x4901,0x5004, 0x4601,0x4601,0x4601,0x4601,0x4904,0x4704,0x4704,0x4704,0x4704,0x4704, 0x4704,0x4704,0x4704,0x4904,0x4904,0x4904,0x4904,0x4901,0x4901,0x4901, 0x4901,0x5004,0x4601,0x4601,0x4601,0x4601,0x4904,0x4210,0x4210,0x4210, 0x4208,0x8028,0x3610,0x3710,0x4008,0x4008,0x3908,0x3208,0x3204,0x8004, 0x4204,0x8004,0x4208,0x8028,0x4601,0x4601,0x4601,0x4601,0x4601,0x4601, 0x4601,0x4601,0x4601,0x4601,0x4601,0x4601,0x4601,0x4601,0x4601,0x4601, 0x4710,0x4008,0x4004,0x4004,0x3908,0x3904,0x3904,0x3704,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4904, 0x4904,0x4704,0x4704,0x4604,0x4604,0x4704,0x4704,0x4404,0x4404,0x4210, 0x4410,0x4210,0x4410,0x4604,0x4704,0x4904,0x4704,0x4604,0x4704,0x4904, 0x4604,0x4B04,0x4904,0x4704,0x4904,0x4B04,0x4904,0x4804,0x4B04,0x4904, 0x4904,0x4904,0x4904,0x4904,0x4904,0x4904,0x4904,0x4904,0x3904,0x3904, 0x3904,0x3908,0x8020,0x4604,0x8004,0x3B04,0x8004,0x4704,0x8004,0x4404, 0x8004,0x4104,0x800C,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401, 0x4401,0x4204,0x8004,0x4404,0x8004,0x4201,0x4201,0x4201,0x4201,0x4201, 0x4201,0x4201,0x4201,0x4201,0x4201,0x4201,0x4201,0x4201,0x4201,0x4201, 0x4201,0x4108,0x8010,0x4101,0x4101,0x4101,0x4101,0x4101,0x4101,0x4101, 0x4101,0x4204,0x8004,0x4604,0x8004,0x3B04,0x8004,0x3704,0x8004,0x3408, 0x8004,0x4404,0x4704,0x4604,0x8004,0x5704,0x5701,0x5701,0x5701,0x5701, 0x5604,0x8004,0x4704,0x4204,0x4204,0x4404,0x4404,0x4604,0x4604,0x4204, 0x4204,0x4104,0x4104,0x4204,0x4204,0x4404,0x4404,0x4104,0x4104,0x4204, 0x4204,0x4404,0x4404,0x4604,0x4604,0x4204,0x4204,0x4104,0x4104,0x4204, 0x4204,0x4404,0x4404,0x4104,0x4104,0x4204,0x4204,0x4604,0x4404,0x4304, 0x3B04,0x4104,0x4304,0x4404,0x4704,0x4404,0x4204,0x4104,0x3904,0x3B04, 0x4104,0x5204,0x5204,0x5204,0x5204,0x5204,0x5204,0x5204,0x5204,0x5204, 0x4904,0x4904,0x4904,0x4904,0x4904,0x4904,0x4704,0x4604,0x4204,0x4404, 0x4404,0x4604,0x4604,0x4204,0x4204,0x4104,0x4104,0x4204,0x4204,0x4404, 0x4404,0x4104,0x4104,0x4204,0x4204,0x4404,0x4404,0x4604,0x4604,0x4204, 0x4204,0x4104,0x4104,0x4204,0x4204,0x4404,0x4404,0x4104,0x4104,0x4204, 0x4204,0x4604,0x4404,0x4304,0x3B04,0x4104,0x4304,0x4404,0x4704,0x4404, 0x4204,0x4104,0x3904,0x3B04,0x4104,0x4204,0x5204,0x5204,0x5204,0x5204, 0x5204,0x5204,0x5204,0x5204,0x4904,0x4904,0x4904,0x4904,0x4904,0x4904, 0x4704,0x4604,0x3904,0x3B04,0x4104,0x4204,0x4204,0x4404,0x4404,0x4604, 0x4104,0x4204,0x4404,0x4604,0x4604,0x4704,0x4704,0x4904,0x4904,0x4A04, 0x4A04,0x4B08,0x8008,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401, 0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401, 0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4401,0x4201,0x4201,0x4201, 0x4201,0x4104,0x5204,0x8004,0x5204,0x8004,0x5204,0x800C,0x4208,0x8004, 0x3904,0x4208,0x8004,0x3904,0x4204,0x3904,0x4204,0x4604,0x4908,0x8008, 0x4908,0x8004,0x4604,0x4908,0x8004,0x4604,0x4904,0x4604,0x4304,0x4604, 0x3B08,0x8008,0x4004,0x4004,0x4204,0x4204,0x4404,0x4404,0x4004,0x4004, 0x3B04,0x3B04,0x4004,0x4004,0x4204,0x4204,0x3B04,0x3B04,0x4004,0x4004, 0x4204,0x4204,0x4404,0x4404,0x4004,0x4004,0x3B04,0x3B04,0x4004,0x4004, 0x4204,0x4204,0x3B04,0x3B04,0x4004,0x4004,0x4204,0x4204,0x4404,0x4404, 0x4004,0x4004,0x3B04,0x3B04,0x4004,0x4004,0x4204,0x4204,0x3B04,0x3B04, 0x3904,0x3904,0x3B04,0x3B04,0x4004,0x4004,0x3904,0x3904,0x3904,0x3904, 0x3A04,0x3A04,0x4004,0x4004,0x3904,0x3904,0x3704,0x3704,0x3604,0x3604, 0x3704,0x3704,0x4604,0x4604,0x4704,0x4704,0x4604,0x4604,0x4704,0x3704, 0x3604,0x3704,0x3908,0x8004,0x3201,0x3201,0x3201,0x3201,0x3401,0x3401, 0x3401,0x3401,0x3601,0x3601,0x3601,0x3601,0x3701,0x3701,0x3701,0x3701, 0x3901,0x3901,0x3901,0x3901,0x4001,0x4001,0x4001,0x4001,0x3A04,0x8004, 0x3601,0x3601,0x3601,0x3601,0x3701,0x3701,0x3701,0x3701,0x3901,0x3901, 0x3901,0x3901,0x3A01,0x3A01,0x3A01,0x3A01,0x4101,0x4101,0x4101,0x4101, 0x4401,0x4401,0x4401,0x4401,0x4204,0x8038,0x4B04,0x4B04,0x4B01,0x4B01, 0x4B01,0x4B01,0x5004,0x4904,0x4904,0x4901,0x4901,0x4901,0x4901,0x4B04, 0x4704,0x4704,0x4701,0x4701,0x4701,0x4701,0x4B04,0x4B01,0x4B01,0x4B01, 0x4B01,0x4904,0x4704,0x4204,0x3B08,0x8004,0x4204,0x4708,0x8004,0x4204, 0x4704,0x4204,0x4704,0x4B04,0x5208,0x8008,0x5008,0x8004,0x4904,0x5008, 0x8004,0x4904,0x5004,0x4904,0x4604,0x4904,0x4208,0x8008,0x4704,0x4704, 0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704, 0x4701,0x4701,0x4701,0x4701,0x4B04,0x4401,0x4401,0x4401,0x4401,0x4704, 0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704, 0x4704,0x4704,0x4701,0x4701,0x4701,0x4701,0x4B04,0x4401,0x4401,0x4401, 0x4401,0x4704,0x4210,0x4210,0x4210,0x4208,0x8028,0x3610,0x3710,0x4008, 0x4008,0x3908,0x3908,0x3204,0x8004,0x4204,0x8004,0x4208,0x8028,0x4601, 0x4601,0x4601,0x4601,0x4601,0x4601,0x4601,0x4601,0x4601,0x4601,0x4601, 0x4601,0x4601,0x4601,0x4601,0x4601,0x4710,0x4008,0x4004,0x4004,0x3908, 0x3904,0x3904,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x4704, 0x4704,0x4704,0x4704,0x4704,0x4904,0x4904,0x4704,0x4704,0x4604,0x4604, 0x4704,0x4704,0x4404,0x4404,0x4210,0x4410,0x4210,0x4410,0x4208,0x4408, 0x4208,0x4408,0x4204,0x3204,0x3204,0x3204,0x3208,0x8020,0x3B04,0x8004, 0x3404,0x8004,0x4004,0x8004,0x3904,0x8004,0x3604,0x800C,0x4901,0x4901, 0x4901,0x4901,0x4901,0x4901,0x4901,0x4901,0x4704,0x8004,0x4904,0x8004, 0x4B10,0x4908,0x8008,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201, 0x5201,0x5201,0x5201,0x5001,0x5001,0x4B01,0x4B01,0x4901,0x4901,0x4704, 0x8004,0x5404,0x8004,0x5004,0x8004,0x4904,0x8004,0x5208,0x8004,0x5004, 0x5001,0x5001,0x5001,0x5001,0x4B04,0x8004,0x5004,0x5001,0x5001,0x5001, 0x5001,0x4B04,0x8004,0x4004,0x3704,0x3704,0x3904,0x3904,0x3B04,0x3B04, 0x3704,0x3704,0x3604,0x3604,0x3704,0x3704,0x3904,0x3904,0x3604,0x3604, 0x3704,0x3704,0x3904,0x3904,0x3B04,0x3B04,0x3704,0x3704,0x3604,0x3604, 0x3704,0x3704,0x3904,0x3904,0x3604,0x3604,0x3704,0x4704,0x4B04,0x4904, 0x4804,0x4404,0x4604,0x4804,0x4904,0x5004,0x4904,0x4704,0x4604,0x4204, 0x4404,0x4604,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704, 0x4704,0x4204,0x4204,0x4204,0x4204,0x4204,0x4204,0x4004,0x3B04,0x3704, 0x3904,0x3904,0x3B04,0x3B04,0x3704,0x3704,0x3604,0x3604,0x3704,0x3704, 0x3904,0x3904,0x3604,0x3604,0x3704,0x4704,0x4904,0x4904,0x4B04,0x4B04, 0x4704,0x4704,0x4604,0x4604,0x4704,0x4704,0x4904,0x4904,0x4604,0x4604, 0x4704,0x4704,0x4B04,0x4904,0x4804,0x4404,0x4604,0x4804,0x4904,0x5004, 0x4904,0x4704,0x4604,0x4204,0x4404,0x4604,0x4704,0x4704,0x4704,0x4704, 0x4704,0x4704,0x4704,0x4704,0x4701,0x4701,0x4701,0x4701,0x4904,0x5004, 0x5004,0x5004,0x5004,0x5004,0x4B04,0x4904,0x4204,0x4404,0x4604,0x4704, 0x4704,0x4904,0x4904,0x4B04,0x3604,0x3704,0x3904,0x3B04,0x3B04,0x4004, 0x4004,0x4004,0x4004,0x4104,0x4104,0x4208,0x8008,0x3901,0x3901,0x3901, 0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901, 0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901, 0x3901,0x3701,0x3701,0x3701,0x3701,0x3604,0x3708,0x8018,0x3901,0x3901, 0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901, 0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901, 0x3901,0x3901,0x3701,0x3701,0x3701,0x3701,0x3604,0x3708,0x8008,0x4708, 0x8008,0x4408,0x8008,0x4708,0x8008,0x3710,0x3710,0x3710,0x3708,0x3908, 0x3710,0x3710,0x3710,0x3708,0x3908,0x3704,0x3B04,0x4204,0x4704,0x4B04, 0x4704,0x5204,0x4B04,0x4708,0x3706,0x3702,0x3708,0x8008,0x4208,0x8004, 0x3904,0x4208,0x8004,0x3904,0x4204,0x3904,0x4204,0x4604,0x4908,0x8008, 0x4908,0x8004,0x4604,0x4908,0x8004,0x4604,0x4904,0x4604,0x4304,0x4604, 0x3B08,0x8008,0x4004,0x4004,0x4204,0x4204,0x4404,0x4404,0x4004,0x4004, 0x3B04,0x3B04,0x4004,0x4004,0x4204,0x4204,0x3B04,0x3B04,0x4004,0x4004, 0x4204,0x4204,0x4404,0x4404,0x4004,0x4004,0x3B04,0x3B04,0x4004,0x4004, 0x4204,0x4204,0x3B04,0x3B04,0x4004,0x4004,0x4204,0x4204,0x4404,0x4404, 0x4004,0x4004,0x3B04,0x3B04,0x4004,0x4004,0x4204,0x4204,0x3B04,0x3B04, 0x3904,0x3904,0x3B04,0x3B04,0x4004,0x4004,0x3904,0x3904,0x3904,0x3904, 0x3A04,0x3A04,0x4004,0x4004,0x3904,0x3904,0x3704,0x3704,0x3604,0x3604, 0x3704,0x3704,0x4604,0x4604,0x4704,0x4704,0x4604,0x4604,0x4704,0x3704, 0x3604,0x3704,0x3908,0x8004,0x3201,0x3201,0x3201,0x3201,0x3401,0x3401, 0x3401,0x3401,0x3601,0x3601,0x3601,0x3601,0x3701,0x3701,0x3701,0x3701, 0x3901,0x3901,0x3901,0x3901,0x4001,0x4001,0x4001,0x4001,0x3A04,0x8004, 0x3601,0x3601,0x3601,0x3601,0x3701,0x3701,0x3701,0x3701,0x3901,0x3901, 0x3901,0x3901,0x3A01,0x3A01,0x3A01,0x3A01,0x4101,0x4101,0x4101,0x4101, 0x4401,0x4401,0x4401,0x4401,0x4204,0x8038,0x4B04,0x4B04,0x4B01,0x4B01, 0x4B01,0x4B01,0x5004,0x4904,0x4904,0x4901,0x4901,0x4901,0x4901,0x4B04, 0x4704,0x4704,0x4701,0x4701,0x4701,0x4701,0x4B04,0x4B01,0x4B01,0x4B01, 0x4B01,0x4904,0x4704,0x4204,0x3B08,0x8004,0x4204,0x4708,0x8004,0x4204, 0x4704,0x4204,0x4704,0x4B04,0x5208,0x8008,0x5008,0x8004,0x4904,0x5008, 0x8004,0x4904,0x5004,0x4904,0x4604,0x4904,0x4208,0x8008,0x4704,0x4704, 0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704, 0x4701,0x4701,0x4701,0x4701,0x4B04,0x4401,0x4401,0x4401,0x4401,0x4704, 0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704, 0x4704,0x4704,0x4701,0x4701,0x4701,0x4701,0x4B04,0x4401,0x4401,0x4401, 0x4401,0x4704,0x4210,0x4210,0x4210,0x4208,0x8028,0x3610,0x3710,0x4008, 0x4008,0x3908,0x3908,0x3204,0x8004,0x4204,0x8004,0x4208,0x8028,0x4601, 0x4601,0x4601,0x4601,0x4601,0x4601,0x4601,0x4601,0x4601,0x4601,0x4601, 0x4601,0x4601,0x4601,0x4601,0x4601,0x4710,0x4008,0x4004,0x4004,0x3908, 0x3904,0x3904,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x4704, 0x4704,0x4704,0x4704,0x4704,0x4904,0x4904,0x4704,0x4704,0x4604,0x4604, 0x4704,0x4704,0x4404,0x4404,0x4210,0x4410,0x4210,0x4410,0x4208,0x4408, 0x4208,0x4408,0x4204,0x3204,0x3204,0x3204,0x3208,0x8020,0x3B04,0x8004, 0x3404,0x8004,0x4004,0x8004,0x3904,0x8004,0x3604,0x800C,0x4901,0x4901, 0x4901,0x4901,0x4901,0x4901,0x4901,0x4901,0x4704,0x8004,0x4904,0x8004, 0x4B10,0x4908,0x8008,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201,0x5201, 0x5201,0x5201,0x5201,0x5001,0x5001,0x4B01,0x4B01,0x4901,0x4901,0x4704, 0x8004,0x5404,0x8004,0x5004,0x8004,0x4904,0x8004,0x5208,0x8004,0x5004, 0x5001,0x5001,0x5001,0x5001,0x4B04,0x8004,0x5004,0x5001,0x5001,0x5001, 0x5001,0x4B04,0x8004,0x4004,0x3704,0x3704,0x3904,0x3904,0x3B04,0x3B04, 0x3704,0x3704,0x3604,0x3604,0x3704,0x3704,0x3904,0x3904,0x3604,0x3604, 0x3704,0x3704,0x3904,0x3904,0x3B04,0x3B04,0x3704,0x3704,0x3604,0x3604, 0x3704,0x3704,0x3904,0x3904,0x3604,0x3604,0x3704,0x4704,0x4B04,0x4904, 0x4804,0x4404,0x4604,0x4804,0x4904,0x5004,0x4904,0x4704,0x4604,0x4204, 0x4404,0x4604,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704,0x4704, 0x4704,0x4204,0x4204,0x4204,0x4204,0x4204,0x4204,0x4004,0x3B04,0x3704, 0x3904,0x3904,0x3B04,0x3B04,0x3704,0x3704,0x3604,0x3604,0x3704,0x3704, 0x3904,0x3904,0x3604,0x3604,0x3704,0x4704,0x4904,0x4904,0x4B04,0x4B04, 0x4704,0x4704,0x4604,0x4604,0x4704,0x4704,0x4904,0x4904,0x4604,0x4604, 0x4704,0x4704,0x4B04,0x4904,0x4804,0x4404,0x4604,0x4804,0x4904,0x5004, 0x4904,0x4704,0x4604,0x4204,0x4404,0x4604,0x4704,0x4704,0x4704,0x4704, 0x4704,0x4704,0x4704,0x4704,0x4701,0x4701,0x4701,0x4701,0x4904,0x5004, 0x5004,0x5004,0x5004,0x5004,0x4B04,0x4904,0x4204,0x4404,0x4604,0x4704, 0x4704,0x4904,0x4904,0x4B04,0x3604,0x3704,0x3904,0x3B04,0x3B04,0x4004, 0x4004,0x4004,0x4004,0x4104,0x4104,0x4208,0x8008,0x3901,0x3901,0x3901, 0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901, 0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901, 0x3901,0x3701,0x3701,0x3701,0x3701,0x3604,0x3708,0x8018,0x3901,0x3901, 0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901, 0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901, 0x3901,0x3901,0x3701,0x3701,0x3701,0x3701,0x3604,0x3708,0x8008,0x4708, 0x8008,0x4408,0x8008,0x4708,0x8008,0x3710,0x3710,0x3710,0x3708,0x3908, 0x3710,0x3710,0x3710,0x3708,0x3908,0x3704,0x3B04,0x4204,0x4704,0x4B04, 0x4704,0x5204,0x4B04,0x4708,0x3706,0x3702,0x3708,0x8008, 0x0000 }; static unsigned Voice3 [] = { 0x3708,0x8004,0x3204,0x3708,0x8004,0x3204,0x3704,0x3204,0x3704,0x3B04, 0x3208,0x8008,0x4008,0x8004,0x3904,0x4008,0x8004,0x3904,0x4004,0x3904, 0x3604,0x4904,0x4208,0x8008,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3904,0x3904, 0x3B04,0x3B04,0x3604,0x3604,0x3704,0x3704,0x3904,0x3904,0x3B08,0x8028, 0x3210,0x3410,0x3008,0x3008,0x3208,0x3208,0x2B04,0x8004,0x3204,0x8004, 0x3708,0x8008,0x4B10,0x5010,0x3201,0x3201,0x3201,0x3201,0x3201,0x3201, 0x3201,0x3201,0x3201,0x3201,0x3201,0x3201,0x3201,0x3201,0x3201,0x3201, 0x3410,0x3008,0x3008,0x3208,0x3208,0x3B14,0x3B02,0x3901,0x3B01,0x4004, 0x3904,0x4714,0x4702,0x4601,0x4701,0x4904,0x4604,0x3704,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3604,0x3604,0x3704, 0x3704,0x3404,0x3404,0x3204,0x3204,0x3204,0x3204,0x3204,0x3204,0x3204, 0x3204,0x3204,0x3204,0x3204,0x3204,0x3204,0x3204,0x3204,0x3204,0x3204, 0x3404,0x3604,0x3404,0x3204,0x3404,0x3604,0x3204,0x3704,0x3904,0x3B04, 0x3904,0x3704,0x3904,0x3B04,0x3804,0x3904,0x3904,0x3904,0x3904,0x3904, 0x3904,0x3904,0x3904,0x3904,0x2904,0x2904,0x2904,0x2908,0x8008,0x490A, 0x4702,0x4602,0x4402,0x4204,0x8004,0x3304,0x8004,0x3404,0x8004,0x3204, 0x8004,0x3104,0x8004,0x2904,0x800C,0x2A01,0x2A01,0x2A01,0x2A01,0x2A01, 0x2A01,0x2A01,0x2A01,0x2B04,0x8004,0x2704,0x8004,0x2908,0x3901,0x3901, 0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901, 0x3801,0x3801,0x3801,0x3801,0x3701,0x3701,0x3701,0x3701,0x3401,0x3401, 0x3401,0x3401,0x3204,0x8004,0x3404,0x8004,0x3604,0x8004,0x3304,0x8004, 0x3404,0x8004,0x3204,0x8004,0x3104,0x8004,0x2904,0x8004,0x2B04,0x8004, 0x3704,0x8004,0x3904,0x8004,0x2904,0x8004,0x4604,0x4604,0x4704,0x4704, 0x4904,0x4904,0x4604,0x4604,0x4404,0x4404,0x4604,0x4604,0x4704,0x4704, 0x4404,0x4404,0x4604,0x4604,0x4704,0x4704,0x4904,0x4904,0x4604,0x4604, 0x4404,0x4404,0x4604,0x4604,0x4704,0x4704,0x4404,0x4404,0x4608,0x8008, 0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601, 0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5408,0x8008,0x5401,0x5401, 0x5401,0x5401,0x5401,0x5401,0x5401,0x5401,0x5401,0x5401,0x5401,0x5401, 0x5401,0x5401,0x5401,0x5401,0x5204,0x5604,0x5704,0x5904,0x5701,0x5701, 0x5701,0x5701,0x5901,0x5901,0x5B01,0x5B01,0x5904,0x5704,0x5701,0x5701, 0x5701,0x5701,0x5604,0x5204,0x5604,0x5601,0x5601,0x5601,0x5601,0x5404, 0x5204,0x5104,0x5204,0x4604,0x4704,0x4704,0x4904,0x4904,0x4604,0x4604, 0x4404,0x4404,0x4604,0x4604,0x4704,0x4704,0x4404,0x4404,0x4604,0x4604, 0x4704,0x4704,0x4904,0x4904,0x4604,0x4604,0x4404,0x4404,0x4604,0x4604, 0x4704,0x4704,0x4404,0x4404,0x4608,0x8008,0x5601,0x5601,0x5601,0x5601, 0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601, 0x5601,0x5601,0x5408,0x8008,0x5401,0x5401,0x5401,0x5401,0x5401,0x5401, 0x5401,0x5401,0x5401,0x5401,0x5401,0x5401,0x5401,0x5401,0x5401,0x5401, 0x5204,0x5504,0x5704,0x5904,0x5701,0x5701,0x5701,0x5701,0x5901,0x5901, 0x5B01,0x5B01,0x5904,0x5704,0x5701,0x5701,0x5701,0x5701,0x5604,0x5204, 0x5604,0x5601,0x5601,0x5601,0x5601,0x5404,0x5204,0x5104,0x3204,0x2904, 0x2B04,0x3104,0x3204,0x3204,0x3404,0x3404,0x3604,0x3104,0x3204,0x3404, 0x3604,0x3604,0x3704,0x3704,0x3904,0x3904,0x3A04,0x3A04,0x3B08,0x8008, 0x3710,0x3910,0x4204,0x8004,0x4204,0x8004,0x4204,0x800C,0x3708,0x8004, 0x3204,0x3708,0x8004,0x3204,0x3704,0x3204,0x3704,0x3B04,0x3208,0x8008, 0x4008,0x8004,0x3904,0x4008,0x8004,0x3904,0x4004,0x3904,0x3604,0x4904, 0x4208,0x8008,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3904,0x3904,0x3B04,0x3B04, 0x3604,0x3604,0x3704,0x3704,0x3904,0x3904,0x3B08,0x8028,0x3210,0x3410, 0x3008,0x3008,0x3208,0x3208,0x2B04,0x8004,0x3204,0x8004,0x3708,0x8008, 0x4B10,0x5010,0x3201,0x3201,0x3201,0x3201,0x3201,0x3201,0x3201,0x3201, 0x3201,0x3201,0x3201,0x3201,0x3201,0x3201,0x3201,0x3201,0x3410,0x3008, 0x3008,0x3208,0x3208,0x3B14,0x3B02,0x3901,0x3B01,0x4004,0x3904,0x4714, 0x4702,0x4601,0x4701,0x4904,0x4604,0x3704,0x3704,0x3704,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x3704,0x3604,0x3604,0x3704,0x3704,0x3404, 0x3404,0x3204,0x3204,0x3204,0x3204,0x3204,0x3204,0x3204,0x3204,0x3204, 0x3204,0x3204,0x3204,0x3204,0x3204,0x3204,0x3204,0x3204,0x3404,0x3604, 0x3404,0x3204,0x3404,0x3604,0x3204,0x3704,0x3904,0x3B04,0x3904,0x3704, 0x3904,0x3B04,0x3804,0x3904,0x3904,0x3904,0x3904,0x3904,0x3904,0x3904, 0x3904,0x3904,0x2904,0x2904,0x2904,0x2908,0x8008,0x490A,0x4702,0x4602, 0x4402,0x4204,0x8004,0x3304,0x8004,0x3404,0x8004,0x3204,0x8004,0x3104, 0x8004,0x2904,0x800C,0x2A01,0x2A01,0x2A01,0x2A01,0x2A01,0x2A01,0x2A01, 0x2A01,0x2B04,0x8004,0x2704,0x8004,0x2908,0x3901,0x3901,0x3901,0x3901, 0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3901,0x3801,0x3801, 0x3801,0x3801,0x3701,0x3701,0x3701,0x3701,0x3401,0x3401,0x3401,0x3401, 0x3204,0x8004,0x3404,0x8004,0x3604,0x8004,0x3304,0x8004,0x3404,0x8004, 0x3204,0x8004,0x3104,0x8004,0x2904,0x8004,0x2B04,0x8004,0x3704,0x8004, 0x3904,0x8004,0x2904,0x8004,0x4604,0x4604,0x4704,0x4704,0x4904,0x4904, 0x4604,0x4604,0x4404,0x4404,0x4604,0x4604,0x4704,0x4704,0x4404,0x4404, 0x4604,0x4604,0x4704,0x4704,0x4904,0x4904,0x4604,0x4604,0x4404,0x4404, 0x4604,0x4604,0x4704,0x4704,0x4404,0x4404,0x4608,0x8008,0x5601,0x5601, 0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601, 0x5601,0x5601,0x5601,0x5601,0x5408,0x8008,0x5401,0x5401,0x5401,0x5401, 0x5401,0x5401,0x5401,0x5401,0x5401,0x5401,0x5401,0x5401,0x5401,0x5401, 0x5401,0x5401,0x5204,0x5604,0x5704,0x5904,0x5701,0x5701,0x5701,0x5701, 0x5901,0x5901,0x5B01,0x5B01,0x5904,0x5704,0x5701,0x5701,0x5701,0x5701, 0x5604,0x5204,0x5604,0x5601,0x5601,0x5601,0x5601,0x5404,0x5204,0x5104, 0x5204,0x4604,0x4704,0x4704,0x4904,0x4904,0x4604,0x4604,0x4404,0x4404, 0x4604,0x4604,0x4704,0x4704,0x4404,0x4404,0x4604,0x4604,0x4704,0x4704, 0x4904,0x4904,0x4604,0x4604,0x4404,0x4404,0x4604,0x4604,0x4704,0x4704, 0x4404,0x4404,0x4608,0x8008,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601, 0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601,0x5601, 0x5408,0x8008,0x5401,0x5401,0x5401,0x5401,0x5401,0x5401,0x5401,0x5401, 0x5401,0x5401,0x5401,0x5401,0x5401,0x5401,0x5401,0x5401,0x5204,0x5504, 0x5704,0x5904,0x5701,0x5701,0x5701,0x5701,0x5901,0x5901,0x5B01,0x5B01, 0x5904,0x5704,0x5701,0x5701,0x5701,0x5701,0x5604,0x5204,0x5604,0x5601, 0x5601,0x5601,0x5601,0x5404,0x5204,0x5104,0x3204,0x2904,0x2B04,0x3104, 0x3204,0x3204,0x3404,0x3404,0x3604,0x3104,0x3204,0x3404,0x3604,0x3604, 0x3704,0x3704,0x3904,0x3904,0x3A04,0x3A04,0x3B08,0x8008,0x3710,0x3910, 0x4204,0x8004,0x4204,0x8004,0x4204,0x800C,0x3208,0x8004,0x2904,0x3208, 0x8004,0x2904,0x3204,0x2904,0x3204,0x3604,0x4908,0x8008,0x3908,0x8004, 0x3604,0x3908,0x8004,0x3604,0x3904,0x3604,0x3304,0x3604,0x2B08,0x8008, 0x4404,0x4404,0x4504,0x4504,0x4704,0x4704,0x4404,0x4404,0x4204,0x4204, 0x4404,0x4404,0x4504,0x4504,0x4204,0x4204,0x4404,0x4404,0x4504,0x4504, 0x4704,0x4704,0x4404,0x4404,0x4204,0x4204,0x4404,0x4404,0x4504,0x4504, 0x4204,0x4204,0x4404,0x4404,0x4504,0x4504,0x4704,0x4704,0x4404,0x4404, 0x4204,0x4204,0x4404,0x4404,0x4504,0x4504,0x4204,0x4204,0x4004,0x4004, 0x4204,0x4204,0x4404,0x4404,0x4004,0x4004,0x4004,0x4004,0x4204,0x4204, 0x4304,0x4304,0x4004,0x4004,0x3A04,0x3A04,0x3904,0x3904,0x3A04,0x3A04, 0x4904,0x4904,0x4A04,0x4A04,0x4904,0x4904,0x4A04,0x4A04,0x4904,0x4704, 0x4608,0x8004,0x2201,0x2201,0x2201,0x2201,0x2401,0x2401,0x2401,0x2401, 0x2601,0x2601,0x2601,0x2601,0x2701,0x2701,0x2701,0x2701,0x2901,0x2901, 0x2901,0x2901,0x3001,0x3001,0x3001,0x3001,0x2A04,0x8004,0x2601,0x2601, 0x2601,0x2601,0x2701,0x2701,0x2701,0x2701,0x2901,0x2901,0x2901,0x2901, 0x2A01,0x2A01,0x2A01,0x2A01,0x2101,0x2101,0x2101,0x2101,0x3401,0x3401, 0x3401,0x3401,0x3204,0x8004,0x4204,0x4404,0x4504,0x4704,0x4904,0x4A08, 0x4B08,0x5008,0x5108,0x5204,0x5204,0x5201,0x5201,0x5201,0x5201,0x5404, 0x5004,0x5004,0x5001,0x5001,0x5001,0x5001,0x5204,0x4B04,0x4B04,0x4B01, 0x4B01,0x4B01,0x4B01,0x5204,0x5201,0x5201,0x5201,0x5201,0x5004,0x4B04, 0x4904,0x4708,0x8004,0x3204,0x3708,0x8004,0x3204,0x3704,0x3204,0x3704, 0x3B04,0x4208,0x8008,0x4008,0x8004,0x3904,0x4008,0x8004,0x3904,0x4004, 0x3904,0x3604,0x3904,0x3208,0x8008,0x3704,0x3704,0x3704,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3904, 0x3904,0x3B04,0x3B04,0x3704,0x3704,0x3904,0x3904,0x3B04,0x3B04,0x4008, 0x8008,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01, 0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x5010,0x4908,0x4908, 0x4708,0x4708,0x4408,0x4408,0x4008,0x3908,0x4204,0x8004,0x4604,0x8004, 0x4704,0x800C,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01, 0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x5010,0x4B01, 0x4B01,0x4B01,0x4B01,0x4904,0x4904,0x4904,0x4901,0x4901,0x4901,0x4901, 0x4704,0x4704,0x4704,0x4408,0x4404,0x4404,0x4008,0x4004,0x4004,0x3B14, 0x3B01,0x3B01,0x3901,0x3B01,0x4001,0x4001,0x4001,0x4001,0x3904,0x4714, 0x4701,0x4701,0x4601,0x4701,0x4901,0x4901,0x4901,0x4901,0x4604,0x4B10, 0x5010,0x4B08,0x5210,0x5708,0x5610,0x5710,0x5610,0x5710,0x5608,0x5708, 0x5608,0x5708,0x5604,0x4204,0x4204,0x4204,0x4208,0x8008,0x4201,0x4201, 0x4201,0x4201,0x4201,0x4201,0x4201,0x4201,0x4201,0x4201,0x4001,0x4001, 0x3B01,0x3B01,0x3901,0x3901,0x3704,0x8004,0x4404,0x8004,0x4004,0x8004, 0x3904,0x8004,0x4204,0x800C,0x4B0A,0x4902,0x4702,0x4602,0x5404,0x8004, 0x5004,0x8004,0x3208,0x4201,0x4201,0x4201,0x4201,0x4201,0x4201,0x4201, 0x4201,0x4201,0x4201,0x4201,0x4201,0x4101,0x4101,0x4101,0x4101,0x4001, 0x4001,0x4001,0x4001,0x3901,0x3901,0x3901,0x3901,0x3704,0x8004,0x3904, 0x8004,0x3B04,0x8004,0x3804,0x8004,0x3904,0x8004,0x3704,0x8004,0x3604, 0x8004,0x3204,0x8004,0x3404,0x8004,0x3004,0x8004,0x3204,0x8004,0x3204, 0x8004,0x2708,0x8018,0x3208,0x8018,0x2708,0x8018,0x3208,0x8018,0x3B08, 0x8008,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01, 0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4908,0x8008,0x4901, 0x4901,0x4901,0x4901,0x4901,0x4901,0x4901,0x4901,0x4901,0x4901,0x4901, 0x4901,0x4901,0x4901,0x4901,0x4901,0x4704,0x4B04,0x5004,0x5204,0x5001, 0x5001,0x5001,0x5001,0x5201,0x5201,0x5401,0x5401,0x5204,0x5004,0x5001, 0x5001,0x5001,0x5001,0x4B04,0x4704,0x4B04,0x4B01,0x4B01,0x4B01,0x4B01, 0x4904,0x4704,0x4604,0x4704,0x3B04,0x4004,0x4004,0x4204,0x4204,0x3B04, 0x3B04,0x3904,0x3904,0x3B04,0x3B04,0x4004,0x4004,0x3904,0x3904,0x3B04, 0x4B04,0x5004,0x5004,0x5204,0x5204,0x4B04,0x4B04,0x4904,0x4904,0x4B04, 0x4B04,0x5004,0x5004,0x4904,0x4904,0x8004,0x3704,0x3B04,0x3904,0x3804, 0x3404,0x3604,0x3804,0x3904,0x4004,0x3904,0x3704,0x3604,0x3204,0x3404, 0x3604,0x3704,0x3704,0x3904,0x3B04,0x4004,0x4004,0x4004,0x4004,0x4204, 0x4204,0x4204,0x4204,0x3204,0x3204,0x3204,0x3204,0x3704,0x3204,0x3404, 0x3604,0x3704,0x3704,0x3904,0x3904,0x3B04,0x3604,0x3704,0x3904,0x3B04, 0x3B04,0x4004,0x4004,0x4204,0x4204,0x4304,0x4304,0x4408,0x8008,0x3001, 0x3001,0x3001,0x3001,0x3001,0x3001,0x3001,0x3001,0x3001,0x3001,0x3001, 0x3001,0x3001,0x3001,0x3001,0x3001,0x3210,0x2708,0x8018,0x3001,0x3001, 0x3001,0x3001,0x3001,0x3001,0x3001,0x3001,0x3001,0x3001,0x3001,0x3001, 0x3001,0x3001,0x3001,0x3001,0x3210,0x2708,0x8018,0x3008,0x8008,0x3208, 0x8008,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704, 0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704, 0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704, 0x2704,0x2704,0x2704,0x2704,0x2B04,0x3204,0x3704,0x3B04,0x3704,0x4204, 0x3B04,0x3708,0x2706,0x2702,0x2708,0x8008,0x3208,0x8004,0x2904,0x3208, 0x8004,0x2904,0x3204,0x2904,0x3204,0x3604,0x4908,0x8008,0x3908,0x8004, 0x3604,0x3908,0x8004,0x3604,0x3904,0x3604,0x3304,0x3604,0x2B08,0x8008, 0x4404,0x4404,0x4504,0x4504,0x4704,0x4704,0x4404,0x4404,0x4204,0x4204, 0x4404,0x4404,0x4504,0x4504,0x4204,0x4204,0x4404,0x4404,0x4504,0x4504, 0x4704,0x4704,0x4404,0x4404,0x4204,0x4204,0x4404,0x4404,0x4504,0x4504, 0x4204,0x4204,0x4404,0x4404,0x4504,0x4504,0x4704,0x4704,0x4404,0x4404, 0x4204,0x4204,0x4404,0x4404,0x4504,0x4504,0x4204,0x4204,0x4004,0x4004, 0x4204,0x4204,0x4404,0x4404,0x4004,0x4004,0x4004,0x4004,0x4204,0x4204, 0x4304,0x4304,0x4004,0x4004,0x3A04,0x3A04,0x3904,0x3904,0x3A04,0x3A04, 0x4904,0x4904,0x4A04,0x4A04,0x4904,0x4904,0x4A04,0x4A04,0x4904,0x4704, 0x4608,0x8004,0x2201,0x2201,0x2201,0x2201,0x2401,0x2401,0x2401,0x2401, 0x2601,0x2601,0x2601,0x2601,0x2701,0x2701,0x2701,0x2701,0x2901,0x2901, 0x2901,0x2901,0x3001,0x3001,0x3001,0x3001,0x2A04,0x8004,0x2601,0x2601, 0x2601,0x2601,0x2701,0x2701,0x2701,0x2701,0x2901,0x2901,0x2901,0x2901, 0x2A01,0x2A01,0x2A01,0x2A01,0x2101,0x2101,0x2101,0x2101,0x3401,0x3401, 0x3401,0x3401,0x3204,0x8004,0x4204,0x4404,0x4504,0x4704,0x4904,0x4A08, 0x4B08,0x5008,0x5108,0x5204,0x5204,0x5201,0x5201,0x5201,0x5201,0x5404, 0x5004,0x5004,0x5001,0x5001,0x5001,0x5001,0x5204,0x4B04,0x4B04,0x4B01, 0x4B01,0x4B01,0x4B01,0x5204,0x5201,0x5201,0x5201,0x5201,0x5004,0x4B04, 0x4904,0x4708,0x8004,0x3204,0x3708,0x8004,0x3204,0x3704,0x3204,0x3704, 0x3B04,0x4208,0x8008,0x4008,0x8004,0x3904,0x4008,0x8004,0x3904,0x4004, 0x3904,0x3604,0x3904,0x3208,0x8008,0x3704,0x3704,0x3704,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704, 0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3704,0x3904, 0x3904,0x3B04,0x3B04,0x3704,0x3704,0x3904,0x3904,0x3B04,0x3B04,0x4008, 0x8008,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01, 0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x5010,0x4908,0x4908, 0x4708,0x4708,0x4408,0x4408,0x4008,0x3908,0x4204,0x8004,0x4604,0x8004, 0x4704,0x800C,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01, 0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x5010,0x4B01, 0x4B01,0x4B01,0x4B01,0x4904,0x4904,0x4904,0x4901,0x4901,0x4901,0x4901, 0x4704,0x4704,0x4704,0x4408,0x4404,0x4404,0x4008,0x4004,0x4004,0x3B14, 0x3B01,0x3B01,0x3901,0x3B01,0x4001,0x4001,0x4001,0x4001,0x3904,0x4714, 0x4701,0x4701,0x4601,0x4701,0x4901,0x4901,0x4901,0x4901,0x4604,0x4B10, 0x5010,0x4B08,0x5210,0x5708,0x5610,0x5710,0x5610,0x5710,0x5608,0x5708, 0x5608,0x5708,0x5604,0x4204,0x4204,0x4204,0x4208,0x8008,0x4201,0x4201, 0x4201,0x4201,0x4201,0x4201,0x4201,0x4201,0x4201,0x4201,0x4001,0x4001, 0x3B01,0x3B01,0x3901,0x3901,0x3704,0x8004,0x4404,0x8004,0x4004,0x8004, 0x3904,0x8004,0x4204,0x800C,0x4B0A,0x4902,0x4702,0x4602,0x5404,0x8004, 0x5004,0x8004,0x3208,0x4201,0x4201,0x4201,0x4201,0x4201,0x4201,0x4201, 0x4201,0x4201,0x4201,0x4201,0x4201,0x4101,0x4101,0x4101,0x4101,0x4001, 0x4001,0x4001,0x4001,0x3901,0x3901,0x3901,0x3901,0x3704,0x8004,0x3904, 0x8004,0x3B04,0x8004,0x3804,0x8004,0x3904,0x8004,0x3704,0x8004,0x3604, 0x8004,0x3204,0x8004,0x3404,0x8004,0x3004,0x8004,0x3204,0x8004,0x3204, 0x8004,0x2708,0x8018,0x3208,0x8018,0x2708,0x8018,0x3208,0x8018,0x3B08, 0x8008,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01, 0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4B01,0x4908,0x8008,0x4901, 0x4901,0x4901,0x4901,0x4901,0x4901,0x4901,0x4901,0x4901,0x4901,0x4901, 0x4901,0x4901,0x4901,0x4901,0x4901,0x4704,0x4B04,0x5004,0x5204,0x5001, 0x5001,0x5001,0x5001,0x5201,0x5201,0x5401,0x5401,0x5204,0x5004,0x5001, 0x5001,0x5001,0x5001,0x4B04,0x4704,0x4B04,0x4B01,0x4B01,0x4B01,0x4B01, 0x4904,0x4704,0x4604,0x4704,0x3B04,0x4004,0x4004,0x4204,0x4204,0x3B04, 0x3B04,0x3904,0x3904,0x3B04,0x3B04,0x4004,0x4004,0x3904,0x3904,0x3B04, 0x4B04,0x5004,0x5004,0x5204,0x5204,0x4B04,0x4B04,0x4904,0x4904,0x4B04, 0x4B04,0x5004,0x5004,0x4904,0x4904,0x8004,0x3704,0x3B04,0x3904,0x3804, 0x3404,0x3604,0x3804,0x3904,0x4004,0x3904,0x3704,0x3604,0x3204,0x3404, 0x3604,0x3704,0x3704,0x3904,0x3B04,0x4004,0x4004,0x4004,0x4004,0x4204, 0x4204,0x4204,0x4204,0x3204,0x3204,0x3204,0x3204,0x3704,0x3204,0x3404, 0x3604,0x3704,0x3704,0x3904,0x3904,0x3B04,0x3604,0x3704,0x3904,0x3B04, 0x3B04,0x4004,0x4004,0x4204,0x4204,0x4304,0x4304,0x4408,0x8008,0x3001, 0x3001,0x3001,0x3001,0x3001,0x3001,0x3001,0x3001,0x3001,0x3001,0x3001, 0x3001,0x3001,0x3001,0x3001,0x3001,0x3210,0x2708,0x8018,0x3001,0x3001, 0x3001,0x3001,0x3001,0x3001,0x3001,0x3001,0x3001,0x3001,0x3001,0x3001, 0x3001,0x3001,0x3001,0x3001,0x3210,0x2708,0x8018,0x3008,0x8008,0x3208, 0x8008,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704, 0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704, 0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704,0x2704, 0x2704,0x2704,0x2704,0x2704,0x2B04,0x3204,0x3704,0x3B04,0x3704,0x4204, 0x3B04,0x3708,0x2706,0x2702,0x2708,0x8008, 0x0000 }; #if defined(__C64__) || defined(__CBM510__) static unsigned long FreqTab [12] = { #ifndef NTSC /* PAL */ 0x008B38, 0x009381, 0x009C45, 0x00A590, 0x00AF68, 0x00B9D6, 0x00C4E4, 0x00D099, 0x00DCFF, 0x00EA24, 0x00F810, 0x0106D1, #else /* NTSC */ 0x00861E, 0x008E19, 0x00968B, 0x009F7F, 0x00A8FA, 0x00B307, 0x00BDAD, 0x00C8F4, 0x00D4E6, 0x00E18F, 0x00EEF9, 0x00FD2F, #endif }; #elif defined(__C128__) static unsigned long FreqTab [12] = { 0x00892B, 0x009153, 0x0099F7, 0x00A31E, 0x00ACD2, 0x00B718, 0x00C1FD, 0x00CD85, 0x00D9BD, 0x00E6B0, 0x00F467, 0x0102F0, }; #elif defined(__CBM610__) static unsigned long FreqTab [12] = { 0x004495, 0x0048AA, 0x004CFB, 0x00518F, 0x005669, 0x005B8C, 0x0060FE, 0x0066C3, 0x006CDE, 0x007358, 0x007A34, 0x008178, }; #endif typedef struct { unsigned char DoneMask; /* Set this if we're done */ unsigned char Trigger; /* Trigger value */ unsigned char Ticks; /* Ticks for this tone */ unsigned Freq; /* Actual frequency value */ unsigned* Data; /* Pointer to data */ struct __sid_voice* Voice; /* Pointer to sid registers */ } VoiceCtrl; /* Control structs for all three voices */ static VoiceCtrl V1 = { 0x01, 0x11, 0, 0, Voice1, &SID.v1 }; static VoiceCtrl V2 = { 0x02, 0x41, 0, 0, Voice2, &SID.v2 }; static VoiceCtrl V3 = { 0x04, 0x11, 0, 0, Voice3, &SID.v3 }; /* Pointers to the structs for easy reference */ static VoiceCtrl* V [3] = { &V1, &V2, &V3 }; /* Screen dimensions */ static unsigned char XSize, YSize; /* Variable that contains the time of the next clock tick to play a note */ static unsigned char NextClock; /* Start- and runtime */ static clock_t StartTime; /* Number of ticks for each tone */ #define TICKS_PER_TONE 4 /* Done flag. Contains one bit for each voice. Will contain 0x07 if all * voices have finished playing. */ static unsigned char Done; /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void MakeTeeLine (unsigned char Y) /* Make a divider line */ { cputcxy (0, Y, CH_LTEE); chline (XSize - 2); cputc (CH_RTEE); } static void MakeNiceScreen (void) /* Make a nice screen */ { typedef struct { unsigned char Y; char* Msg; } TextDesc; static TextDesc Text [] = { { 2, "Wolfgang Amadeus Mozart" }, { 4, "\"Eine kleine Nachtmusik\"" }, { 5, "(KV 525)" }, { 9, "Ported to the SID in 1987 by" }, { 11, "Joachim von Bassewitz" }, { 12, "(joachim@von-bassewitz.de)" }, { 13, "and" }, { 14, "Ullrich von Bassewitz" }, { 15, "(ullrich@von-bassewitz.de)" }, { 18, "C Implementation by" }, { 19, "Ullrich von Bassewitz" }, { 23, "Press any key to quit..." }, }; register const TextDesc* T; unsigned char I; unsigned char X; /* Clear the screen hide the cursor, set colors */ #ifdef __CBM610__ textcolor (COLOR_WHITE); #else textcolor (COLOR_GRAY3); #endif bordercolor (COLOR_BLACK); bgcolor (COLOR_BLACK); clrscr (); cursor (0); /* Top line */ cputcxy (0, 0, CH_ULCORNER); chline (XSize - 2); cputc (CH_URCORNER); /* Left line */ cvlinexy (0, 1, 23); /* Bottom line */ cputc (CH_LLCORNER); chline (XSize - 2); cputc (CH_LRCORNER); /* Right line */ cvlinexy (XSize - 1, 1, 23); /* Several divider lines */ MakeTeeLine (7); MakeTeeLine (22); /* Write something into the frame */ for (I = 0, T = Text; I < sizeof (Text) / sizeof (Text [0]); ++I) { X = (XSize - strlen (T->Msg)) / 2; cputsxy (X, T->Y, T->Msg); ++T; } } static void TimeSync (void) /* Sync the time for the next tone */ { static unsigned char Clock; do { Clock = clock (); } while (Clock != NextClock); NextClock = Clock + TICKS_PER_TONE; } static void DisplayTime (void) /* Display the running time */ { clock_t Time = (clock () - StartTime) / CLOCKS_PER_SEC; unsigned Sec = Time % 60; unsigned Min = Time / 60; gotoxy (1, 0); cprintf ("%02d:%02d", Min, Sec); } /* On the 510/610, the SID is in another bank (the system bank), so we cannot * just write to the memory space. */ #if defined(__CBM510__) || defined(__CBM610__) # define outb(addr,val) pokebsys ((unsigned)(addr), val) # define outw(addr,val) pokewsys ((unsigned)(addr), val) #else # define outb(addr,val) (*(addr)) = (val) # define outw(addr,val) (*(addr)) = (val) #endif int main (void) { unsigned char I; unsigned char Tone; unsigned char Octave; unsigned Val; struct __sid_voice* Voice; register VoiceCtrl* VC; /* Initialize the debugger */ DbgInit (0); /* Get the screen dimensions */ screensize (&XSize, &YSize); /* Make a nice screen */ MakeNiceScreen (); /* Initialize the SID */ outw (&SID.v1.pw, 0x0800); outb (&SID.v1.ad, 0x33); outb (&SID.v1.sr, 0xF0); outw (&SID.v2.pw, 0x0800); outb (&SID.v2.ad, 0x77); outb (&SID.v2.sr, 0x74); outw (&SID.v3.pw, 0x0800); outb (&SID.v3.ad, 0x77); outb (&SID.v3.sr, 0xD2); outw (&SID.flt_freq, 0xF0F0); outb (&SID.flt_ctrl, 0xF2); outb (&SID.amp, 0x5F); /* Sync the clock */ NextClock = StartTime = clock (); NextClock += TICKS_PER_TONE; /* Play each voice until all three are done */ while (Done != 0x07) { /* Display the time in the lower left corner */ DisplayTime (); /* Wait for the next run */ TimeSync (); /* Check for a key */ if (kbhit ()) { if (cgetc () == 'd') { /* Start the debugger */ BREAK (); } else { /* Stop playing music */ break; } } /* Play all three voices */ for (I = 0; I < 3; ++I) { /* Get a pointer to this voice */ VC = V [I]; Voice = VC->Voice; /* Is this voice done? */ if (Done & VC->DoneMask) { /* Voice already done */ continue; } /* Do we have any more ticks to play? */ if (VC->Ticks == 0) { /* We need new data */ if ((Val = *VC->Data) == 0) { /* End of data. Mark the voice as done */ Done |= VC->DoneMask; continue; } ++VC->Data; /* Get the ticks from the data */ VC->Ticks = (Val & 0x7F) - 1; /* Check if this is a tone or a pause */ if (Val & 0x8000) { /* This is a pause. Remember it and shut off the SID */ outb (&Voice->ctrl, VC->Trigger & 0xFE); } else { /* This is a tone. Extract the attributes. */ Tone = (Val >> 8) & 0x0F; Octave = ((Val >> 12) & 0x07) ^ 0x07; /* Calculate the frequency */ VC->Freq = FreqTab [Tone] >> Octave; /* Set the frequency */ outw (&Voice->freq, VC->Freq); /* Start the tone */ outb (&Voice->ctrl, VC->Trigger); } } else { /* Decrement the ticks. If this is the last tick of a tone, * reset bit 0 of the trigger value and write it back to the * SID to start the release phase. */ if (--(VC->Ticks) == 0) { outb (&Voice->ctrl, VC->Trigger & 0xFE); } } } } /* Reset the SID */ outb (&SID.v1.ctrl, 0x00); outb (&SID.v2.ctrl, 0x00); outb (&SID.v3.ctrl, 0x00); /* Clear the screen */ clrscr (); /* If we have a character, remove it from the buffer */ if (kbhit ()) { cgetc (); } /* Done */ return 0; }
723
./cc65/samples/ascii.c
/* ascii.c ** ** Shows the ASCII (or ATASCII, PETSCII) codes of typed characters. ** ** 2003-03-09, Greg King <gngking@erols.com> */ /* Define USE_STDIO, when you want to use the stdio functions. ** Do not define it, when you want to use the conio functions. ** NOTE: stdin on some targets is line-bufferred. You might need to type ** a key, then tap the return(enter)-key, in order to see each code. */ /* #define USE_STDIO */ #include <conio.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define QUIT 'Q' /* r -- row. t -- table-column. */ static unsigned char height, width, r, t; static int c; #ifndef USE_STDIO # define PRINT cprintf # define PUT(c) cputc((char)(c)) /* conio doesn't echo typed characters. ** So, this function does it. */ static int GET(void) { PUT(c = (int)cgetc()); return c; } #else # define PRINT printf # define GET getchar #endif int main(void) { # ifndef USE_STDIO /* conio doesn't scroll! Avoid trouble by starting at the top ** of the screen, and never going "below" the bottom of the screen. */ clrscr(); r = 7; /* allow for prompt */ # endif /* This prompt fits on the VIC-20's narrow screen. */ PRINT("Type characters to see\r\ntheir hexadecimal code\r\nnumbers:\r\n\n"); screensize(&width, &height); /* get the screen's dimensions */ width /= 6; /* get number of codes on a line */ cursor(true); t = 0; while ((c = GET()) != EOF) { # ifndef USE_STDIO if (r == height) { clrscr(); t = 0; PUT(c); /* echo char. again because screen was erased */ r = 1; } if (c == '\n') ++r; # endif PRINT("=$%02x ", c); if (c == QUIT) break; if (++t == width) { PRINT("\r\n"); ++r; t = 0; } } PRINT("\r\n"); return EXIT_SUCCESS; }
724
./cc65/samples/enumdevdir.c
/* * Enumerate devices, directories and files. * * 2012-10-15, Oliver Schmidt (ol.sc@web.de) * */ #include <stdio.h> #include <conio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <device.h> #include <dirent.h> void printdir (char *newdir) { char olddir[FILENAME_MAX]; char curdir[FILENAME_MAX]; DIR *dir; struct dirent *ent; char *subdirs = NULL; unsigned dirnum = 0; unsigned num; getcwd (olddir, sizeof (olddir)); if (chdir (newdir)) { /* If chdir() fails we just print the * directory name - as done for files. */ printf (" Dir %s\n", newdir); return; } /* We call getcwd() in order to print the * absolute pathname for a subdirectory. */ getcwd (curdir, sizeof (curdir)); printf (" Dir %s:\n", curdir); /* Calling opendir() always with "." avoids * fiddling around with pathname separators. */ dir = opendir ("."); while (ent = readdir (dir)) { if (_DE_ISREG (ent->d_type)) { printf (" File %s\n", ent->d_name); continue; } /* We defer handling of subdirectories until we're done with the * current one as several targets don't support other disk i/o * while reading a directory (see cc65 readdir() doc for more). */ if (_DE_ISDIR (ent->d_type)) { subdirs = realloc (subdirs, FILENAME_MAX * (dirnum + 1)); strcpy (subdirs + FILENAME_MAX * dirnum++, ent->d_name); } } closedir (dir); for (num = 0; num < dirnum; ++num) { printdir (subdirs + FILENAME_MAX * num); } free (subdirs); chdir (olddir); } void main (void) { unsigned char device; char devicedir[FILENAME_MAX]; /* Calling getfirstdevice()/getnextdevice() does _not_ turn on the motor * of a drive-type device and does _not_ check for a disk in the drive. */ device = getfirstdevice (); while (device != INVALID_DEVICE) { printf ("Device %d:\n", device); /* Calling getdevicedir() _does_ check for a (formatted) disk in a * floppy-disk-type device and returns NULL if that check fails. */ if (getdevicedir (device, devicedir, sizeof (devicedir))) { printdir (devicedir); } else { printf (" N/A\n"); } device = getnextdevice (device); } cgetc (); }
725
./cc65/samples/sieve.c
/* * Calculate all primes up to a specific number. */ #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <time.h> #include <conio.h> /* Workaround missing clock stuff */ #ifdef __APPLE2__ # define clock() 0 # define CLOCKS_PER_SEC 1 #endif /*****************************************************************************/ /* Data */ /*****************************************************************************/ #define COUNT 16384 /* Up to what number? */ #define SQRT_COUNT 128 /* Sqrt of COUNT */ static unsigned char Sieve[COUNT]; /*****************************************************************************/ /* Code */ /*****************************************************************************/ #pragma static-locals(1); static char ReadUpperKey (void) /* Read a key from console, convert to upper case and return */ { return toupper (cgetc ()); } int main (void) { /* Clock variable */ clock_t Ticks; unsigned Sec; unsigned Milli; /* This is an example where register variables make sense */ register unsigned char* S; register unsigned I; register unsigned J; /* Output a header */ printf ("Sieve benchmark - calculating primes\n"); printf ("between 2 and %u\n", COUNT); printf ("Please wait patiently ...\n"); /* Read the clock */ Ticks = clock(); /* Execute the sieve */ I = 2; while (I < SQRT_COUNT) { if (Sieve[I] == 0) { /* Prime number - mark multiples */ J = I*2; S = &Sieve[J]; while (J < COUNT) { *S = 1; S += I; J += I; } } ++I; } /* Calculate the time used */ Ticks = clock() - Ticks; Sec = (unsigned) (Ticks / CLOCKS_PER_SEC); Milli = ((Ticks % CLOCKS_PER_SEC) * 1000) / CLOCKS_PER_SEC; /* Print the time used */ printf ("Time used: %u.%03u seconds\n", Sec, Milli); printf ("Q to quit, any other key for list\n"); /* Wait for a key and print the list if not 'Q' */ if (ReadUpperKey () != 'Q') { /* Print the result */ J = 0; for (I = 2; I < COUNT; ++I) { if (Sieve[I] == 0) { printf ("%4d\n", I); if (++J == 23) { printf ("Q to quit, any other key continues\n"); if (ReadUpperKey () == 'Q') { break; } J = 0; } } if (kbhit() && ReadUpperKey == 'Q') { break; } } } return EXIT_SUCCESS; }
726
./cc65/samples/overlaydemo.c
/* * Minimalistic overlay demo program. * * 2009-10-02, Oliver Schmidt (ol.sc@web.de) * */ #include <stdio.h> #include <conio.h> #ifndef __CBM__ #include <fcntl.h> #include <unistd.h> #else #include <device.h> #endif extern void _OVERLAY1_LOAD__[], _OVERLAY1_SIZE__[]; extern void _OVERLAY2_LOAD__[], _OVERLAY2_SIZE__[]; extern void _OVERLAY3_LOAD__[], _OVERLAY3_SIZE__[]; /* Functions resident in an overlay can call back functions resident in the * main program at any time without any precautions. The function log() is * an example for such a function resident in the main program. */ void log (char *msg) { printf ("Log: %s\n", msg); } /* In a real-world overlay program one would probably not use a #pragma but * rather place all the code of certain source files into the overlay by * compiling them with --code-name OVERLAY1. */ #pragma code-name (push, "OVERLAY1"); void foo (void) { /* Functions resident in an overlay can access all program variables and * constants at any time without any precautions because those are never * placed in overlays. The string constant below is an example for such * a constant resident in the main program. */ log ("Calling main from overlay 1"); } #pragma code-name (pop); #pragma code-name (push, "OVERLAY2"); void bar (void) { log ("Calling main from overlay 2"); } #pragma code-name (pop); #pragma code-name (push, "OVERLAY3"); void foobar (void) { log ("Calling main from overlay 3"); } #pragma code-name(pop); unsigned char loadfile (char *name, void *addr, void *size) { #ifndef __CBM__ int file = open (name, O_RDONLY); if (file == -1) { log ("Opening overlay file failed"); return 0; } read (file, addr, (unsigned) size); close (file); #else /* Avoid compiler warnings about unused parameters. */ (void) addr; (void) size; if (cbm_load (name, getcurrentdevice (), NULL) == 0) { log ("Loading overlay file failed"); return 0; } #endif return 1; } void main (void) { log ("Calling overlay 1 from main"); /* The symbols _OVERLAY1_LOAD__ and _OVERLAY1_SIZE__ were generated by the * linker. They contain the overlay area address and size specific to a * certain program. */ if (loadfile ("ovrldemo.1", _OVERLAY1_LOAD__, _OVERLAY1_SIZE__)) { /* The linker makes sure that the call to foo() ends up at the right mem * addr. However it's up to user to make sure that the - right - overlay * is actually loaded before making the the call. */ foo (); } log ("Calling overlay 2 from main"); /* Replacing one overlay with another one can only happen from the main * program. This implies that an overlay can never load another overlay. */ if (loadfile ("ovrldemo.2", _OVERLAY2_LOAD__, _OVERLAY2_SIZE__)) { bar (); } log ("Calling overlay 3 from main"); if (loadfile ("ovrldemo.3", _OVERLAY3_LOAD__, _OVERLAY3_SIZE__)) { foobar (); } cgetc (); }
727
./cc65/samples/fire.c
/***************************************************************************** * fire test program for cc65. * * * * (w)2002 by groepaz/hitmen * * * * Cleanup and porting by Ullrich von Bassewitz. * * 2004-06-08, Greg King * * * *****************************************************************************/ /* sync page-flipping to vertical blank */ /* #define DOVSYNC */ #include <stdlib.h> #include <string.h> /* for memset */ #include <time.h> #include <conio.h> #if defined(__C64__) # define BUFFER 0x0400 # define SCREEN1 0xE000 # define SCREEN2 0xE400 # define CHARSET 0xE800 # define COLORRAM 0xD800 # define outb(addr,val) (*(addr) = (val)) # define inb(addr) (*(addr)) #elif defined(__C128__) # define BUFFER 0x0400 # define SCREEN1 0xE000 # define SCREEN2 0xE400 # define CHARSET 0xE800 # define COLORRAM 0xD800 # define outb(addr,val) (*(addr) = (val)) # define inb(addr) (*(addr)) #elif defined(__CBM510__) # define BUFFER 0xF800 # define SCREEN1 0xF000 # define SCREEN2 0xF400 # define CHARSET 0xE000 # define COLORRAM 0xD400 # define outb(addr,val) pokebsys ((unsigned)(addr), val) # define inb(addr) peekbsys ((unsigned)(addr)) #endif /* Values for the VIC address register to switch between the two pages */ #define PAGE1 ((SCREEN1 >> 6) & 0xF0) | ((CHARSET >> 10) & 0x0E) #define PAGE2 ((SCREEN2 >> 6) & 0xF0) | ((CHARSET >> 10) & 0x0E) /* Use static local variables for speed */ #pragma static-locals (1); #ifdef DOVSYNC # define waitvsync() while ((signed char)VIC.ctrl1 >= 0) #else # define waitvsync() #endif static void makechar (void) { static const unsigned char bittab[8] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 }; register char *font; register unsigned char i, ii, b, bc; unsigned char c; gotoxy (0, 1); for (font = (char*)CHARSET; font != (char*)(CHARSET+(1*8)); ++font) { *font = 0x00; } for (font = (char*)(CHARSET+(64*8)); font != (char*)(CHARSET+(256*8)); ++font) { *font = 0xff; } for (c = 0; c < 0x40; ++c) { bc = 0; for (i = 0; i < 8; i++){ b = 0; for (ii = 0; ii < 8; ii++) { bc += c; if (bc > 0x3f) { bc = bc - 0x40; b += bittab[(ii + (i & 1)) & 0x7]; } } ((unsigned char*)CHARSET + (1 * 8)) [(c * 8) + i] = b; } if ((c & 0x07) == 0) { cputc ('.'); } } } static void fire (unsigned screenbase) { register char* screen; register char* buffer; register char c; screen = (char*) screenbase; buffer = (char*) BUFFER; while (buffer != (char*) (BUFFER + (24 * 40))) { c = (buffer[40-1] + buffer[40-1] + buffer[40] + buffer[41]) / 4; if (c > 2) { c -= 3; } *screen = *buffer = c; ++screen; ++buffer; } screen = (char*) (screenbase + (23 * 40)); buffer = (char*) (BUFFER + (23 * 40)); for(; buffer != (char*)(BUFFER+(25*40)); ++screen, ++buffer) { *screen = *buffer = 0x30 + (inb (&SID.noise) >> 4); } } int main (void) { unsigned char border; unsigned char background; unsigned char text; unsigned char v; clock_t t; unsigned long f = 0; unsigned long sec; unsigned sec10; unsigned long fps; unsigned fps10; int i; #if defined(__C64__) unsigned char block; #endif #if defined(__C128__) unsigned char block; unsigned char initflag; unsigned char graphflag; #endif /* Noise on channel 3 for random numbers */ outb (&SID.v3.freq, 0xffff); outb (&SID.v3.ctrl, 0x80); clrscr (); cprintf ("Making charset, mompls"); makechar (); /* Set the border and background colors */ border = bordercolor (COLOR_BLACK); background = bgcolor (COLOR_BLACK); text = textcolor (COLOR_BLACK); clrscr (); for(i = 0; i != 0x400; i++) { *((char *)(i + BUFFER)) = 0; *((char *)(i + SCREEN1)) = 0; *((char *)(i + SCREEN2)) = 0; outb ((char*)(i + COLORRAM), COLOR_YELLOW); } #if defined(__C64__) || defined(__C128__) /* Move the VIC 16K block */ block = inb (&CIA2.pra); outb (&CIA2.pra, (block & 0xFC) | ((SCREEN1 >> 14) ^ 0x03)); #endif #if defined(__C128__) /* Save and change some flags, so that kernal/basic interrupt handler will * not interfere with our routine. */ initflag = *(unsigned char*) 0xA04; *(unsigned char*) 0xA04 &= 0xFE; graphflag = *(unsigned char*) 0xD8; *(unsigned char*) 0xD8 = 0xFF; #endif /* Remember the VIC address register */ v = inb (&VIC.addr); /* Run the demo until a key was hit */ t = clock (); while (!kbhit()) { /* Build page 1, then make it visible */ fire (SCREEN1); waitvsync (); outb (&VIC.addr, PAGE1); /* Build page 2, then make it visible */ fire (SCREEN2); waitvsync (); outb (&VIC.addr, PAGE2); /* Count frames */ f += 2; } t = clock() - t; /* Switch back the VIC screen */ outb (&VIC.addr, v); #if defined(__C64__) || defined(__C128__) /* Move back the VIC 16K block */ outb (&CIA2.pra, block); #endif #if defined(__C128__) /* Restore the flags */ *(unsigned char*) 0xA04 = initflag; *(unsigned char*) 0xD8 = graphflag; #endif /* Fetch the character from the keyboard buffer and discard it */ (void) cgetc(); /* Reset screen colors */ bordercolor (border); bgcolor (background); textcolor (text); clrscr (); /* Calculate stats */ sec = (t * 10) / CLK_TCK; sec10 = sec % 10; sec /= 10; fps = (f * (CLK_TCK * 10)) / t; fps10 = fps % 10; fps /= 10; /* Output stats */ gotoxy (0, 0); cprintf ("time : %lu.%us", sec, sec10); gotoxy (0, 1); cprintf ("frames: %lu", f); gotoxy (0, 2); cprintf ("fps : %lu.%u", fps, fps10); /* Wait for a key, then end */ cputsxy (0, 4, "Press any key when done..."); (void) cgetc (); /* Done */ return EXIT_SUCCESS; }
728
./cc65/samples/gunzip65.c
/* * gunzip65 - a gunzip utility for 6502-based machines. * * Piotr Fusik <fox@scene.pl> * * This should be considered as a test of my zlib-compatible library * rather than a real application. * It's not user-friendly, fault-tolerant, whatever. * However, it really works for real GZIP files, provided they are small * enough to fit in buffer[] (after decompression!). */ #include <stdio.h> #include <string.h> #include <zlib.h> #ifndef __CC65__ /* * Emulate inflatemem() if using original zlib. * As you can see, this program is quite portable. */ unsigned inflatemem(char* dest, const char* source) { z_stream stream; stream.next_in = (Bytef*) source; stream.avail_in = 65535; stream.next_out = dest; stream.avail_out = 65535; stream.zalloc = (alloc_func) 0; stream.zfree = (free_func) 0; inflateInit2(&stream, -MAX_WBITS); inflate(&stream, Z_FINISH); inflateEnd(&stream); return stream.total_out; } #endif /* __CC65__ */ /* * Structure of a GZIP file: * * 1. GZIP header: * Offset 0: Signature (2 bytes: 0x1f, 0x8b) * Offset 2: Compression method (1 byte: 8 == "deflate") * Offset 3: Flags (1 byte: see below) * Offset 4: File date and time (4 bytes) * Offset 8: Extra flags (1 byte) * Offset 9: Target OS (1 byte: DOS, Amiga, Unix, etc.) * if (flags & FEXTRA) { 2 bytes of length, then length bytes } * if (flags & FNAME) { ASCIIZ filename } * if (flags & FCOMMENT) { ASCIIZ comment } * if (flags & FHCRC) { 2 bytes of CRC } * * 2. Deflate compressed data. * * 3. GZIP trailer: * Offset 0: CRC-32 (4 bytes) * Offset 4: uncompressed file length (4 bytes) */ /* Flags in the GZIP header. */ #define FTEXT 1 /* Extra text */ #define FHCRC 2 /* Header CRC */ #define FEXTRA 4 /* Extra field */ #define FNAME 8 /* File name */ #define FCOMMENT 16 /* File comment */ /* * We read whole GZIP file into this buffer. * Then we use this buffer for the decompressed data. */ static unsigned char buffer[26000]; /* * Get a 16-bit little-endian unsigned number, using unsigned char* p. * On many machines this could be (*(unsigned short*) p), * but I really like portability. :-) */ #define GET_WORD(p) (*(p) + ((unsigned) (p)[1] << 8)) /* Likewise, for a 32-bit number. */ #define GET_LONG(p) (GET_WORD(p) + ((unsigned long) GET_WORD(p + 2) << 16)) /* * Uncompress a GZIP file. * On entry, buffer[] should contain the whole GZIP file contents, * and the argument complen should be equal to the length of the GZIP file. * On return, buffer[] contains the uncompressed data, and the returned * value is the length of the uncompressed data. */ unsigned uncompress_buffer(unsigned complen) { unsigned char* ptr; unsigned long crc; unsigned long unclen; void* ptr2; unsigned unclen2; /* check GZIP signature */ if (buffer[0] != 0x1f || buffer[1] != 0x8b) { puts("Not GZIP format"); return 0; } /* check compression method (it is always (?) "deflate") */ if (buffer[2] != 8) { puts("Unsupported compression method"); return 0; } /* get CRC from GZIP trailer */ crc = GET_LONG(buffer + complen - 8); /* get uncompressed length from GZIP trailer */ unclen = GET_LONG(buffer + complen - 4); if (unclen > sizeof(buffer)) { puts("Uncompressed size too big"); return 0; } /* skip extra field, file name, comment and crc */ ptr = buffer + 10; if (buffer[3] & FEXTRA) ptr = buffer + 12 + GET_WORD(buffer + 10); if (buffer[3] & FNAME) while (*ptr++ != 0); if (buffer[3] & FCOMMENT) while (*ptr++ != 0); if (buffer[3] & FHCRC) ptr += 2; /* * calculate length of raw "deflate" data * (without the GZIP header and 8-byte trailer) */ complen -= (ptr - buffer) + 8; /* * We will move the compressed data to the end of buffer[]. * Thus the compressed data and the decompressed data (written from * the beginning of buffer[]) may overlap, as long as the decompressed * data doesn't go further than unread compressed data. * ptr2 points to the beginning of compressed data at the end * of buffer[]. */ ptr2 = buffer + sizeof(buffer) - complen; /* move the compressed data to end of buffer[] */ memmove(ptr2, ptr, complen); /* uncompress */ puts("Inflating..."); unclen2 = inflatemem(buffer, ptr2); /* verify uncompressed length */ if (unclen2 != (unsigned) unclen) { puts("Uncompressed size does not match"); return 0; } /* verify CRC */ puts("Calculating CRC..."); if (crc32(crc32(0L, Z_NULL, 0), buffer, unclen2) != crc) { puts("CRC mismatch"); return 0; } /* return number of uncompressed bytes */ return unclen2; } /* * Get a filename from standard input. */ char* get_fname(void) { static char filename[100]; unsigned len; fgets(filename, sizeof(filename), stdin); len = strlen(filename); if (len >= 1 && filename[len - 1] == '\n') filename[len - 1] = '\0'; return filename; } int main(void) { FILE* fp; unsigned length; /* read GZIP file */ puts("GZIP file name:"); fp = fopen(get_fname(), "rb"); if (!fp) { puts("Can't open GZIP file"); return 1; } length = fread(buffer, 1, sizeof(buffer), fp); fclose(fp); if (length == sizeof(buffer)) { puts("File is too long"); return 1; } /* decompress */ length = uncompress_buffer(length); if (length == 0) return 1; /* write uncompressed file */ puts("Uncompressed file name:"); fp = fopen(get_fname(), "wb"); if (!fp) { puts("Can't create output file"); return 1; } if (fwrite(buffer, 1, length, fp) != length) { puts("Error while writing output file"); return 1; } fclose(fp); puts("Ok."); return 0; }
729
./cc65/samples/plasma.c
/***************************************************************************** * plasma test program for cc65. * * * * (w)2001 by groepaz/hitmen * * * * Cleanup and porting by Ullrich von Bassewitz. * * * *****************************************************************************/ #include <stdlib.h> #include <time.h> #include <conio.h> #if defined(__C64__) || defined(__C128__) # define SCREEN1 0xE000 # define SCREEN2 0xE400 # define CHARSET 0xE800 # define outb(addr,val) (*(addr)) = (val) # define inb(addr) (*(addr)) #elif defined(__CBM510__) # define SCREEN1 0xF000 # define SCREEN2 0xF400 # define CHARSET 0xE000 # define outb(addr,val) pokebsys ((unsigned)(addr), val) # define inb(addr) peekbsys ((unsigned)(addr)) #elif defined(__PLUS4__) # define SCREEN1 0x6400 # define SCREEN2 0x6C00 # define CHARSET 0x7000 # define outb(addr,val) (*(addr)) = (val) # define inb(addr) (*(addr)) #endif /* Values for the VIC address register to switch between the two pages */ #if defined(__PLUS4__) #define PAGE1 ((SCREEN1 >> 8) & 0xF8) #define PAGE2 ((SCREEN2 >> 8) & 0xF8) #define CHARADR ((CHARSET >> 8) & 0xFC) #else #define PAGE1 ((SCREEN1 >> 6) & 0xF0) | ((CHARSET >> 10) & 0x0E) #define PAGE2 ((SCREEN2 >> 6) & 0xF0) | ((CHARSET >> 10) & 0x0E) #endif /* Use static local variables for speed */ #pragma static-locals (1); static const unsigned char sinustable[0x100] = { 0x80, 0x7d, 0x7a, 0x77, 0x74, 0x70, 0x6d, 0x6a, 0x67, 0x64, 0x61, 0x5e, 0x5b, 0x58, 0x55, 0x52, 0x4f, 0x4d, 0x4a, 0x47, 0x44, 0x41, 0x3f, 0x3c, 0x39, 0x37, 0x34, 0x32, 0x2f, 0x2d, 0x2b, 0x28, 0x26, 0x24, 0x22, 0x20, 0x1e, 0x1c, 0x1a, 0x18, 0x16, 0x15, 0x13, 0x11, 0x10, 0x0f, 0x0d, 0x0c, 0x0b, 0x0a, 0x08, 0x07, 0x06, 0x06, 0x05, 0x04, 0x03, 0x03, 0x02, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x03, 0x03, 0x04, 0x05, 0x06, 0x06, 0x07, 0x08, 0x0a, 0x0b, 0x0c, 0x0d, 0x0f, 0x10, 0x11, 0x13, 0x15, 0x16, 0x18, 0x1a, 0x1c, 0x1e, 0x20, 0x22, 0x24, 0x26, 0x28, 0x2b, 0x2d, 0x2f, 0x32, 0x34, 0x37, 0x39, 0x3c, 0x3f, 0x41, 0x44, 0x47, 0x4a, 0x4d, 0x4f, 0x52, 0x55, 0x58, 0x5b, 0x5e, 0x61, 0x64, 0x67, 0x6a, 0x6d, 0x70, 0x74, 0x77, 0x7a, 0x7d, 0x80, 0x83, 0x86, 0x89, 0x8c, 0x90, 0x93, 0x96, 0x99, 0x9c, 0x9f, 0xa2, 0xa5, 0xa8, 0xab, 0xae, 0xb1, 0xb3, 0xb6, 0xb9, 0xbc, 0xbf, 0xc1, 0xc4, 0xc7, 0xc9, 0xcc, 0xce, 0xd1, 0xd3, 0xd5, 0xd8, 0xda, 0xdc, 0xde, 0xe0, 0xe2, 0xe4, 0xe6, 0xe8, 0xea, 0xeb, 0xed, 0xef, 0xf0, 0xf1, 0xf3, 0xf4, 0xf5, 0xf6, 0xf8, 0xf9, 0xfa, 0xfa, 0xfb, 0xfc, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfc, 0xfb, 0xfa, 0xfa, 0xf9, 0xf8, 0xf6, 0xf5, 0xf4, 0xf3, 0xf1, 0xf0, 0xef, 0xed, 0xeb, 0xea, 0xe8, 0xe6, 0xe4, 0xe2, 0xe0, 0xde, 0xdc, 0xda, 0xd8, 0xd5, 0xd3, 0xd1, 0xce, 0xcc, 0xc9, 0xc7, 0xc4, 0xc1, 0xbf, 0xbc, 0xb9, 0xb6, 0xb3, 0xb1, 0xae, 0xab, 0xa8, 0xa5, 0xa2, 0x9f, 0x9c, 0x99, 0x96, 0x93, 0x90, 0x8c, 0x89, 0x86, 0x83 }; static void doplasma (register unsigned char* scrn) { unsigned char xbuf[40]; unsigned char ybuf[25]; unsigned char c1a,c1b; unsigned char c2a,c2b; unsigned char c1A,c1B; unsigned char c2A,c2B; register unsigned char i, ii; c1a = c1A; c1b = c1B; for (ii = 0; ii < 25; ++ii) { ybuf[ii] = (sinustable[c1a] + sinustable[c1b]); c1a += 4; c1b += 9; } c1A += 3; c1B -= 5; c2a = c2A; c2b = c2B; for (i = 0; i < 40; ++i) { xbuf[i] = (sinustable[c2a] + sinustable[c2b]); c2a += 3; c2b += 7; } c2A += 2; c2B -= 3; for (ii = 0; ii < 25; ++ii) { /* Unrolling the following loop will give a speed increase of * nearly 100% (~24fps), but it will also increase the code * size a lot. */ for (i = 0; i < 40; ++i, ++scrn) { *scrn = (xbuf[i] + ybuf[ii]); } } } static void makechar (void) { static const unsigned char bittab[8] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 }; unsigned char i, ii, b, s; unsigned c; gotoxy (0, 1); for (c = 0; c < 0x100; ++c) { s = sinustable[c]; for (i = 0; i < 8; ++i){ b = 0; for (ii = 0; ii < 8; ++ii) { if ((rand() & 0xFF) > s) { b |= bittab[ii]; } } ((unsigned char*)CHARSET) [(c*8) + i] = b; } if ((c & 0x07) == 0) { cputc ('.'); } } } int main (void) { unsigned char border; unsigned char background; unsigned char text; unsigned char v; clock_t t; unsigned long f = 0; unsigned long sec; unsigned sec10; unsigned long fps; unsigned fps10; #if defined(__C64__) unsigned char block; #endif #if defined(__C128__) unsigned char block; unsigned char initflag; unsigned char graphflag; #endif #if defined(__PLUS4__) unsigned int i; unsigned char v2; #endif clrscr (); cprintf ("Making charset, mompls"); makechar(); /* Set the border and background colors */ border = bordercolor (COLOR_BLUE); background = bgcolor (COLOR_BLUE); text = textcolor (COLOR_BLACK); clrscr (); #if defined(__C64__) || defined(__C128__) /* Move the VIC 16K block */ block = inb (&CIA2.pra); outb (&CIA2.pra, (block & 0xFC) | ((SCREEN1 >> 14) ^ 0x03)); #endif #if defined(__C128__) /* Save and change some flags, so that kernal/basic interupt handler will * not interfere with our routine. */ initflag = *(unsigned char*) 0xA04; *(unsigned char*) 0xA04 &= 0xFE; graphflag = *(unsigned char*) 0xD8; *(unsigned char*) 0xD8 = 0xFF; #endif /* Remember the VIC address register */ #if defined(__PLUS4__) v = inb (&TED.char_addr); v2 = inb (&TED.video_addr); #else v = inb (&VIC.addr); #endif #if defined(__PLUS4__) for (i=0;i<1000;i++) { ((unsigned char *) (SCREEN1-0x0400))[i] = 0; ((unsigned char *) (SCREEN2-0x0400))[i] = 0; } outb (&TED.char_addr, CHARADR); #endif /* Run the demo until a key was hit */ t = clock (); while (!kbhit()) { /* Build page 1, then make it visible */ doplasma ((unsigned char*)SCREEN1); #if defined(__PLUS4__) outb (&TED.video_addr, PAGE1); #else outb (&VIC.addr, PAGE1); #endif /* Build page 2, then make it visible */ doplasma ((unsigned char*)SCREEN2); #if defined(__PLUS4__) outb (&TED.video_addr, PAGE2); #else outb (&VIC.addr, PAGE2); #endif /* Count frames */ f += 2; } t = clock() - t; /* Switch back the VIC screen */ #if defined(__PLUS4__) outb (&TED.video_addr, v2); outb (&TED.char_addr, v); #else outb (&VIC.addr, v); #endif #if defined(__C64__) || defined(__C128__) /* Move back the VIC 16K block */ outb (&CIA2.pra, block); #endif #if defined(__C128__) /* Restore the flags */ *(unsigned char*) 0xA04 = initflag; *(unsigned char*) 0xD8 = graphflag; #endif /* Fetch the character from the keyboard buffer and discard it */ (void) cgetc(); /* Reset screen colors */ bordercolor (border); bgcolor (background); textcolor (text); clrscr (); /* Calculate stats */ sec = (t * 10) / CLK_TCK; sec10 = sec % 10; sec /= 10; fps = (f * (CLK_TCK * 10)) / t; fps10 = fps % 10; fps /= 10; /* Output stats */ gotoxy (0, 0); cprintf ("time : %lu.%us", sec, sec10); gotoxy (0, 1); cprintf ("frames: %lu", f); gotoxy (0, 2); cprintf ("fps : %lu.%u", fps, fps10); /* Wait for a key, then end */ cputsxy (0, 4, "Press any key when done..."); (void) cgetc (); /* Done */ return EXIT_SUCCESS; }
730
./cc65/samples/diodemo.c
/*****************************************************************************/ /* */ /* diodemo.c */ /* */ /* Direct Disk I/O Demo Program */ /* */ /* */ /* */ /* (C) Copyright 2005, Oliver Schmidt, <ol.sc@web.de> */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stddef.h> #include <stdlib.h> #include <limits.h> #include <conio.h> #include <ctype.h> #include <errno.h> #include <dio.h> #define MAX_CHUNKS 10 /* Maximum acceptable number of chunks */ static unsigned char ScreenX; static unsigned char ScreenY; static void ClearLine (void) /* Clear the screen line the cursor is on */ { cputc ('\r'); cclear (ScreenX); } static unsigned char AskForDrive (const char* Name) /* Ask for a drive id and return it */ { unsigned char Drive = 0; char Char; cprintf ("\r\n%s Drive ID ? ", Name); cursor (1); do { Char = cgetc (); if (isdigit (Char)) { cputc (Char); Drive = Drive * 10 + Char - '0'; } } while (Char != CH_ENTER); cursor (0); return Drive; } static void AskForDisk (const char* Name, unsigned char Drive) /* Ask the user to insert a specific disk */ { ClearLine (); cprintf ("\rInsert %s Disk into Drive %d !", Name, Drive); cgetc (); } static char* AllocBuffer (unsigned int SectSize, unsigned int SectCount, unsigned int* ChunkCount) /* Allocate a copy buffer on the heap and return a pointer to it */ { char* Buffer = NULL; unsigned long BufferSize; unsigned int Chunks = 1; /* Increase number of chunks resp. decrease size */ /* of one chunk until buffer allocation succeeds */ do { *ChunkCount = (unsigned int) ((SectCount + Chunks - 1) / Chunks); BufferSize = *ChunkCount * (unsigned long) SectSize; if (BufferSize < UINT_MAX) { Buffer = malloc ((size_t) BufferSize); } } while (Buffer == NULL && ++Chunks <= MAX_CHUNKS); return Buffer; } int main (int argc, const char* argv[]) { unsigned char SourceId; unsigned char TargetId; dhandle_t Source = NULL; dhandle_t Target = NULL; unsigned int SectSize; unsigned int SectCount; char* Buffer; unsigned int Sector; unsigned int ChunkCount; unsigned int ChunkOffset = 0; clrscr (); screensize (&ScreenX, &ScreenY); cputs ("Floppy Disk Copy\r\n"); chline (16); cputs ("\r\n"); /* Get source and target drive id (which may very well be identical) */ switch (argc) { case 1: SourceId = AskForDrive ("Source"); TargetId = AskForDrive ("Target"); cputs ("\r\n"); break; case 2: SourceId = TargetId = atoi (argv[1]); break; case 3: SourceId = atoi (argv[1]); TargetId = atoi (argv[2]); break; default: cprintf ("\r\nToo many arguments\r\n"); return EXIT_FAILURE; } cputs ("\r\n"); do { /* Check for single drive copy or inital iteration */ if (SourceId == TargetId || Source == NULL) { AskForDisk ("Source", SourceId); } /* Check for initial iteration */ if (Source == NULL) { /* Open source drive */ Source = dio_open (SourceId); if (Source == NULL) { cprintf ("\r\n\nError %d on opening Drive %d\r\n", (int) _oserror, SourceId); return EXIT_FAILURE; } SectSize = dio_query_sectsize (Source); SectCount = dio_query_sectcount (Source); /* Allocate buffer */ Buffer = AllocBuffer (SectSize, SectCount, &ChunkCount); if (Buffer == NULL) { cputs ("\r\n\nError on allocating Buffer\r\n"); return EXIT_FAILURE; } } ClearLine (); /* Read one chunk of sectors into buffer */ for (Sector = ChunkOffset; Sector < SectCount && (Sector - ChunkOffset) < ChunkCount; ++Sector) { cprintf ("\rReading Sector %d of %d", Sector + 1, SectCount); /* Read one sector */ if (dio_read (Source, Sector, Buffer + (Sector - ChunkOffset) * SectSize) != 0) { cprintf ("\r\n\nError %d on reading from Drive %d\r\n", (int) _oserror, SourceId); return EXIT_FAILURE; } } /* Check for single drive copy or inital iteration */ if (TargetId == SourceId || Target == NULL) { AskForDisk ("Target", TargetId); } /* Open target drive on initial iteration */ if (Target == NULL) { Target = dio_open (TargetId); if (Target == NULL) { cprintf ("\r\n\nError %d on opening Drive %d\r\n", (int) _oserror, TargetId); return EXIT_FAILURE; } /* Check for compatible drives */ if (dio_query_sectsize (Target) != SectSize || dio_query_sectcount (Target) != SectCount) { cputs ("\r\n\nFormat mismatch between Drives\r\n"); return EXIT_FAILURE; } } ClearLine (); /* Write one chunk of sectors from buffer */ for (Sector = ChunkOffset; Sector < SectCount && (Sector - ChunkOffset) < ChunkCount; ++Sector) { cprintf ("\rWriting Sector %d of %d", Sector + 1, SectCount); /* Write one sector */ if (dio_write (Target, Sector, Buffer + (Sector - ChunkOffset) * SectSize) != 0) { cprintf ("\r\n\nError %d on writing to Drive %d\r\n", (int) _oserror, TargetId); return EXIT_FAILURE; } } /* Advance to next chunk */ ChunkOffset += ChunkCount; } while (Sector < SectCount); ClearLine (); cprintf ("\rSuccessfully copied %d Sectors\r\n", SectCount); free (Buffer); dio_close (Source); dio_close (Target); return EXIT_SUCCESS; }
731
./cc65/samples/geos/geosconio.c
#include <geos.h> #include <conio.h> #include <mouse.h> void main(void) { struct mouse_info info; char ch; DlgBoxOk("Now the screen will be", "cleared."); clrscr(); DlgBoxOk("Now a character will be", "written at 20,20"); gotoxy(20, 20); cputc('A'); DlgBoxOk("Now a string will be", "written at 0,1"); cputsxy(0, 1, CBOLDON "Just" COUTLINEON "a " CITALICON "string." CPLAINTEXT ); DlgBoxOk("Write text and finish it", "with a dot."); cursor(1); do { ch = cgetc(); cputc(ch); } while (ch!='.'); cursor(0); DlgBoxOk("Seems that it is all for conio.", "Let's test mouse routines."); mouse_init(1); cputsxy(0, 2, CBOLDON "Now you can't see mouse (press any key)" CPLAINTEXT); mouse_hide(); while (!kbhit()) { }; cputc(cgetc()); cputsxy(0, 3, CBOLDON "Now you see the mouse (press any key)" CPLAINTEXT); mouse_show(); while (!kbhit()) { }; cputc(cgetc()); // Get the current mouse coordinates and button states and print them mouse_info(&info); gotoxy(0, 4); cprintf("X = %3d", info.pos.x); gotoxy(0, 5); cprintf("Y = %3d", info.pos.y); gotoxy(0, 6); cprintf("LB = %c", (info.buttons & MOUSE_BTN_LEFT)? '1' : '0'); gotoxy(0, 7); cprintf("RB = %c", (info.buttons & MOUSE_BTN_RIGHT)? '1' : '0'); DlgBoxOk("Bye,", "Bye."); }
732
./cc65/samples/geos/yesno.c
/* GEOSLib example example of using DlgBoxYesNo, DlgBoxOkCancel and DlgBoxOk functions Maciej 'YTM/Elysium' Witkowiak <ytm@elysium.pl> 26.12.1999 */ #include <geos.h> void main(void) { do { if (DlgBoxYesNo("Are you female?", "(don't lie ;-)") == YES) { DlgBoxOk("You claim to be woman!", "You wanna dance?"); } else { DlgBoxOk("Ergh, another man...", "Let's go for a beer."); }; } while (DlgBoxOkCancel("Do you want to try again?", "") == OK); }
733
./cc65/samples/geos/bitmap-demo.c
/* * Minimalistic GEOSLib bitmap demo program * * 2012-06-10, Oliver Schmidt (ol.sc@web.de) * * To create bitmap.c use the sp65 sprite and bitmap utility: * sp65 -r logo.pcx -c geos-bitmap -w bitmap.c,ident=bitmap * */ #include <conio.h> #include <geos.h> #include "bitmap.c" #if (!(bitmap_COLORS == 2 && \ bitmap_WIDTH%8 == 0 && \ bitmap_WIDTH <= SC_PIX_WIDTH && \ bitmap_HEIGHT <= SC_PIX_HEIGHT)) #error Incompatible Bitmap #endif struct iconpic picture = {(char*)bitmap, 0, 0, bitmap_WIDTH/8, bitmap_HEIGHT}; void main(void) { BitmapUp(&picture); cgetc(); }
734
./cc65/samples/geos/menu.c
/* Note: * This is just a sample piece of code that shows how to use some structs - * it may not even run. */ #include <geos.h> /* prototypes are necessary */ void smenu1 (void); void smenu2 (void); void smenu3 (void); typedef void menuString; /* you can declare a menu using cc65 non-ANSI extensions */ static const menuString subMenu1 = { (char)0, (char)(3*15), (unsigned)0, (unsigned)50, (char)(3 | VERTICAL), "subitem1", (char)MENU_ACTION, (unsigned)smenu1, "subitem2", (char)MENU_ACTION, (unsigned)smenu2, "subitem3", (char)MENU_ACTION, (unsigned)smenu3 }; /* or by using initialized structures */ static struct menu subMenu2 = { { 0, 3*15, 0, 50 }, 3 | VERTICAL, { { "subitem1", MENU_ACTION, smenu1 }, { "subitem2", MENU_ACTION, smenu2 }, { "subitem3", MENU_ACTION, smenu3 }, } }; void main (void) { DoMenu(&subMenu1); DoMenu(&subMenu2); }
735
./cc65/samples/geos/getid.c
/* This is an example program for GEOS. It reads GEOS serial number and prints it on the screen. Maciej 'YTM/Elysium' Witkowiak <ytm@elysium.pl> 05.03.2004 */ #include <stdlib.h> #include <geos.h> #include <conio.h> const graphicStr Table = { NEWPATTERN(0), MOVEPENTO(0, 0), RECTANGLETO(320, 199), GSTR_END }; void Exit(void) { exit(0); } void Menu = { (char)0, (char)14, (int)0, (int)28, (char)(HORIZONTAL|1), CBOLDON "quit", (char)MENU_ACTION, &Exit }; int main(void) { dispBufferOn = ST_WR_FORE; GraphicsString(&Table); cputsxy(0, 3, CBOLDON "Your Serial Number is:"); cputhex16(GetSerialNumber()); DoMenu(&Menu); MainLoop(); // will never reach this point... return 0; }
736
./cc65/samples/geos/hello2.c
/* GEOSLib example Hello, world example - using graphic functions Maciej 'YTM/Alliance' Witkowiak <ytm@friko.onet.pl> 26.12.1999 */ #include <geos.h> // Let's define the window we're operating struct window wholeScreen = {0, SC_PIX_HEIGHT-1, 0, SC_PIX_WIDTH-1}; void main (void) { // Let's show what we've got... // Let's clear the screen - with different pattern, because apps have cleared screen upon // start SetPattern(0); InitDrawWindow(&wholeScreen); Rectangle(); // Now some texts PutString(COUTLINEON "This is compiled using cc65!" CPLAINTEXT, 20, 10); PutString(CBOLDON "This is bold", 30, 10); PutString(CULINEON "and this is bold and underline!", 40, 10); PutString(CPLAINTEXT "This is plain text", 50, 10); // Wait for 5 secs... // Note that this is multitasking sleep, and if there are any icons/menus onscreen, // they would be usable, in this case you have only pointer usable Sleep(5*50); // Normal apps exit from main into system's mainloop, and app finish // when user selects it from icons or menu, but here we want to exit // immediately. // So instead: // MainLoop(); // we can do: // (nothing as this is the end of main function) // exit(0); // return; return; }
737
./cc65/samples/geos/filesel.c
/* GEOSLib example using DlgBoxFileSelect Maciej 'YTM/Elysium' Witkowiak <ytm@elysium.pl> 26.12.1999 */ #include <geos.h> char fName[17] = ""; void main (void) { r0=(int)fName; DlgBoxOk(CBOLDON "You now will be presented", "with an apps list" CPLAINTEXT); DlgBoxFileSelect("", APPLICATION, fName); DlgBoxOk("You've chosen:" CBOLDON, fName); }
738
./cc65/samples/geos/overlay-demo.c
/* * Minimalistic GEOSLib overlay demo program * * 2012-01-01, Oliver Schmidt (ol.sc@web.de) * */ #include <stdio.h> #include <geos.h> #include "overlay-demores.h" /* Functions resident in an overlay can call back functions resident in the * main program at any time without any precautions. The function show() is * an example for such a function resident in the main program. */ void show(char *name) { char line1[40]; sprintf(line1, CBOLDON "Overlay Demo - Overlay %s" CPLAINTEXT, name); DlgBoxOk(line1, "Click OK to return to Main."); } /* In a real-world overlay program one would probably not use a #pragma but * rather place the all the code of certain source files into the overlay by * compiling them with --code-name OVERLAY1. */ #pragma code-name(push, "OVERLAY1"); void foo(void) { /* Functions resident in an overlay can access all program variables and * constants at any time without any precautions because those are never * placed in overlays. The string constant "One" is an example for such * a constant resident in the main program. */ show("One"); } #pragma code-name(pop); #pragma code-name(push, "OVERLAY2"); void bar(void) { show("Two"); } #pragma code-name(pop); #pragma code-name(push, "OVERLAY3"); void foobar (void) { show("Three"); } #pragma code-name(pop); void main(int /*argc*/, char *argv[]) { if (OpenRecordFile(argv[0])) { _poserror("OpenRecordFile"); return; } DlgBoxOk(CBOLDON "Overlay Demo - Main" CPLAINTEXT, "Click OK to call Overlay One."); if (PointRecord(1)) { _poserror("PointRecord.1"); return; } /* The macro definitions OVERLAY_ADDR and OVERLAY_SIZE were generated in * overlay-demores.h by grc65. They contain the overlay area address and * size specific to a certain program. */ if (ReadRecord(OVERLAY_ADDR, OVERLAY_SIZE)) { _poserror("ReadRecord.1"); return; } /* The linker makes sure that the call to foo() ends up at the right mem * addr. However it's up to user to make sure that the - right - overlay * is actually loaded before making the the call. */ foo(); DlgBoxOk(CBOLDON "Overlay Demo - Main" CPLAINTEXT, "Click OK to call Overlay Two."); if (PointRecord(2)) { _poserror("PointRecord.2"); return; } /* Replacing one overlay with another one can only happen from the main * program. This implies that an overlay can never load another overlay. */ if (ReadRecord(OVERLAY_ADDR, OVERLAY_SIZE)) { _poserror("ReadRecord.2"); return; } bar(); DlgBoxOk(CBOLDON "Overlay Demo - Main" CPLAINTEXT, "Click OK to call Overlay Three."); if (PointRecord(3)) { _poserror("PointRecord.3"); return; } if (ReadRecord(OVERLAY_ADDR, OVERLAY_SIZE)) { _poserror("ReadRecord.3"); return; } foobar(); if (CloseRecordFile()) { _poserror("CloseRecordFile"); return; } }
739
./cc65/samples/geos/vector-demo.c
#include <geos.h> #include <conio.h> #include <stdlib.h> unsigned char x,y; void_func oldMouseVector, oldKeyVector; void foo1 (void) { // do something on mouse press/release gotoxy(x,y); ++x; cputc('A'); // call previous routine oldMouseVector(); } void foo2 (void) { // do something on key press/release gotoxy(x,y); ++y; cputc('B'); // call previous routine oldKeyVector(); } void hook_into_system(void) { // hook into system vectors - preserve old value oldMouseVector = mouseVector; mouseVector = foo1; oldKeyVector = keyVector; keyVector = foo2; } void remove_hooks(void) { mouseVector = oldMouseVector; keyVector = oldKeyVector; } int main(void) { x = 0; y = 0; // To make cc65 do something for you before exiting you might register // a function to be called using atexit call. #include <stdlib.h> then and // write: atexit(&remove_hooks); clrscr(); cputsxy(0,1, CBOLDON "Just" COUTLINEON "a " CITALICON "string." CPLAINTEXT ); hook_into_system(); // This program will loop forever though MainLoop(); // If not using atexit() you have to remember about restoring system vectors // right before exiting your application. Otherwise the system will most // likely crash. // remove_hooks(); return 0; }
740
./cc65/samples/geos/inittab.c
/* Note: * This is just a sample piece of code that shows how to use some structs - * it may not even run. */ #include <geos.h> static const void myTab = { 0xd020, (char)2, (char)0, (char)2, 0x4000, (char)5, (char)0, (char)1, (char)2, (char)3, (char)4, 0x0000 }; int main (void) { InitRam(&myTab); }
741
./cc65/samples/geos/grphstr.c
/* Note: * This is just a sample piece of code that shows how to use some structs - * it may not even run. */ #include <geos.h> static const graphicStr myString = { MOVEPENTO (0, 0), LINETO(100, 100), RECTANGLETO(50, 50), NEWPATTERN(3), FRAME_RECTO(50, 50), PEN_X_DELTA(10), PEN_Y_DELTA(10), PEN_XY_DELTA(10, 10), GSTR_END }; int main (void) { GraphicsString(&myString); }
742
./cc65/samples/geos/dialog.c
/* Note: * This is just a sample piece of code that shows how to use some structs - * it may not even run. */ #include <geos.h> void sysopvfunc (void); void opvecfunc (void); void usrfunc (void); static const dlgBoxStr myDialog = { DB_SETPOS (1, 0, 150, 0, 319), DB_TXTSTR (10, 20, "test"), DB_VARSTR (10, 20, &r0L), DB_GETSTR (10, 20, &r0L, 9), DB_SYSOPV (sysopvfunc), DB_GRPHSTR (&r0L), DB_GETFILES (10, 10), DB_OPVEC (opvecfunc), DB_USRICON (0, 0, &r0L), DB_USRROUT (usrfunc), DB_ICON (OK, DBI_X_0, DBI_Y_0 ), DB_ICON (CANCEL, DBI_X_1, DBI_Y_1), DB_END }; void main (void) { DoDlgBox (&myDialog); }
743
./cc65/samples/geos/rmvprot.c
/* GEOSLib example This small application removes GEOS disk write protection tag. e.g. boot disk is always protected after boot-up Maciej 'YTM/Elysium' Witkowiak <ytm@elysium.pl> 21.03.2000 */ #include <geos.h> char diskName[17] = ""; static const graphicStr clearScreen = { MOVEPENTO(0, 0), NEWPATTERN(2), RECTANGLETO(SC_PIX_WIDTH-1, SC_PIX_HEIGHT-1), GSTR_END }; static const dlgBoxStr mainDialog = { DB_DEFPOS(1), DB_TXTSTR(TXT_LN_X, TXT_LN_2_Y, CBOLDON "Remove protection on:" CPLAINTEXT), DB_TXTSTR(TXT_LN_X, TXT_LN_3_Y, diskName), DB_ICON(OK, DBI_X_0, DBI_Y_2), DB_ICON(DISK, DBI_X_1, DBI_Y_2), DB_ICON(CANCEL, DBI_X_2, DBI_Y_2), DB_END }; static const dlgBoxStr changeDiskDlg = { DB_DEFPOS(1), DB_TXTSTR(TXT_LN_X, TXT_LN_2_Y, CBOLDON "Insert new disk"), DB_TXTSTR(TXT_LN_X, TXT_LN_3_Y, "into drive." CPLAINTEXT), DB_ICON(OK, DBI_X_0, DBI_Y_2), DB_ICON(CANCEL, DBI_X_2, DBI_Y_2), DB_END }; static const dlgBoxStr errorDialog = { DB_DEFPOS(1), DB_TXTSTR(TXT_LN_X, TXT_LN_2_Y, CBOLDON "Error happened..."), DB_TXTSTR(TXT_LN_X, TXT_LN_3_Y, "exiting..." CPLAINTEXT), DB_ICON(OK, DBI_X_0, DBI_Y_2), DB_END }; void Error(void) { DoDlgBox(&errorDialog); EnterDeskTop(); } void main(void) { // Here we clear the screen. Not really needed anyway... GraphicsString(&clearScreen); // Get the name of current disk to show it in dialog box GetPtrCurDkNm(diskName); while (1) { switch (DoDlgBox(&mainDialog)) { // What's the result of dialog box? which icon was pressed? case OK: if (GetDirHead()) Error(); curDirHead[OFF_GS_DTYPE] = 0; if (PutDirHead()) Error(); break; case DISK: DoDlgBox(&changeDiskDlg); GetPtrCurDkNm(diskName); break; default: // CANCEL is the third option return; break; } } }
744
./cc65/samples/geos/hello1.c
/* GEOSLib example Hello, world example - with DBox Maciej 'YTM/Elysium' Witkowiak <ytm@elysium.pl> 26.12.1999 */ #include <geos.h> void main (void) { // Let's show what we've got... DlgBoxOk(CBOLDON "Hello, world" CPLAINTEXT, "This is written in C!"); // Normal apps exit from main into system's mainloop, and app finish // when user selects it from icons or menu, but here we want to exit // immediately. // So instead: // MainLoop(); // we can do: // (nothing as this is the end of main function) // exit(0); // return; return; }
745
./cc65/samples/tutorial/hello.c
#include <stdio.h> #include <stdlib.h> extern const char text[]; /* In text.s */ int main (void) { printf ("%s\n", text); return EXIT_SUCCESS; }
746
./cc65/libsrc/tgi/tgi_pieslice.c
/*****************************************************************************/ /* */ /* tgi_pieslice.c */ /* */ /* Draw an ellipic pie slice */ /* */ /* */ /* */ /* (C) 2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <tgi.h> #include <tgi/tgi-kernel.h> #include <cc65.h> /*****************************************************************************/ /* Code */ /*****************************************************************************/ void __fastcall__ tgi_pieslice (int x, int y, unsigned char rx, unsigned char ry, unsigned sa, unsigned ea) /* Draw an ellipse pie slice with center at x/y and radii rx/ry using the * current drawing color. The pie slice covers the angle between sa and ea * (startangle and endangle), which must be in the range 0..360 (otherwise the * function may behave unextectedly). */ { /* Draw an arc ... */ tgi_arc (x, y, rx, ry, sa, ea); /* ... and close it */ tgi_line (x, y, x + tgi_imulround (rx, cc65_cos (sa)), y - tgi_imulround (ry, cc65_sin (sa))); tgi_line (x, y, x + tgi_imulround (rx, cc65_cos (ea)), y - tgi_imulround (ry, cc65_sin (ea))); }
747
./cc65/libsrc/tgi/tgi_load_vectorfont.c
/*****************************************************************************/ /* */ /* tgi_load_vectorfont.c */ /* */ /* Loader module for TGI vector font files */ /* */ /* */ /* */ /* (C) 2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <tgi.h> #include <tgi/tgi-kernel.h> #include <tgi/tgi-vectorfont.h> /*****************************************************************************/ /* Code */ /*****************************************************************************/ const tgi_vectorfont* __fastcall__ tgi_load_vectorfont (const char* name) /* Load a vector font into memory and return it. In case of errors, NULL is * returned and an error is set, which can be retrieved using tgi_geterror. * To use the font, it has to be installed using tgi_install_vectorfont. */ { static const char Magic[4] = { 0x54, 0x43, 0x48, TGI_VF_VERSION }; tgi_vectorfont_header H; int F; tgi_vectorfont* Font = 0; unsigned V; unsigned char I; /* Assume we have an error loading the font */ tgi_error = TGI_ERR_CANNOT_LOAD; /* Open the file */ F = open (name, O_RDONLY); if (F < 0) { /* Cannot open file */ goto LoadError; } /* Read the header */ if (read (F, &H, sizeof (H)) != sizeof (H)) { /* Cannot read header bytes */ goto LoadError; } /* Check the header */ if (memcmp (&H, Magic, sizeof (Magic)) != 0) { /* Header magic not ok */ goto LoadError; } /* Allocate memory for the data */ Font = malloc (H.size); if (Font == 0) { /* Out of memory */ tgi_error = TGI_ERR_NO_RES; goto LoadError; } /* Read the whole font file into the buffer */ if (read (F, Font, H.size) != H.size) { /* Problem reading font data */ free (Font); goto LoadError; } /* Close the file */ close (F); /* Fix the offset pointers. When loaded, they contain numeric offsets * into the VectorOps, with the start of the VectorOps at offset zero. * We will add a pointer to the VectorOps to make them actual pointers * that may be used independently from anything else. */ V = (unsigned) &Font->vec_ops; for (I = 0; I < TGI_VF_CCOUNT; ++I) { Font->chars[I] += V; } /* Clear the error */ tgi_error = TGI_ERR_OK; /* Return the vector font loaded */ return Font; LoadError: /* Some sort of load problem. If the file is still open, be sure to * close it */ if (F >= 0) { close (F); } return 0; }
748
./cc65/libsrc/tgi/tgi_arc.c
/*****************************************************************************/ /* */ /* tgi_arc.c */ /* */ /* Draw an ellipse arc */ /* */ /* */ /* */ /* (C) 2002-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <tgi.h> #include <tgi/tgi-kernel.h> #include <cc65.h> /*****************************************************************************/ /* Code */ /*****************************************************************************/ void __fastcall__ tgi_arc (int x, int y, unsigned char rx, unsigned char ry, unsigned sa, unsigned ea) /* Draw an ellipse arc with center at x/y and radii rx/ry using the current * drawing color. The arc covers the angle between sa and ea (startangle and * endangle), which must be in the range 0..360 (otherwise the function may * bevave unextectedly). */ { int x1, y1, x2, y2; unsigned char inc; unsigned char done = 0; /* Bail out if there's nothing to do */ if (sa > ea) { return; } /* Determine the number of segments to use. This may be refined ... */ if (rx + ry >= 25) { inc = 12; } else { inc = 24; } /* Calculate the start coords */ x1 = x + tgi_imulround (rx, cc65_cos (sa)); y1 = y - tgi_imulround (ry, cc65_sin (sa)); do { sa += inc; if (sa >= ea) { sa = ea; done = 1; } x2 = x + tgi_imulround (rx, cc65_cos (sa)); y2 = y - tgi_imulround (ry, cc65_sin (sa)); tgi_line (x1, y1, x2, y2); x1 = x2; y1 = y2; } while (!done); }
749
./cc65/libsrc/common/fgetpos.c
/* * fgetpos.c * * Christian Groessler, 07-Aug-2000 */ #include <stdio.h> /*****************************************************************************/ /* Code */ /*****************************************************************************/ int __fastcall__ fgetpos (FILE* f, fpos_t* pos) { *pos = ftell (f); if (*pos != -1) return 0; return -1; }
750
./cc65/libsrc/common/perror.c
/*****************************************************************************/ /* */ /* perror.c */ /* */ /* Print a system error message */ /* */ /* */ /* */ /* (C) 1998-2010, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> #include <errno.h> void __fastcall__ perror (const char* msg) { /* Fetch the message that corresponds to errno */ const char* errormsg = strerror (_errno); /* Different output depending on msg */ if (msg) { fprintf (stderr, "%s: %s\n", msg, errormsg); } else { fprintf (stderr, "%s\n", errormsg); } }
751
./cc65/libsrc/common/asctime.c
/*****************************************************************************/ /* */ /* asctime.c */ /* */ /* Convert a broken down time into a string */ /* */ /* */ /* */ /* (C) 2002 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@musoftware.de */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <time.h> /*****************************************************************************/ /* Code */ /*****************************************************************************/ char* __fastcall__ asctime (const struct tm* timep) { static char buf[26]; /* Format into given buffer and return the result */ return strftime (buf, sizeof (buf), "%c\n", timep)? buf : 0; }
752
./cc65/libsrc/common/getopt.c
/* * This is part of a changed public domain getopt implementation that * had the following text on top: * * I got this off net.sources from Henry Spencer. * It is a public domain getopt(3) like in System V. * I have made the following modifications: * * A test main program was added, ifdeffed by GETOPT. * This main program is a public domain implementation * of the getopt(1) program like in System V. The getopt * program can be used to standardize shell option handling. * e.g. cc -DGETOPT getopt.c -o getopt */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #define ARGCH ':' #define BADCH '?' #define EMSG "" int opterr = 1; /* useless, never set or used */ int optind = 1; /* index into parent argv vector */ int optopt; /* character checked for validity */ char *optarg; /* argument associated with option */ #define tell(s) fputs(*argv,stderr);fputs(s,stderr); \ fputc(optopt,stderr);fputc('\n',stderr);return(BADCH); int __fastcall__ getopt (int argc, char* const* argv, const char* optstring) /* Get option letter from argument vector */ { static char *place = EMSG; /* option letter processing */ register char *oli; /* option letter list index */ if (!*place) { /* update scanning pointer */ if (optind >= argc || *(place = argv[optind]) != '-' || !*++place) { return (EOF); } if (*place == '-') { /* found "--" */ ++optind; return (EOF); } } /* option letter okay? */ if ((optopt = (int) *place++) == ARGCH || !(oli = strchr (optstring, optopt))) { if (!*place) { ++optind; } tell (": illegal option -- "); } if (*++oli != ARGCH) { /* don't need argument */ optarg = NULL; if (!*place) { ++optind; } } else { /* need an argument */ if (*place) { /* no white space */ optarg = place; } else if (argc <= ++optind) { /* no arg */ place = EMSG; tell (": option requires an argument -- "); } else { /* white space */ optarg = argv[optind]; } place = EMSG; ++optind; } return (optopt); /* dump back option letter */ }
753
./cc65/libsrc/common/bsearch.c
/* * bsearch.c * * Ullrich von Bassewitz, 17.06.1998 */ #include <stdlib.h> void* __fastcall__ bsearch (const void* key, const void* base, size_t n, size_t size, int (*cmp) (const void*, const void*)) { int current; int result; int found = 0; int first = 0; int last = n - 1; /* Binary search */ while (first <= last) { /* Set current to mid of range */ current = (last + first) / 2; /* Do a compare */ result = cmp ((void*) (((int) base) + current*size), key); if (result < 0) { first = current + 1; } else { last = current - 1; if (result == 0) { /* Found one entry that matches the search key. However there may be * more than one entry with the same key value and ANSI guarantees * that we return the first of a row of items with the same key. */ found = 1; } } } /* Did we find the entry? */ return (void*) (found? ((int) base) + first*size : 0); }
754
./cc65/libsrc/common/localtime.c
/*****************************************************************************/ /* */ /* localtime.c */ /* */ /* Convert calendar time into broken down local time */ /* */ /* */ /* */ /* (C) 2002 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@musoftware.de */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <time.h> /*****************************************************************************/ /* Code */ /*****************************************************************************/ struct tm* __fastcall__ localtime (const time_t* timep) { static struct tm timebuf; time_t t; /* Check the argument */ if (timep == 0 || (long) (t = *timep) < 0) { /* Invalid arg */ return 0; } /* Since our ints are just 16 bits, split the given time into seconds, * hours and days. Each of the values will fit in a 16 bit variable. * The mktime routine will then do the rest. */ timebuf.tm_sec = t % 3600; timebuf.tm_min = 0; timebuf.tm_hour = (t / 3600) % 24; timebuf.tm_mday = (t / (3600UL * 24UL)) + 1; timebuf.tm_mon = 0; timebuf.tm_year = 70; /* Base value is 1/1/1970 */ /* Call mktime to do the final conversion */ mktime (&timebuf); /* Return the result */ return &timebuf; }
755
./cc65/libsrc/common/fgets.c
/* * Ullrich von Bassewitz, 11.08.1998 * * char* fgets (char* s, int size, FILE* f); */ #include <stdio.h> #include <errno.h> #include "_file.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ char* __fastcall__ fgets (char* s, unsigned size, register FILE* f) { register char* p = s; unsigned i; int c; if (size == 0) { /* Invalid size */ return (char*) _seterrno (EINVAL); } /* Read input */ i = 0; while (--size) { /* Get next character */ if ((c = fgetc (f)) == EOF) { /* Error or EOF */ if ((f->f_flags & _FERROR) != 0 || i == 0) { /* ERROR or EOF on first char */ *p = '\0'; return 0; } else { /* EOF with data already read */ break; } } /* One char more */ *p = c; ++p; ++i; /* Stop at end of line */ if ((char)c == '\n') { break; } } /* Terminate the string */ *p = '\0'; /* Done */ return s; }
756
./cc65/libsrc/common/pmemalign.c
/*****************************************************************************/ /* */ /* posix_memalign */ /* */ /* Allocate an aligned memory block */ /* */ /* */ /* */ /* (C) 2004-2005 Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided "as-is," without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated, but is not required. */ /* 2. Alterred source versions must be marked plainly as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or alterred from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stddef.h> /* define NULL */ #include <stdlib.h> /* declare function's prototype */ #include <_heap.h> #include <errno.h> #define EOK 0 /* No errors (non-standard name) */ /* This is a very simple version of an aligned memory allocator. We will * allocate a greater block, so that we can place the aligned block (that is * returned) within it. We use our knowledge about the internal heap * structures to free the unused parts of the bigger block (the two chunks * below and above the aligned block). */ int __fastcall__ posix_memalign (void** memptr, size_t alignment, size_t size) /* Allocate a block of memory with the given "size", which is aligned to a * memory address that is a multiple of "alignment". "alignment" MUST NOT be * zero, and MUST be a power of two; otherwise, this function will return * EINVAL. The function returns ENOMEM if not enough memory is available * to satisfy the request. "memptr" must point to a variable; that variable * will return the address of the allocated memory. Use free() to release that * allocated block. */ { size_t rawsize; size_t uppersize; size_t lowersize; register struct usedblock* b; /* points to raw Block */ register struct usedblock* u; /* points to User block */ register struct usedblock* p; /* Points to upper block */ /* Handle requests for zero-sized blocks */ if (size == 0) { *memptr = NULL; return EINVAL; } /* Test alignment: is it a power of two? There must be only one bit set. */ if (alignment == 0 || (alignment & --alignment) != 0) { *memptr = NULL; return EINVAL; } /* Augment the block size up to the alignment, and allocate memory. * We don't need to account for the additional admin. data that's needed to * manage the used block, because the block returned by malloc() has that * overhead added one time; and, the worst thing that might happen is that * we cannot free the upper and lower blocks. */ b = malloc (size + alignment); /* Handle out-of-memory */ if (b == NULL) { *memptr = NULL; return ENOMEM; } /* Create (and return) a new pointer that points to the user-visible * aligned block. */ u = *memptr = (struct usedblock*) (((unsigned)b + alignment) & ~alignment); /* Get a pointer to the (raw) upper block */ p = (struct usedblock*) ((char*)u + size); /* Get the raw-block pointer, which is located just below the visible * unaligned block. The first word of this raw block is the total size * of the block, including the admin. space. */ b = (b-1)->start; rawsize = b->size; /* Check if we can free the space above the user block. That is the case * if the size of the block is at least sizeof (struct freeblock) bytes, * and the size of the remaining block is at least that size, too. * If the upper block is smaller, then we just will pass it to the caller, * together with the requested aligned block. */ uppersize = rawsize - (lowersize = (char*)p - (char*)b); if (uppersize >= sizeof (struct freeblock) && lowersize >= sizeof (struct freeblock)) { /* Setup the usedblock structure */ p->size = uppersize; p->start = p; /* Generate a pointer to the (upper) user space, and free that block */ free (p + 1); /* Decrease the raw-block size by the amount of space just freed */ rawsize = lowersize; } /* Check if we can free the space below the user block. That is the case * if the size of the block is at least sizeof (struct freeblock) bytes, * and the size of the remaining block is at least that size, too. If the * lower block is smaller, we just will pass it to the caller, together * with the requested aligned block. * Beware: We need an additional struct usedblock, in the lower block, * which is part of the block that is passed back to the caller. */ lowersize = ((char*)u - (char*)b) - sizeof (struct usedblock); if ( lowersize >= sizeof (struct freeblock) && (rawsize - lowersize) >= sizeof (struct freeblock)) { /* b already points to the raw lower-block. * Set up the usedblock structure. */ b->size = lowersize; b->start = b; /* Generate a pointer to the (lower) user space, and free that block */ free (b + 1); /* Decrease the raw-block size by the amount of space just freed */ rawsize -= lowersize; /* Set b to the raw user-block (that will be returned) */ b = u - 1; } /* u points to the user-visible block, while b points to the raw block, * and rawsize contains the length of the raw block. Set up the usedblock * structure, but beware: If we didn't free the lower block, then it is * split; which means that we must use b to write the size, * and u to write the start field. */ b->size = rawsize; (u-1)->start = b; return EOK; }
757
./cc65/libsrc/common/fputc.c
/* * fputc.c * * Ullrich von Bassewitz, 02.06.1998 */ #include <stdio.h> #include <unistd.h> #include "_file.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ int __fastcall__ fputc (int c, register FILE* f) { /* Check if the file is open or if there is an error condition */ if ((f->f_flags & _FOPEN) == 0 || (f->f_flags & (_FERROR | _FEOF)) != 0) { goto ReturnEOF; } /* Write the byte */ if (write (f->f_fd, &c, 1) != 1) { /* Error */ f->f_flags |= _FERROR; ReturnEOF: return EOF; } /* Return the byte written */ return c & 0xFF; }
758
./cc65/libsrc/common/fputs.c
/* * int fputs (const char* s, FILE* f); * * Ullrich von Bassewitz, 11.08.1998 */ #include <stdio.h> #include <string.h> #include <unistd.h> #include "_file.h" int __fastcall__ fputs (const char* s, register FILE* f) { /* Check if the file is open or if there is an error condition */ if ((f->f_flags & _FOPEN) == 0 || (f->f_flags & (_FERROR | _FEOF)) != 0) { return EOF; } /* Write the string */ return write (f->f_fd, s, strlen (s)); }
759
./cc65/libsrc/common/getchar.c
/* * getchar.c * * Ullrich von Bassewitz, 11.12.1998 */ #include <stdio.h> #undef getchar /* This is usually declared as a macro */ /*****************************************************************************/ /* Code */ /*****************************************************************************/ int getchar (void) { return fgetc (stdin); }
760
./cc65/libsrc/common/_scanf.c
/* * _scanf.c * * (c) Copyright 2001-2005, Ullrich von Bassewitz <uz@cc65.org> * 2005-01-24, Greg King <gngking@erols.com> * * This is the basic layer for all scanf-type functions. It should be * rewritten in assembly, at some time in the future. So, some of the code * is not as elegant as it could be. */ #include <stddef.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <string.h> #include <setjmp.h> #include <limits.h> #include <errno.h> #include <ctype.h> /* _scanf() can give EOF to these functions. But, the macroes can't ** understand it; so, they are removed. */ #undef isspace #undef isxdigit #include "_scanf.h" #pragma static-locals(on) /*****************************************************************************/ /* SetJmp return codes */ /*****************************************************************************/ enum { RC_OK, /* setjmp() call */ RC_NOCONV, /* No conversion possible */ RC_EOF /* EOF reached */ }; /*****************************************************************************/ /* Data */ /*****************************************************************************/ static const char* format; /* Copy of function argument */ static const struct scanfdata* D_; /* Copy of function argument */ static va_list ap; /* Copy of function argument */ static jmp_buf JumpBuf; /* "Label" that is used for failures */ static char F; /* Character from format string */ static unsigned CharCount; /* Characters read so far */ static int C; /* Character from input */ static unsigned Width; /* Maximum field width */ static long IntVal; /* Converted int value */ static int Assignments; /* Number of assignments */ static unsigned char IntBytes; /* Number of bytes-1 for int conversions */ /* Flags */ static bool Converted; /* Some object was converted */ static bool Positive; /* Flag for positive value */ static bool NoAssign; /* Suppress assignment */ static bool Invert; /* Do we need to invert the charset? */ static unsigned char CharSet[(1+UCHAR_MAX)/CHAR_BIT]; static const unsigned char Bits[CHAR_BIT] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 }; /* We need C to be 16 bits since we cannot check for EOF otherwise. * Unfortunately, this causes the code to be quite larger, even if for most * purposes, checking the low byte would be enough, since if C is EOF, the * low byte will not match any useful character anyway (at least for the * supported platforms - I know that this is not portable). So the following * macro is used to access just the low byte of C. */ #define CHAR(c) (*((unsigned char*)&(c))) /*****************************************************************************/ /* Character sets */ /*****************************************************************************/ /* We don't want the optimizer to ruin our "perfect" ;-) * assembly code! */ #pragma optimize (push, off) static unsigned FindBit (void) /* Locate the character's bit in the charset array. * < .A - Argument character * > .X - Offset of the byte in the character-set mask * > .A - Bit-mask */ { asm ("pha"); asm ("lsr a"); /* Divide by CHAR_BIT */ asm ("lsr a"); asm ("lsr a"); asm ("tax"); /* Byte's offset */ asm ("pla"); asm ("and #%b", CHAR_BIT-1); asm ("tay"); /* Bit's offset */ asm ("lda %v,y", Bits); return (unsigned) __AX__; } #pragma optimize (pop) static void __fastcall__ AddCharToSet (unsigned char /* C */) /* Set the given bit in the character set */ { FindBit(); asm ("ora %v,x", CharSet); asm ("sta %v,x", CharSet); } #pragma optimize (push, off) static unsigned char IsCharInSet (void) /* Check if the char. is part of the character set. */ { /* Get the character from C. */ asm ("lda #$00"); asm ("ldx %v+1", C); asm ("bne L1"); /* EOF never is in the set */ asm ("lda %v", C); FindBit(); asm ("and %v,x", CharSet); asm ("L1:"); asm ("ldx #$00"); return (unsigned char) __AX__; } #pragma optimize (pop) static void InvertCharSet (void) /* Invert the character set */ { asm ("ldy #%b", sizeof (CharSet) - 1); asm ("L1:"); asm ("lda %v,y", CharSet); asm ("eor #$FF"); asm ("sta %v,y", CharSet); asm ("dey"); asm ("bpl L1"); } /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void PushBack (void) /* Push back the last (unused) character, provided it is not EOF. */ { /* Get the character from C. */ /* Only the high-byte needs to be checked for EOF. */ asm ("ldx %v+1", C); asm ("bne %g", Done); asm ("lda %v", C); /* Put unget()'s first argument on the stack. */ asm ("jsr pushax"); /* Copy D into the zero-page. */ (const struct scanfdata*) __AX__ = D_; asm ("sta ptr1"); asm ("stx ptr1+1"); /* Copy the unget vector to jmpvec. */ asm ("ldy #%b", offsetof (struct scanfdata, unget)); asm ("lda (ptr1),y"); asm ("sta jmpvec+1"); asm ("iny"); asm ("lda (ptr1),y"); asm ("sta jmpvec+2"); /* Load D->data into __AX__. */ asm ("ldy #%b", offsetof (struct scanfdata, data) + 1); asm ("lda (ptr1),y"); asm ("tax"); asm ("dey"); asm ("lda (ptr1),y"); /* Call the unget routine. */ asm ("jsr jmpvec"); /* Take back that character's count. */ asm ("lda %v", CharCount); asm ("bne %g", Yank); asm ("dec %v+1", CharCount); Yank: asm ("dec %v", CharCount); Done: ; } static void ReadChar (void) /* Get an input character, count characters */ { /* Move D to ptr1 */ asm ("lda %v", D_); asm ("ldx %v+1", D_); asm ("sta ptr1"); asm ("stx ptr1+1"); /* Copy the get vector to jmpvec */ asm ("ldy #%b", offsetof (struct scanfdata, get)); asm ("lda (ptr1),y"); asm ("sta jmpvec+1"); asm ("iny"); asm ("lda (ptr1),y"); asm ("sta jmpvec+2"); /* Load D->data into __AX__ */ asm ("ldy #%b", offsetof (struct scanfdata, data) + 1); asm ("lda (ptr1),y"); asm ("tax"); asm ("dey"); asm ("lda (ptr1),y"); /* Call the get routine */ asm ("jsr jmpvec"); /* Assign the result to C */ asm ("sta %v", C); asm ("stx %v+1", C); /* If C is EOF, don't bump the character counter. * Only the high-byte needs to be checked. */ asm ("inx"); asm ("beq %g", Done); /* Must bump CharCount. */ asm ("inc %v", CharCount); asm ("bne %g", Done); asm ("inc %v+1", CharCount); Done: ; } #pragma optimize (push, off) static void __fastcall__ Error (unsigned char /* Code */) /* Does a longjmp using the given code */ { asm ("pha"); (char*) __AX__ = JumpBuf; asm ("jsr pushax"); asm ("pla"); asm ("ldx #>0"); asm ("jmp %v", longjmp); } #pragma optimize (pop) static void CheckEnd (void) /* Stop a scan if it prematurely reaches the end of a string or a file. */ { /* Only the high-byte needs to be checked for EOF. */ asm ("ldx %v+1", C); asm ("beq %g", Done); Error (RC_EOF); Done: ; } static void SkipWhite (void) /* Skip white space in the input and return the first non white character */ { while ((bool) isspace (C)) { ReadChar (); } } #pragma optimize (push, off) static void ReadSign (void) /* Read an optional sign and skip it. Store 1 in Positive if the value is * positive, store 0 otherwise. */ { /* We can ignore the high byte of C here, since if it is EOF, the lower * byte won't match anyway. */ asm ("lda %v", C); asm ("cmp #'-'"); asm ("bne %g", NotNeg); /* Negative value */ asm ("sta %v", Converted); asm ("jsr %v", ReadChar); asm ("lda #$00"); /* Flag as negative */ asm ("beq %g", Store); /* Positive value */ NotNeg: asm ("cmp #'+'"); asm ("bne %g", Pos); asm ("sta %v", Converted); asm ("jsr %v", ReadChar); /* Skip the + sign */ Pos: asm ("lda #$01"); /* Flag as positive */ Store: asm ("sta %v", Positive); } #pragma optimize (pop) static unsigned char __fastcall__ HexVal (char C) /* Convert a digit to a value */ { return (bool) isdigit (C) ? C - '0' : (char) tolower ((int) C) - ('a' - 10); } static void __fastcall__ ReadInt (unsigned char Base) /* Read an integer, and store it into IntVal. */ { unsigned char Val, CharCount = 0; /* Read the integer value */ IntVal = 0L; while ((bool) isxdigit (C) && ++Width != 0 && (Val = HexVal ((char) C)) < Base) { ++CharCount; IntVal = IntVal * (long) Base + (long) Val; ReadChar (); } /* If we didn't convert anything, it's a failure. */ if (CharCount == 0) { Error (RC_NOCONV); } /* Another conversion */ Converted = true; } static void AssignInt (void) /* Assign the integer value in Val to the next argument. The function makes * several non-portable assumptions, to reduce code size: * - signed and unsigned types have the same representation. * - short and int have the same representation. * - all pointer types have the same representation. */ { if (NoAssign == false) { /* Get the next argument pointer */ (void*) __AX__ = va_arg (ap, void*); /* Put the argument pointer into the zero-page. */ asm ("sta ptr1"); asm ("stx ptr1+1"); /* Get the number of bytes-1 to copy */ asm ("ldy %v", IntBytes); /* Assign the integer value */ Loop: asm ("lda %v,y", IntVal); asm ("sta (ptr1),y"); asm ("dey"); asm ("bpl %g", Loop); /* Another assignment */ asm ("inc %v", Assignments); asm ("bne %g", Done); asm ("inc %v+1", Assignments); Done: ; } } static void __fastcall__ ScanInt (unsigned char Base) /* Scan an integer including white space, sign and optional base spec, * and store it into IntVal. */ { /* Skip whitespace */ SkipWhite (); /* Read an optional sign */ ReadSign (); /* If Base is unknown (zero), figure it out */ if (Base == 0) { if (CHAR (C) == '0') { ReadChar (); switch (CHAR (C)) { case 'x': case 'X': Base = 16; Converted = true; ReadChar (); break; default: Base = 8; /* Restart at the beginning of the number because it might * be only a single zero digit (which already was read). */ PushBack (); C = '0'; } } else { Base = 10; } } /* Read the integer value */ ReadInt (Base); /* Apply the sign */ if (Positive == false) { IntVal = -IntVal; } /* Assign the value to the next argument unless suppressed */ AssignInt (); } static char GetFormat (void) /* Pick up the next character from the format string. */ { /* return (F = *format++); */ (const char*) __AX__ = format; asm ("sta regsave"); asm ("stx regsave+1"); ++format; asm ("ldy #0"); asm ("lda (regsave),y"); asm ("ldx #>0"); return (F = (char) __AX__); } int __fastcall__ _scanf (const struct scanfdata* D, const char* format_, va_list ap_) /* This is the routine used to do the actual work. It is called from several * types of wrappers to implement the actual ISO xxscanf functions. */ { register char* S; bool HaveWidth; /* True if a width was given */ bool Match; /* True if a character-set has any matches */ char Start; /* Walks over a range */ /* Place copies of the arguments into global variables. This is not very * nice, but on a 6502 platform it gives better code, since the values * do not have to be passed as parameters. */ D_ = D; format = format_; ap = ap_; /* Initialize variables */ Converted = false; Assignments = 0; CharCount = 0; /* Set up the jump "label". CheckEnd() will use that label when EOF * is reached. ReadInt() will use it when number-conversion fails. */ if ((unsigned char) setjmp (JumpBuf) == RC_OK) { Again: /* Get the next input character */ ReadChar (); /* Walk over the format string */ while (GetFormat ()) { /* Check for a conversion */ if (F != '%') { /* Check for a match */ if ((bool) isspace ((int) F)) { /* Special white space handling: Any whitespace in the * format string matches any amount of whitespace including * none(!). So this match will never fail. */ SkipWhite (); continue; } Percent: /* ### Note: The opposite test (C == F) ** would be optimized into buggy code! */ if (C != (int) F) { /* A mismatch -- we will stop scanning the input, * and return the number of assigned conversions. */ goto NoConv; } /* A match -- get the next input character, and continue. */ goto Again; } else { /* A conversion. Skip the percent sign. */ /* 0. Check for %% */ if (GetFormat () == '%') { goto Percent; } /* 1. Assignment suppression */ NoAssign = (F == '*'); if (NoAssign) { GetFormat (); } /* 2. Maximum field width */ Width = UINT_MAX; HaveWidth = (bool) isdigit (F); if (HaveWidth) { Width = 0; do { /* ### Non portable ### */ Width = Width * 10 + (F & 0x0F); } while ((bool) isdigit (GetFormat ())); } if (Width == 0) { /* Invalid specification */ /* Note: This method of leaving the function might seem * to be crude, but it optimizes very well because * the four exits can share this code. */ _seterrno (EINVAL); Assignments = EOF; PushBack (); return Assignments; } /* Increment-and-test makes better code than test-and-decrement * does. So, change the width into a form that can be used in * that way. */ Width = ~Width; /* 3. Length modifier */ IntBytes = sizeof(int) - 1; switch (F) { case 'h': if (*format == 'h') { IntBytes = sizeof(char) - 1; ++format; } GetFormat (); break; case 'l': if (*format == 'l') { /* Treat long long as long */ ++format; } /* FALLTHROUGH */ case 'j': /* intmax_t */ IntBytes = sizeof(long) - 1; /* FALLTHROUGH */ case 'z': /* size_t */ case 't': /* ptrdiff_t */ /* Same size as int */ case 'L': /* long double - ignore this one */ GetFormat (); } /* 4. Conversion specifier */ switch (F) { /* 'd' and 'u' conversions are actually the same, since the * standard says that even the 'u' modifier allows an * optionally signed integer. */ case 'd': /* Optionally signed decimal integer */ case 'u': ScanInt (10); break; case 'i': /* Optionally signed integer with a base */ ScanInt (0); break; case 'o': /* Optionally signed octal integer */ ScanInt (8); break; case 'x': case 'X': /* Optionally signed hexadecimal integer */ ScanInt (16); break; case 's': /* Whitespace-terminated string */ SkipWhite (); CheckEnd (); /* Is it an input failure? */ Converted = true; /* No, conversion will succeed */ if (NoAssign == false) { S = va_arg (ap, char*); } while (C != EOF && (bool) isspace (C) == false && ++Width) { if (NoAssign == false) { *S++ = C; } ReadChar (); } /* Terminate the string just read */ if (NoAssign == false) { *S = '\0'; ++Assignments; } break; case 'c': /* Fixed-length string, NOT zero-terminated */ if (HaveWidth == false) { /* No width given, default is 1 */ Width = ~1u; } CheckEnd (); /* Is it an input failure? */ Converted = true; /* No, at least 1 char. available */ if (NoAssign == false) { S = va_arg (ap, char*); /* ## This loop is convenient for us, but it isn't * standard C. The standard implies that a failure * shouldn't put anything into the array argument. */ while (++Width) { CheckEnd (); /* Is it a matching failure? */ *S++ = C; ReadChar (); } ++Assignments; } else { /* Just skip as many chars as given */ while (++Width) { CheckEnd (); /* Is it a matching failure? */ ReadChar (); } } break; case '[': /* String using characters from a set */ /* Clear the set */ memset (CharSet, 0, sizeof (CharSet)); /* Skip the left-bracket, and test for inversion. */ Invert = (GetFormat () == '^'); if (Invert) { GetFormat (); } if (F == ']') { /* Empty sets aren't allowed; so, a right-bracket * at the beginning must be a member of the set. */ AddCharToSet (F); GetFormat (); } /* Read the characters that are part of the set */ while (F != '\0' && F != ']') { if (*format == '-') { /* Look ahead at next char. */ /* A range. Get start and end, skip the '-' */ Start = F; ++format; switch (GetFormat ()) { case '\0': case ']': /* '-' as last char means: include '-' */ AddCharToSet (Start); AddCharToSet ('-'); break; default: /* Include all characters * that are in the range. */ while (1) { AddCharToSet (Start); if (Start == F) { break; } ++Start; } /* Get next char after range */ GetFormat (); } } else { /* Just a character */ AddCharToSet (F); /* Get next char */ GetFormat (); } } /* Don't go beyond the end of the format string. */ /* (Maybe, this should mean an invalid specification.) */ if (F == '\0') { --format; } /* Invert the set if requested */ if (Invert) { InvertCharSet (); } /* We have the set in CharSet. Read characters and * store them into a string while they are part of * the set. */ Match = false; if (NoAssign == false) { S = va_arg (ap, char*); } while (IsCharInSet () && ++Width) { if (NoAssign == false) { *S++ = C; } Match = Converted = true; ReadChar (); } /* At least one character must match the set. */ if (Match == false) { goto NoConv; } if (NoAssign == false) { *S = '\0'; ++Assignments; } break; case 'p': /* Pointer, general format is 0xABCD. * %hhp --> zero-page pointer * %hp --> near pointer * %lp --> far pointer */ SkipWhite (); if (CHAR (C) != '0') { goto NoConv; } Converted = true; ReadChar (); switch (CHAR (C)) { case 'x': case 'X': break; default: goto NoConv; } ReadChar (); ReadInt (16); AssignInt (); break; case 'n': /* Store the number of characters consumed so far * (the read-ahead character hasn't been consumed). */ IntVal = (long) (CharCount - (C == EOF ? 0u : 1u)); AssignInt (); /* Don't count it. */ if (NoAssign == false) { --Assignments; } break; case 'S': case 'C': /* Wide characters */ case 'a': case 'A': case 'e': case 'E': case 'f': case 'F': case 'g': case 'G': /* Optionally signed float */ /* Those 2 groups aren't implemented. */ _seterrno (ENOSYS); Assignments = EOF; PushBack (); return Assignments; default: /* Invalid specification */ _seterrno (EINVAL); Assignments = EOF; PushBack (); return Assignments; } } } } else { NoConv: /* Coming here means a failure. If that happens at EOF, with no * conversion attempts, then it is considered an error; otherwise, * the number of assignments is returned (the default behaviour). */ if (C == EOF && Converted == false) { Assignments = EOF; /* Special case: error */ } } /* Put the read-ahead character back into the input stream. */ PushBack (); /* Return the number of conversion-and-assignments. */ return Assignments; }
761
./cc65/libsrc/common/_afailed.c
/* * _afailed.c * * Ullrich von Bassewitz, 06.06.1998 */ #include <stdio.h> #include <stdlib.h> void _afailed (char* file, unsigned line) { fprintf (stderr, "ASSERTION FAILED IN %s(%u)\n", file, line); exit (2); }
762
./cc65/libsrc/common/freopen.c
/* * freopen.c * * Ullrich von Bassewitz, 17.06.1998 */ #include <stdio.h> #include <fcntl.h> #include <errno.h> #include "_file.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ FILE* __fastcall__ freopen (const char* name, const char* mode, FILE* f) { /* Check if the file is open, if so, close it */ if ((f->f_flags & _FOPEN) == 0) { /* File is not open */ return (FILE*) _seterrno (EINVAL); /* File not input */ } /* Close the file. Don't bother setting the flag, it will get * overwritten by _fopen. */ if (close (f->f_fd) < 0) { /* An error occured, errno is already set */ return 0; } /* Open the file and return the descriptor */ return _fopen (name, mode, f); }
763
./cc65/libsrc/common/_longminstr.c
/* * Ullrich von Bassewitz, 2012-11-26 * * Minimum value of a long. Is used in ascii conversions, since this value * has no positive counterpart than can be represented in 32 bits. In C, * since the compiler will convert to the correct character set for the * target platform. */ const unsigned char _longminstr[] = "-2147483648";
764
./cc65/libsrc/common/strtok.c
/* * strtok.c * * Ullrich von Bassewitz, 11.12.1998 */ #include <string.h> /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Memory location that holds the last input */ static char* Last = 0; /*****************************************************************************/ /* Code */ /*****************************************************************************/ char* __fastcall__ strtok (register char* s1, const char* s2) { char c; char* start; /* Use the stored location if called with a NULL pointer */ if (s1 == 0) { s1 = Last; } /* If s1 is empty, there are no more tokens. Return 0 in this case. */ if (*s1 == '\0') { return 0; } /* Search the address of the first element in s1 that equals none * of the characters in s2. */ while ((c = *s1) && strchr (s2, c) != 0) { ++s1; } if (c == '\0') { /* No more tokens found */ Last = s1; return 0; } /* Remember the start of the token */ start = s1; /* Search for the end of the token */ while ((c = *s1) && strchr (s2, c) == 0) { ++s1; } if (c == '\0') { /* Last element */ Last = s1; } else { *s1 = '\0'; Last = s1 + 1; } /* Return the start of the token */ return start; }
765
./cc65/libsrc/common/strtoul.c
#include <limits.h> #include <ctype.h> #include <errno.h> #include <stdlib.h> unsigned long __fastcall__ strtoul (const char* nptr, char** endptr, int base) /* Convert a string to a long unsigned int */ { register const char* S = nptr; unsigned long Val = 0; unsigned char Minus = 0; unsigned char Ovf = 0; unsigned CvtCount = 0; unsigned char DigitVal; unsigned long MaxVal; unsigned char MaxDigit; /* Skip white space */ while (isspace (*S)) { ++S; } /* Check for leading + or - sign */ switch (*S) { case '-': Minus = 1; /* FALLTHROUGH */ case '+': ++S; } /* If base is zero, we may have a 0 or 0x prefix. If base is 16, we may * have a 0x prefix. */ if (base == 0) { if (*S == '0') { ++S; if (*S == 'x' || *S == 'X') { ++S; base = 16; } else { base = 8; } } else { base = 10; } } else if (base == 16 && *S == '0' && (S[1] == 'x' || S[1] == 'X')) { S += 2; } /* Determine the maximum valid number and (if the number is equal to this * value) the maximum valid digit. */ MaxDigit = ULONG_MAX % base; MaxVal = ULONG_MAX / base; /* Convert the number */ while (1) { /* Convert the digit into a numeric value */ if (isdigit (*S)) { DigitVal = *S - '0'; } else if (isupper (*S)) { DigitVal = *S - ('A' - 10); } else if (islower (*S)) { DigitVal = *S - ('a' - 10); } else { /* Unknown character */ break; } /* Don't accept a character that doesn't match base */ if (DigitVal >= base) { break; } /* Don't accept anything that makes the final value invalid */ if (Val > MaxVal || (Val == MaxVal && DigitVal > MaxDigit)) { Ovf = 1; } /* Calculate the next value if digit is not invalid */ if (Ovf == 0) { Val = (Val * base) + DigitVal; ++CvtCount; } /* Next character from input */ ++S; } /* Store the end pointer. If no conversion was performed, the value of * nptr is returned in endptr. */ if (endptr) { if (CvtCount > 0) { *endptr = (char*) S - 1; } else { *endptr = (char*) nptr; } } /* Handle overflow */ if (Ovf) { _seterrno (ERANGE); return ULONG_MAX; } /* Return the result */ if (Minus) { return (unsigned long) -(long)Val; } else { return Val; } }
766
./cc65/libsrc/common/_hextab.c
/* * Ullrich von Bassewitz, 11.08.1998 * * Hex conversion table. Must be in C since the compiler will convert * to the correct character set for the target platform. */ const unsigned char _hextab [16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
767
./cc65/libsrc/common/ftell.c
/* * ftell.c * * Christian Groessler, 2000-08-07 * Ullrich von Bassewitz, 2004-05-13 */ #include <stdio.h> #include <errno.h> #include <unistd.h> #include "_file.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ long __fastcall__ ftell (register FILE* f) { long pos; /* Is the file open? */ if ((f->f_flags & _FOPEN) == 0) { _seterrno (EINVAL); /* File not open */ return -1L; } /* Call the low level function */ pos = lseek (f->f_fd, 0L, SEEK_CUR); /* If we didn't have an error, correct the return value in case we have * a pushed back character. */ if (pos > 0 && (f->f_flags & _FPUSHBACK)) { --pos; } /* -1 for error, comes from lseek() */ return pos; }
768
./cc65/libsrc/common/gets.c
/* * gets.c * * Ullrich von Bassewitz, 11.08.1998 */ #include <stdio.h> #include "_file.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ char* __fastcall__ gets (char* s) { register char* p = s; int c; unsigned i = 0; while (1) { /* Get next character */ if ((c = fgetc (stdin)) == EOF) { /* Error or EOF */ *p = '\0'; if (stdin->f_flags & _FERROR) { /* ERROR */ return 0; } else { /* EOF */ if (i) { return s; } else { return 0; } } } /* One char more. Newline ends the input */ if ((char) c == '\n') { *p = '\0'; break; } else { *p = c; ++p; ++i; } } /* Done */ return s; }
769
./cc65/libsrc/common/timezone.c
/*****************************************************************************/ /* */ /* timezone.c */ /* */ /* Timezone specification */ /* */ /* */ /* */ /* (C) 2002 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@musoftware.de */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <time.h> /*****************************************************************************/ /* Data */ /*****************************************************************************/ struct _timezone _tz = { 0, /* True if daylight savings time active */ 0, /* Number of seconds behind UTC */ "UTC", /* Name of timezone, e.g. CET */ "UTC" /* Name when daylight true, e.g. CEST */ };
770
./cc65/libsrc/common/fgetc.c
/* * fgetc.c * * (C) Copyright 1998, 2002 Ullrich von Bassewitz (uz@cc65.org) * */ #include <stdio.h> #include <unistd.h> #include "_file.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ int __fastcall__ fgetc (register FILE* f) { unsigned char c; /* Check if the file is open or if there is an error condition */ if ((f->f_flags & _FOPEN) == 0 || (f->f_flags & (_FERROR | _FEOF)) != 0) { return EOF; } /* If we have a pushed back character, return it */ if (f->f_flags & _FPUSHBACK) { f->f_flags &= ~_FPUSHBACK; return f->f_pushback; } /* Read one byte */ switch (read (f->f_fd, &c, 1)) { case -1: /* Error */ f->f_flags |= _FERROR; return EOF; case 0: /* EOF */ f->f_flags |= _FEOF; return EOF; default: /* Char read */ return c; } }
771
./cc65/libsrc/common/strtol.c
#include <limits.h> #include <ctype.h> #include <errno.h> #include <stdlib.h> long __fastcall__ strtol (const char* nptr, char** endptr, int base) /* Convert a string to a long int */ { register const char* S = nptr; unsigned long Val = 0; unsigned char Minus = 0; unsigned char Ovf = 0; unsigned CvtCount = 0; unsigned char DigitVal; unsigned long MaxVal; unsigned char MaxDigit; /* Skip white space */ while (isspace (*S)) { ++S; } /* Check for leading + or - sign */ switch (*S) { case '-': Minus = 1; /* FALLTHROUGH */ case '+': ++S; } /* If base is zero, we may have a 0 or 0x prefix. If base is 16, we may * have a 0x prefix. */ if (base == 0) { if (*S == '0') { ++S; if (*S == 'x' || *S == 'X') { ++S; base = 16; } else { base = 8; } } else { base = 10; } } else if (base == 16 && *S == '0' && (S[1] == 'x' || S[1] == 'X')) { S += 2; } /* Determine the maximum valid number and (if the number is equal to this * value) the maximum valid digit. */ if (Minus) { MaxVal = LONG_MIN; } else { MaxVal = LONG_MAX; } MaxDigit = MaxVal % base; MaxVal /= base; /* Convert the number */ while (1) { /* Convert the digit into a numeric value */ if (isdigit (*S)) { DigitVal = *S - '0'; } else if (isupper (*S)) { DigitVal = *S - ('A' - 10); } else if (islower (*S)) { DigitVal = *S - ('a' - 10); } else { /* Unknown character */ break; } /* Don't accept a character that doesn't match base */ if (DigitVal >= base) { break; } /* Don't accept anything that makes the final value invalid */ if (Val > MaxVal || (Val == MaxVal && DigitVal > MaxDigit)) { Ovf = 1; } /* Calculate the next value if digit is not invalid */ if (Ovf == 0) { Val = (Val * base) + DigitVal; ++CvtCount; } /* Next character from input */ ++S; } /* Store the end pointer. If no conversion was performed, the value of * nptr is returned in endptr. */ if (endptr) { if (CvtCount > 0) { *endptr = (char*) S - 1; } else { *endptr = (char*) nptr; } } /* Handle overflow */ if (Ovf) { _seterrno (ERANGE); if (Minus) { return LONG_MIN; } else { return LONG_MAX; } } /* Return the result */ if (Minus) { return -(long)Val; } else { return Val; } }
772
./cc65/libsrc/common/locale.c
/* * locale.c * * Ullrich von Bassewitz, 11.12.1998 */ #include <locale.h> #include <limits.h> /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* For memory efficiency use a separate empty string */ static char EmptyString [] = ""; static struct lconv lc = { EmptyString, /* currency_symbol */ ".", /* decimal_point */ EmptyString, /* grouping */ EmptyString, /* int_curr_symbol */ EmptyString, /* mon_decimal_point */ EmptyString, /* mon_grouping */ EmptyString, /* mon_thousands_sep */ EmptyString, /* negative_sign */ EmptyString, /* positive_sign */ EmptyString, /* thousands_sep */ CHAR_MAX, /* frac_digits */ CHAR_MAX, /* int_frac_digits */ CHAR_MAX, /* n_cs_precedes */ CHAR_MAX, /* n_sep_by_space */ CHAR_MAX, /* n_sign_posn */ CHAR_MAX, /* p_cs_precedes */ CHAR_MAX, /* p_sep_by_space */ CHAR_MAX, /* p_sign_posn */ }; /*****************************************************************************/ /* Code */ /*****************************************************************************/ struct lconv* localeconv (void) { return &lc; } char* __fastcall__ setlocale (int, const char* locale) { if (locale == 0 || (locale [0] == 'C' && locale [1] == '\0') || locale [0] == '\0') { /* No change, or value already set, our locale is the "C" locale */ return "C"; } else { /* Cannot set this one */ return 0; } }
773
./cc65/libsrc/common/fseek.c
/* * fseek.c * * Christian Groessler, 2000-08-07 * Ullrich von Bassewitz, 2004-05-12 */ #include <stdio.h> #include <errno.h> #include <unistd.h> #include "_file.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ int __fastcall__ fseek (register FILE* f, long offset, int whence) { long res; /* Is the file open? */ if ((f->f_flags & _FOPEN) == 0) { _seterrno (EINVAL); /* File not open */ return -1; } /* If we have a pushed back character, and whence is relative to the * current position, correct the offset. */ if ((f->f_flags & _FPUSHBACK) && whence == SEEK_CUR) { --offset; } /* Do the seek */ res = lseek(f->f_fd, offset, whence); /* If the seek was successful. Discard any effects of the ungetc function, * and clear the end-of-file indicator. Otherwise set the error indicator * on the stream, and return -1. We will check for >= 0 here, because that * saves some code, and we don't have files with 2 gigabytes in size * anyway:-) */ if (res >= 0) { f->f_flags &= ~(_FEOF | _FPUSHBACK); return 0; } else { f->f_flags |= _FERROR; return -1; } }
774
./cc65/libsrc/common/sleep.c
/* * sleep.c * * Stefan Haubenthal, 2003-06-11 * Ullrich von Bassewitz, 2003-06-12 * */ #include <time.h> #include <unistd.h> /* We cannot implement this function without a working clock function */ #if defined(CLOCKS_PER_SEC) unsigned __fastcall__ sleep (unsigned wait) { clock_t goal = clock () + ((clock_t) wait) * CLOCKS_PER_SEC; while ((long) (goal - clock ()) > 0) ; return 0; } #endif
775
./cc65/libsrc/common/puts.c
/* * puts.c * * Ullrich von Bassewitz, 11.08.1998 */ #include <stdio.h> #include <string.h> #include <unistd.h> #include "_file.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ int __fastcall__ puts (const char* s) { static char nl = '\n'; /* Assume stdout is always open */ if (write (stdout->f_fd, s, strlen (s)) < 0 || write (stdout->f_fd, &nl, 1) < 0) { stdout->f_flags |= _FERROR; return -1; } /* Done */ return 0; }
776
./cc65/libsrc/common/gmtime.c
/*****************************************************************************/ /* */ /* gmtime.c */ /* */ /* Convert calendar time into broken down time in UTC */ /* */ /* */ /* */ /* (C) 2002 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@musoftware.de */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <time.h> /*****************************************************************************/ /* Code */ /*****************************************************************************/ struct tm* __fastcall__ gmtime (const time_t* timep) { time_t t; /* Check for a valid time spec */ if (timep == 0) { return 0; } /* Get the time and correct for the time zone offset */ t = *timep + _tz.timezone; /* Use localtime for conversion */ return localtime (&t); }
777
./cc65/libsrc/common/errormsg.c
/* * errormsg.c * * Ullrich von Bassewitz, 17.05.2000 * * Must be a C function, since we have otherwise problems with the different * character sets. */ const char* const _sys_errlist[] = { "Unknown error", /* 0 */ "No such file or directory", /* ENOENT */ "Out of memory", /* ENOMEM */ "Permission denied", /* EACCES */ "No such device", /* ENODEV */ "Too many open files", /* EMFILE */ "Device or resource busy", /* EBUSY */ "Invalid argument", /* EINVAL */ "No space left on device", /* ENOSPC */ "File exists", /* EEXIST */ "Try again", /* EAGAIN */ "I/O error", /* EIO */ "Interrupted system call", /* EINTR */ "Function not implemented", /* ENOSYS */ "Illegal seek", /* ESPIPE */ "Range error", /* ERANGE */ "Bad file number", /* EBADF */ "Unknown OS error code", /* EUNKNOWN */ };
778
./cc65/libsrc/common/qsort.c
/* * qsort.c * * Ullrich von Bassewitz, 09.12.1998 */ #include <stdlib.h> static void QuickSort (register unsigned char* Base, int Lo, int Hi, register size_t Size, int (*Compare)(const void*, const void*)) /* Internal recursive function. Works with ints, but this shouldn't be * a problem. */ { int I, J; /* Quicksort */ while (Hi > Lo) { I = Lo + Size; J = Hi; while (I <= J) { while (I <= J && Compare (Base + Lo, Base + I) >= 0) { I += Size; } while (I <= J && Compare (Base + Lo, Base + J) < 0) { J -= Size; } if (I <= J) { _swap (Base + I, Base + J, Size); I += Size; J -= Size; } } if (J != Lo) { _swap (Base + J, Base + Lo, Size); } if (((unsigned) J) * 2 > (Hi + Lo)) { QuickSort (Base, J + Size, Hi, Size, Compare); Hi = J - Size; } else { QuickSort (Base, Lo, J - Size, Size, Compare); Lo = J + Size; } } } void __fastcall__ qsort (void* base, size_t nmemb, size_t size, int (*compare)(const void*, const void*)) /* Quicksort implementation */ { if (nmemb > 1) { QuickSort (base, 0, (nmemb-1) * size, size, compare); } }
779
./cc65/libsrc/common/_poserror.c
/*****************************************************************************/ /* */ /* _poserror.c */ /* */ /* Output a system dependent error code */ /* */ /* */ /* */ /* (C) 2003 Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> #include <errno.h> void __fastcall__ _poserror (const char* msg) { /* Fetch the message that corresponds to _oserror */ const char* errormsg = _stroserror (_oserror); /* Different output depending on msg */ if (msg) { fprintf (stderr, "%s: %s\n", msg, errormsg); } else { fprintf (stderr, "%s\n", errormsg); } }
780
./cc65/libsrc/common/system.c
/* * system.c * * Stefan Haubenthal, 2003-05-26 * Ullrich von Bassewitz, 2003-05-27 */ #include <stdio.h> #include <stdlib.h> int __fastcall__ system (const char* s) { if (s == NULL) { return 0; /* no shell */ } else { return -1; /* always fail */ } }
781
./cc65/libsrc/common/fdopen.c
/* * fdopen.c * * Ullrich von Bassewitz, 17.06.1998 */ #include <stdio.h> #include <fcntl.h> #include <errno.h> #include "_file.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ FILE* __fastcall__ fdopen (int handle, const char* /*mode*/) { register FILE* f; /* Find a free file slot */ if ((f = _fdesc ())) { /* Insert the handle, and return the descriptor */ f->f_fd = handle; f->f_flags = _FOPEN; } else { /* No slots */ _seterrno (EMFILE); /* Too many files */ } /* Return the file descriptor */ return f; }
782
./cc65/libsrc/common/rewind.c
/* * rewind.c * * Christian Groessler, 07-Aug-2000 */ #include <stdio.h> /*****************************************************************************/ /* Code */ /*****************************************************************************/ void __fastcall__ rewind (FILE* f) { fseek(f, 0L, SEEK_SET); clearerr(f); }
783
./cc65/libsrc/common/fsetpos.c
/* * fsetpos.c * * Christian Groessler, 07-Aug-2000 */ #include <stdio.h> /*****************************************************************************/ /* Code */ /*****************************************************************************/ int __fastcall__ fsetpos (FILE* f, const fpos_t *pos) { return fseek (f, (fpos_t)*pos, SEEK_SET); }
784
./cc65/libsrc/common/abort.c
/* * abort.c * * Ullrich von Bassewitz, 02.06.1998 */ #include <stdio.h> #include <stdlib.h> #include <signal.h> void abort (void) { raise (SIGABRT); fputs ("ABNORMAL PROGRAM TERMINATION\n", stderr); exit (3); }
785
./cc65/libsrc/common/mktime.c
/*****************************************************************************/ /* */ /* mktime.c */ /* */ /* Make calendar time from broken down time and cleanup */ /* */ /* */ /* */ /* (C) 2002 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@musoftware.de */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <limits.h> #include <stdlib.h> #include <time.h> /*****************************************************************************/ /* Data */ /*****************************************************************************/ #define JANUARY 0 #define FEBRUARY 1 #define DECEMBER 11 #define JAN_1_1970 4 /* 1/1/1970 is a thursday */ static const unsigned char MonthLength [] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; static const unsigned MonthDays [] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; /*****************************************************************************/ /* Code */ /*****************************************************************************/ static unsigned char __fastcall__ IsLeapYear (unsigned Year) /* Returns 1 if the given year is a leap year */ { return (((Year % 4) == 0) && ((Year % 100) != 0 || (Year % 400) == 0)); } time_t __fastcall__ mktime (register struct tm* TM) /* Make a time in seconds since 1/1/1970 from the broken down time in TM. * A call to mktime does also correct the time in TM to contain correct * values. */ { register div_t D; int Max; unsigned DayCount; /* Check if TM is valid */ if (TM == 0) { /* Invalid data */ goto Error; } /* Adjust seconds. */ D = div (TM->tm_sec, 60); TM->tm_sec = D.rem; /* Adjust minutes */ if (TM->tm_min + D.quot < 0) { goto Error; } TM->tm_min += D.quot; D = div (TM->tm_min, 60); TM->tm_min = D.rem; /* Adjust hours */ if (TM->tm_hour + D.quot < 0) { goto Error; } TM->tm_hour += D.quot; D = div (TM->tm_hour, 24); TM->tm_hour = D.rem; /* Adjust days */ if (TM->tm_mday + D.quot < 0) { goto Error; } TM->tm_mday += D.quot; /* Adjust month and year. This is an iterative process, since changing * the month will change the allowed days for this month. */ while (1) { /* Make sure, month is in the range 0..11 */ D = div (TM->tm_mon, 12); TM->tm_mon = D.rem; if (TM->tm_year + D.quot < 0) { goto Error; } TM->tm_year += D.quot; /* Now check if mday is in the correct range, if not, correct month * and eventually year and repeat the process. */ if (TM->tm_mon == FEBRUARY && IsLeapYear (TM->tm_year + 1900)) { Max = 29; } else { Max = MonthLength[TM->tm_mon]; } if (TM->tm_mday > Max) { /* Must correct month and eventually, year */ if (TM->tm_mon == DECEMBER) { TM->tm_mon = JANUARY; ++TM->tm_year; } else { ++TM->tm_mon; } TM->tm_mday -= Max; } else { /* Done */ break; } } /* Ok, all time/date fields are now correct. Calculate the days in this * year. */ TM->tm_yday = MonthDays[TM->tm_mon] + TM->tm_mday - 1; if (TM->tm_mon > FEBRUARY && IsLeapYear (TM->tm_year + 1900)) { ++TM->tm_yday; } /* Calculate days since 1/1/1970. In the complete epoch (1/1/1970 to * somewhere in 2038) all years dividable by 4 are leap years, so * dividing by 4 gives the days that must be added cause of leap years. * (and the last leap year before 1970 was 1968) */ DayCount = ((unsigned) (TM->tm_year-70)) * 365U + (((unsigned) (TM->tm_year-(68+1))) / 4) + TM->tm_yday; /* Calculate the weekday */ TM->tm_wday = (JAN_1_1970 + DayCount) % 7; /* No (US) daylight saving (for now) */ TM->tm_isdst = 0; /* Return seconds since 1970 */ return DayCount * 86400UL + ((unsigned) TM->tm_hour) * 3600UL + ((unsigned) TM->tm_min) * 60U + ((unsigned) TM->tm_sec); Error: /* Error exit */ return (time_t) -1L; }
786
./cc65/libsrc/common/realloc.c
/*****************************************************************************/ /* */ /* realloc.c */ /* */ /* Change the size of an allocated memory block */ /* */ /* */ /* */ /* (C) 1998-2004 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@musoftware.de */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> #include <string.h> #include <_heap.h> void* __fastcall__ realloc (void* block, register size_t size) { register struct usedblock* b; struct usedblock* newblock; unsigned oldsize; unsigned newhptr; /* Check the block parameter */ if (!block) { /* Block is NULL, same as malloc */ return malloc (size); } /* Check the size parameter */ if (size == 0) { /* Block is not NULL, but size is: free the block */ free (block); return 0; } /* Make the internal used size from the given size */ size += HEAP_ADMIN_SPACE; if (size < sizeof (struct freeblock)) { size = sizeof (struct freeblock); } /* The word below the user block contains a pointer to the start of the * raw memory block. The first word of this raw memory block is the full * size of the block. Get a pointer to the real block, get the old block * size. */ b = (((struct usedblock*) block) - 1)->start; oldsize = b->size; /* Is the block at the current heap top? */ if (((unsigned) b) + oldsize == ((unsigned) _heapptr)) { /* Check if we've enough memory at the heap top */ newhptr = ((unsigned) _heapptr) - oldsize + size; if (newhptr <= ((unsigned) _heapend)) { /* Ok, there's space enough */ _heapptr = (unsigned*) newhptr; b->size = size; b->start = b; return block; } } /* The given block was not located on top of the heap, or there's no * room left. Try to allocate a new block and copy the data. */ if (newblock = malloc (size)) { /* Adjust the old size to the user visible portion */ oldsize -= HEAP_ADMIN_SPACE; /* If the new block is larger than the old one, copy the old * data only */ if (size > oldsize) { size = oldsize; } /* Copy the block data */ memcpy (newblock, block, size); free (block); } return newblock; }
787
./cc65/libsrc/common/strftime.c
/*****************************************************************************/ /* */ /* strftime.c */ /* */ /* Convert broken down time to a string in a user specified format */ /* */ /* */ /* */ /* (C) 2002 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@musoftware.de */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> #include <stdio.h> #include <time.h> /* Use static local variables for speed */ #pragma static-locals (on); /*****************************************************************************/ /* Code */ /*****************************************************************************/ size_t __fastcall__ strftime (char* buf, size_t bufsize, const char* format, const struct tm* tm) { static const char* days[7] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; static const char* months[12] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; unsigned count; unsigned len; char c; char arg[40]; const char* argptr; /* Copy until we reach the end of the format string or a format specifier */ count = 0; while (1) { if (count >= bufsize) { /* Not enough buffer space available */ return 0; } if ((c = *format++) == '\0') { /* End of format string reached */ *buf = '\0'; return count; } if (c == '%') { /* Format specifier */ argptr = arg; switch (*format++) { case '%': arg[0] = '%'; arg[1] = '\0'; break; case 'A': argptr = days[tm->tm_wday]; break; case 'B': argptr = months[tm->tm_mon]; break; case 'D': sprintf (arg, "%02d/%02d/%02d", tm->tm_mon + 1, tm->tm_mday, tm->tm_year % 100); break; case 'F': /* C99 */ sprintf (arg, "%04d-%02d-%02d", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday); break; case 'H': sprintf (arg, "%02d", tm->tm_hour); break; case 'I': sprintf (arg, "%02d", tm->tm_hour % 12); break; case 'M': sprintf (arg, "%02d", tm->tm_min); break; case 'P': /* GNU extension */ argptr = (tm->tm_hour >= 12)? "pm" : "am"; break; case 'S': sprintf (arg, "%02d", tm->tm_sec); break; case 'U': sprintf (arg, "%02d", (tm->tm_yday + 7 - tm->tm_wday) / 7); break; case 'W': sprintf (arg, "%02d", (tm->tm_yday + 7 - (tm->tm_wday? tm->tm_wday - 1 : 6)) / 7); break; case 'X': sprintf (arg, "%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec); break; case 'Y': sprintf (arg, "%4d", tm->tm_year + 1900); break; case 'Z': argptr = tm->tm_isdst? _tz.dstname : _tz.tzname; break; case 'a': sprintf (arg, "%.3s", days[tm->tm_wday]); break; case 'b': sprintf (arg, "%.3s", months[tm->tm_mon]); break; case 'c': sprintf (arg, "%.3s %.3s%3d %02d:%02d:%02d %d", days[tm->tm_wday], months[tm->tm_mon], tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, tm->tm_year + 1900); break; case 'd': sprintf (arg, "%02d", tm->tm_mday); break; case 'j': sprintf (arg, "%03d", tm->tm_yday + 1); break; case 'm': sprintf (arg, "%02d", tm->tm_mon + 1); break; case 'p': argptr = (tm->tm_hour >= 12)? "PM" : "AM"; break; case 'w': sprintf (arg, "%d", tm->tm_wday); break; case 'x': sprintf (arg, "%04d-%02d-%02d", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday); break; case 'y': sprintf (arg, "%02d", tm->tm_year % 100); break; default: /* Unknown format specifier, convert to empty string */ arg[0] = '\0'; break; } /* Check if we have enough space to copy the argument string */ len = strlen (argptr); count += len; if (count < bufsize) { memcpy (buf, argptr, len); buf += len; } } else { /* No format character, just copy */ *buf++ = c; ++count; } } }
788
./cc65/libsrc/common/strxfrm.c
/* * strxfrm.c * * Ullrich von Bassewitz, 11.12.1998 */ #include <string.h> size_t __fastcall__ strxfrm (char* dest, const char* src, size_t count) { strncpy (dest, src, count); return strlen (src); }
789
./cc65/libsrc/geos-apple/targetutil/convert.c
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <dirent.h> #include <device.h> #include <dio.h> unsigned char info_signature[3] = {3, 21, 63 | 0x80}; dhandle_t dhandle; struct dir_entry_t { struct { unsigned name_length :4; unsigned storage_type :4; } storage_length; char file_name[15]; unsigned char file_type; unsigned key_pointer; unsigned blocks_used; unsigned char size[3]; unsigned long creation; unsigned char version; unsigned char min_version; unsigned char access; unsigned aux_type; unsigned long last_mod; unsigned header_pointer; }* dir_entry; union { unsigned char bytes[512]; struct { unsigned prev_block; unsigned next_block; unsigned char entries[1]; } content; } dir_block; union { unsigned char bytes[512]; struct { unsigned char addr_lo[254]; unsigned char size_lo[2]; unsigned char addr_hi[254]; unsigned char size_hi[2]; } content; } index_block, master_block, vlir_block; union { unsigned char bytes[512]; struct { unsigned reserved; unsigned char info_block[254]; unsigned char vlir_records[128]; struct dir_entry_t dir_entry; } content; } header_block; static void err_exit(char *operation, unsigned char oserr) { if (oserr) { fprintf(stderr, "%s - err:%02x - %s", operation, (int)_oserror, _stroserror(_oserror)); } else { fprintf(stderr, "%s", operation); } getchar(); exit(EXIT_FAILURE); } static unsigned get_dir_entry(char* p_name) { char* d_name; char* f_name; size_t f_namelen; DIR* dir; struct dirent* dirent; unsigned cur_addr; unsigned char entry_length; unsigned char entries_per_block; unsigned char cur_entry; /* Split path name into directory name and file name */ f_name = strrchr(p_name, '/'); if (f_name) { d_name = p_name; *f_name++ = '\0'; } else { d_name = "."; f_name = p_name; } f_namelen = strlen(f_name); /* Start with high level functions to get handling of relative path and current drive for free */ dir = opendir(d_name); if (!dir) { err_exit("opendir", 1); } dirent = readdir(dir); if (!dirent) { err_exit("readdir", 1); } /* Field header_pointer directly follows field last_mod */ cur_addr = *(unsigned*)(&dirent->d_mtime.hour + 1); dhandle = dio_open(getcurrentdevice()); if (!dhandle) { err_exit("dio_open", 1); } if (dio_read(dhandle, cur_addr, &dir_block)) { err_exit("dio_read.1", 1); } /* Get directory entry infos from directory header */ entry_length = dir_block.bytes[0x23]; entries_per_block = dir_block.bytes[0x24]; /* Skip directory header entry */ cur_entry = 1; do { /* Search for next active directory entry */ do { /* Check if next directory block is necessary */ if (cur_entry == entries_per_block) { /* Check if another directory block is present */ cur_addr = dir_block.content.next_block; if (!cur_addr) { _mappederrno(0x46); err_exit("dio_read.2", 1); } /* Read next directory block */ if (dio_read(dhandle, cur_addr, &dir_block)) { err_exit("dio_read.3", 1); } /* Start with first entry in next block */ cur_entry = 0; } /* Compute pointer to current entry */ dir_entry = (struct dir_entry_t*)(dir_block.content.entries + cur_entry * entry_length); /* Switch to next entry */ ++cur_entry; } while (!dir_entry->storage_length.storage_type); } while (dir_entry->storage_length.name_length != f_namelen || strncasecmp(dir_entry->file_name, f_name, f_namelen)); return cur_addr; } int main(int argc, char* argv[]) { char input[80]; char* p_name; unsigned dir_addr; unsigned header_addr; unsigned char index; unsigned long size; if (argc > 1) { p_name = argv[1]; } else { printf("\n" "Apple GEOS Convert 1.0\n" "----------------------\n" "\n" "Pathname:"); p_name = gets(input); } dir_addr = get_dir_entry(p_name); /* Read index block */ if (dio_read(dhandle, dir_entry->key_pointer, &index_block)) { err_exit("dio_read.4", 1); } /* First pointer is header block */ header_addr = index_block.content.addr_lo[0] | index_block.content.addr_hi[0] << 8; /* Read header block */ if (dio_read(dhandle, header_addr, &header_block)) { err_exit("dio_read.5", 1); } /* Do some sanity check */ for (index = 0; index < sizeof(info_signature); ++index) { if (header_block.content.info_block[index] != info_signature[index]) { err_exit("file signature mismatch", 0); } } /* Check ProDOS storage type in directory entry template */ if (header_block.content.dir_entry.storage_length.storage_type == 2) { /* ProDOS sapling file means GEOS Sequential file*/ printf("\nSequential file\n"); /* Remove header block pointer from pointer list */ memmove(&index_block.content.addr_lo[0], &index_block.content.addr_lo[1], sizeof(index_block.content.addr_lo) - 1); memmove(&index_block.content.addr_hi[0], &index_block.content.addr_hi[1], sizeof(index_block.content.addr_hi) - 1); /* Get file size from ProDOS directory entry template */ size = (unsigned long)(header_block.content.dir_entry.size[0]) | (unsigned long)(header_block.content.dir_entry.size[1]) << 8 | (unsigned long)(header_block.content.dir_entry.size[2]) << 16; } else { /* ProDOS tree file means GEOS VLIR file */ unsigned vlir_addr; unsigned long vlir_size; unsigned char vlir_blocks; unsigned char record = 0; printf("\nVLIR file\n"); /* Skip header block pointer */ index = 1; size = 0; while (1) { /* Get next VLIR index pointer from index block */ vlir_addr = index_block.content.addr_lo[index] | index_block.content.addr_hi[index] << 8; ++index; /* Check for end of pointer list */ if (vlir_addr == 0) { break; } /* Check for empty VLIRs */ while (header_block.content.vlir_records[record] == 0xFF) { /* Add empty VLIR index pointer to to master index block */ master_block.content.addr_lo[record] = 0xFF; master_block.content.addr_hi[record] = 0xFF; ++record; } /* Add VLIR index pointer to master index block */ master_block.content.addr_lo[record] = (unsigned char)(vlir_addr ); master_block.content.addr_hi[record] = (unsigned char)(vlir_addr >> 8); ++record; /* Read VLIR index block */ if (dio_read(dhandle, vlir_addr, &vlir_block)) { err_exit("dio_read.6", 1); } /* Get VLIR size from VLIR index block */ vlir_size = (unsigned long)(vlir_block.content.size_lo[1]) | (unsigned long)(vlir_block.content.size_hi[1]) << 8 | (unsigned long)(vlir_block.content.size_lo[0]) << 16 | (unsigned long)(vlir_block.content.size_hi[0]) << 24; printf("VLIR %u size %lu bytes\n", record - 1, vlir_size); /* Compute VLIR block size */ vlir_blocks = (unsigned char)((vlir_size + 511) / 512); /* Copy VLIR block pointers from index block to VLIR index block */ memcpy(&vlir_block.content.addr_lo[0], &index_block.content.addr_lo[index], vlir_blocks); memcpy(&vlir_block.content.addr_hi[0], &index_block.content.addr_hi[index], vlir_blocks); index += vlir_blocks; /* Write back VLIR index block */ if (dio_write(dhandle, vlir_addr, &vlir_block)) { err_exit("dio_write.1", 1); } /* Add VLIR size to file size */ size += vlir_size; } /* Replace (by now completely read) index block with (by now completely created) master index block */ index_block = master_block; } printf("File size %lu bytes\n\n", size); /* Set file size in index block */ index_block.content.size_lo[1] = (unsigned char)(size ); index_block.content.size_hi[1] = (unsigned char)(size >> 8); index_block.content.size_lo[0] = (unsigned char)(size >> 16); index_block.content.size_hi[0] = (unsigned char)(size >> 24); /* Write index block */ if (dio_write(dhandle, dir_entry->key_pointer, &index_block)) { err_exit("dio_write.2", 1); } /* Copy selected fields from directory entry template to directory block */ dir_entry->storage_length = header_block.content.dir_entry.storage_length; memcpy(dir_entry->file_name, header_block.content.dir_entry.file_name, 15); dir_entry->file_type = header_block.content.dir_entry.file_type; dir_entry->size[0] = (unsigned char)(size ); dir_entry->size[1] = (unsigned char)(size >> 8); dir_entry->size[2] = (unsigned char)(size >> 16); dir_entry->creation = header_block.content.dir_entry.creation; dir_entry->version = header_block.content.dir_entry.version; dir_entry->min_version = header_block.content.dir_entry.min_version; dir_entry->aux_type = header_addr; dir_entry->last_mod = header_block.content.dir_entry.last_mod; /* Write directory block */ if (dio_write(dhandle, dir_addr, &dir_block)) { err_exit("dio_write.3", 1); } /* We're done */ if (dio_close(dhandle)) { err_exit("dio_close", 1); } printf("Convert to '%.*s' successful", dir_entry->storage_length.name_length, dir_entry->file_name); getchar(); return EXIT_SUCCESS; }
790
./cc65/libsrc/apple2/rewinddir.c
/*****************************************************************************/ /* */ /* rewinddir.c */ /* */ /* Reset directory stream */ /* */ /* */ /* */ /* (C) 2005 Oliver Schmidt, <ol.sc@web.de> */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <unistd.h> #include <string.h> #include <dirent.h> #include "dir.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ void __fastcall__ rewinddir (register DIR* dir) { /* Rewind directory file */ if (lseek (dir->fd, 0, SEEK_SET)) { /* Read directory key block */ if (read (dir->fd, dir->block.bytes, sizeof (dir->block)) == sizeof (dir->block)) { /* Skip directory header entry */ dir->current_entry = 1; /* Return success */ return; } } /* Assert that no subsequent readdir() finds an active entry */ memset (dir->block.bytes, 0, sizeof (dir->block)); /* Return failure */ }
791
./cc65/libsrc/apple2/readdir.c
/*****************************************************************************/ /* */ /* readdir.c */ /* */ /* Read directory entry */ /* */ /* */ /* */ /* (C) 2005 Oliver Schmidt, <ol.sc@web.de> */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stddef.h> #include <unistd.h> #include <dirent.h> #include "dir.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ struct dirent* __fastcall__ readdir (register DIR* dir) { register unsigned char* entry; /* Search for the next active directory entry */ do { /* Read next directory block if necessary */ if (dir->current_entry == dir->entries_per_block) { if (read (dir->fd, dir->block.bytes, sizeof (dir->block)) != sizeof (dir->block)) { /* Just return failure as read() has */ /* set errno if (and only if) no EOF */ return NULL; } /* Start with first entry in next block */ dir->current_entry = 0; } /* Compute pointer to current entry */ entry = dir->block.content.entries + dir->current_entry * dir->entry_length; /* Switch to next entry */ ++dir->current_entry; } while (entry[0x00] == 0); /* Move creation date/time to allow for next step below */ *(unsigned long*)&entry[0x1A] = *(unsigned long*)&entry[0x18]; /* Feature unsigned long access to EOF by extension from 3 to 4 bytes */ entry[0x18] = 0; /* Move file type to allow for next step below */ entry[0x19] = entry[0x10]; /* Zero-terminate file name */ entry[0x01 + (entry[0x00] & 0x0F)] = 0; /* Return success */ return (struct dirent*)&entry[0x01]; }
792
./cc65/libsrc/apple2/opendir.c
/*****************************************************************************/ /* */ /* opendir.h */ /* */ /* Open a directory */ /* */ /* */ /* */ /* (C) 2005 Oliver Schmidt, <ol.sc@web.de> */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <dirent.h> #include "dir.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ extern char _cwd[FILENAME_MAX]; /*****************************************************************************/ /* Code */ /*****************************************************************************/ DIR* __fastcall__ opendir (register const char* name) { register DIR* dir; /* Alloc DIR */ if ((dir = malloc (sizeof (*dir))) == NULL) { /* May not have been done by malloc() */ _directerrno (ENOMEM); /* Return failure */ return NULL; } /* Interpret dot as current working directory */ if (*name == '.') { name = _cwd; } /* Open directory file */ if ((dir->fd = open (name, O_RDONLY)) != -1) { /* Read directory key block */ if (read (dir->fd, dir->block.bytes, sizeof (dir->block)) == sizeof (dir->block)) { /* Get directory entry infos from directory header */ dir->entry_length = dir->block.bytes[0x23]; dir->entries_per_block = dir->block.bytes[0x24]; /* Skip directory header entry */ dir->current_entry = 1; /* Return success */ return dir; } /* EOF: Most probably no directory file at all */ if (_oserror == 0) { _directerrno (EINVAL); } /* Cleanup directory file */ close (dir->fd); } /* Cleanup DIR */ free (dir); /* Return failure */ return NULL; }
793
./cc65/libsrc/apple2/closedir.c
/*****************************************************************************/ /* */ /* closedir.c */ /* */ /* Close a directory */ /* */ /* */ /* */ /* (C) 2005 Oliver Schmidt, <ol.sc@web.de> */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> #include <fcntl.h> #include <dirent.h> #include "dir.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ int __fastcall__ closedir (DIR* dir) { int result; /* Cleanup directory file */ result = close (dir->fd); /* Cleanup DIR */ free (dir); return result; }
794
./cc65/libsrc/zlib/uncompress.c
/* * uncompress.c * * Piotr Fusik, 18.11.2001 */ #include <zlib.h> int uncompress (char* dest, unsigned* destLen, const char* source, unsigned sourceLen) { unsigned len; unsigned char* ptr; unsigned long csum; /* source[0]: Compression method and flags bits 0 to 3: Compression method (must be Z_DEFLATED) bits 4 to 7: Compression info (must be <= 7) source[1]: Flags bits 0 to 4: Check bits bit 5: Preset dictionary (not supported, sorry) bits 6 to 7: Compression level */ if ((source[0] & 0x8f) != Z_DEFLATED || source[1] & 0x20) return Z_DATA_ERROR; if ((((unsigned) source[0] << 8) | (unsigned char) source[1]) % 31) return Z_DATA_ERROR; *destLen = len = inflatemem(dest, source + 2); ptr = (unsigned char*) source + sourceLen - 4; csum = adler32(adler32(0L, Z_NULL, 0), dest, len); if ((unsigned char) csum != ptr[3] || (unsigned char) (csum >> 8) != ptr[2] || (unsigned char) (csum >> 16) != ptr[1] || (unsigned char) (csum >> 24) != ptr[0]) return Z_DATA_ERROR; return Z_OK; }
795
./cc65/libsrc/cbm/readdir.c
/* * Ullrich von Bassewitz, 2012-05-30. Based on code by Groepaz. */ #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <cbm.h> #include "dir.h" #include <stdio.h> struct dirent* __fastcall__ readdir (register DIR* dir) { register unsigned char* b; register unsigned char i; register unsigned char count; static unsigned char s; static unsigned char j; unsigned char buffer[0x40]; static struct dirent entry; /* Remember the directory offset for this entry */ entry.d_off = dir->off; /* Skip the basic line-link */ if (!_dirread (dir, buffer, 2)) { /* errno already set */ goto exitpoint; } /* Read the number of blocks */ if (!_dirread (dir, &entry.d_blocks, sizeof (entry.d_blocks))) { goto exitpoint; } /* Read the next file entry into the buffer */ for (count = 0, b = buffer; count < sizeof (buffer); ++b) { if (!_dirread1 (dir, b)) { goto exitpoint; } ++count; if (*b == '\0') { break; } } /* Bump the directory offset and include the bytes for line-link and size */ dir->off += count + 4; /* End of directory is reached if the buffer contains "blocks free". It is * sufficient here to check for the leading 'b'. buffer will contain at * least one byte if we come here. */ if (buffer[0] == 'b') { goto exitpoint; } /* Parse the buffer for the filename and file type */ i = 0; j = 0; s = 0; b = buffer; while (i < count) { switch (s) { case 0: /* Searching for start of file name */ if (*b == '"') { s = 1; } break; case 1: /* Within file name */ if (*b == '"') { /* End of file name found. */ entry.d_name[j] = '\0'; entry.d_namlen = j; if (entry.d_off > 2) { /* Proceed with file type */ s = 2; } else { /* This is a disk header, so we're done */ entry.d_type = _CBM_T_HEADER; return &entry; } } else if (j < sizeof (entry.d_name) - 1) { entry.d_name[j] = *b; ++j; } break; case 2: /* Searching for file type */ if (*b != ' ') { entry.d_type = _cbm_filetype (*b); if (*b == 'd') { /* May be DEL or DIR, check next char */ s = 3; } else { /* Done */ return &entry; } } break; case 3: /* Distinguish DEL or DIR file type entries */ switch (*b) { case 'e': break; case 'i': entry.d_type = _CBM_T_DIR; break; default: entry.d_type = _CBM_T_OTHER; break; } return &entry; } ++i; ++b; } /* Something went wrong when parsing the directory entry */ _errno = EIO; exitpoint: return 0; }
796
./cc65/libsrc/cbm/cbm_load.c
/* * Marc 'BlackJack' Rintsch, 06.03.2001 * * unsigned int cbm_load(const char* name, * unsigned char device, * const unsigned char* data); */ #include <cbm.h> /* loads file "name" from given device to given address or to the load address * of the file if "data" is 0 */ unsigned int cbm_load(const char* name, unsigned char device, void* data) { /* LFN is set to 0 but it's not needed for loading. * (BASIC V2 sets it to the value of the SA for LOAD) */ cbm_k_setlfs(0, device, data == 0); cbm_k_setnam(name); return (cbm_k_load(0, (unsigned int)data) - (unsigned int)data); }
797
./cc65/libsrc/cbm/opendir.c
/* * Ullrich von Bassewitz, 2012-05-30. Based on code by Groepaz. */ #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include "dir.h" DIR* __fastcall__ opendir (register const char* name) { unsigned char buf[2]; DIR* dir = 0; DIR d; /* Setup the actual file name that is sent to the disk. We accept "0:", * "1:" and "." as directory names. */ d.name[0] = '$'; if (name == 0 || name[0] == '\0' || (name[0] == '.' && name[1] == '\0')) { d.name[1] = '\0'; } else if ((name[0] == '0' || name[0] == '1') && name[1] == ':' && name[2] == '\0') { d.name[1] = name[0]; d.name[2] = '\0'; } else { errno = EINVAL; goto exitpoint; } /* Set the offset of the first entry */ d.off = sizeof (buf); /* Open the directory on disk for reading */ d.fd = open (d.name, O_RDONLY); if (d.fd >= 0) { /* Skip the load address */ if (_dirread (&d, buf, sizeof (buf))) { /* Allocate memory for the DIR structure returned */ dir = malloc (sizeof (*dir)); /* Copy the contents of d */ if (dir) { memcpy (dir, &d, sizeof (d)); } else { /* Set an appropriate error code */ errno = ENOMEM; } } } exitpoint: /* Done */ return dir; }
798
./cc65/libsrc/cbm/cbm_dir.c
/* This is a very simplified version of the POSIX opendir(), */ /* readdir(), and closedir() -- for Commodore computers. */ /* Created by Josef Soucek, 2003. E-mail: josef.soucek@ct.cz */ /* 2003-01-21 -- Version 0.1 */ /* 2009-10-10 -- Version 0.3 */ /* 2011-04-07 -- Version 0.4, groepaz */ /* 2011-04-14 -- Version 0.5, Greg King */ /* Tested with floppy-drive and IDE64 devices. */ /* Not tested with messed (buggy) directory listings. */ /* Limits filenames to 16 chars. (VICE supports more */ /* in directory listings). */ #include <stdarg.h> #include <cbm.h> #include <errno.h> /* Opens directory listing. Returns 0 if opening directory was successful; ** otherwise, an error-code corresponding to cbm_open(). As an optional ** argument, the name of the directory may be passed to the function. If ** no explicit name is specified, "$" is used. */ unsigned char cbm_opendir (unsigned char lfn, unsigned char device, ...) { va_list ap; const char* name = "$"; /* The name used in cbm_open may optionally be passed */ if (__argsize__ == 4) { va_start (ap, device); name = va_arg (ap, const char*); va_end (ap); } /* Open the directory */ if (cbm_open (lfn, device, CBM_READ, name) == 0) { if ((_oserror = cbm_k_chkin (lfn)) == 0) { /* Ignore start address */ cbm_k_basin(); cbm_k_basin(); cbm_k_clrch(); if (cbm_k_readst()) { cbm_close(lfn); _oserror = 4; /* directory cannot be read */ } } } return _oserror; } /* Reads one directory line into cbm_dirent structure. ** Returns 0 if reading directory-line was successful. ** Returns non-zero if reading directory failed, or no more file-names to read. ** Returns 2 on last line. Then, l_dirent->size = the number of "blocks free." */ unsigned char __fastcall__ cbm_readdir (unsigned char lfn, register struct cbm_dirent* l_dirent) { unsigned char byte, i = 0; unsigned char is_header = 0; unsigned char rv = 1; if (!cbm_k_chkin(lfn)) { if (!cbm_k_readst()) { /* skip 2 bytes, next-BASIC-line pointer */ cbm_k_basin(); cbm_k_basin(); /* File-size or drive/partition number */ l_dirent->size = cbm_k_basin() | (cbm_k_basin() << 8); byte = cbm_k_basin(); switch (byte) { /* "B" BLOCKS FREE. */ case 'b': /* Read until end; careless callers might call us again. */ while (!cbm_k_readst()) { cbm_k_basin(); } rv = 2; /* EOF */ goto ret_val; /* Reverse-text shows when this is the directory header. */ case 0x12: /* RVS_ON */ is_header = 1; } while (byte != '\"') { /* prevent endless loop */ if (cbm_k_readst()) { rv = 3; goto ret_val; } byte = cbm_k_basin(); } while ((byte = cbm_k_basin()) != '\"') { /* prevent endless loop */ if (cbm_k_readst()) { rv = 4; goto ret_val; } if (i < sizeof (l_dirent->name) - 1) { l_dirent->name[i] = byte; ++i; } } l_dirent->name[i] = '\0'; if (is_header) { l_dirent->type = CBM_T_HEADER; /* Get the disk-format code. */ i = 6; do { l_dirent->access = byte = cbm_k_basin(); } while (--i != 0); } else { /* Go to the file-type column. */ while ((byte = cbm_k_basin()) == ' ') { /* prevent endless loop */ if (cbm_k_readst()) { rv = 5; goto ret_val; } } l_dirent->access = CBM_A_RW; /* "Splat" files shouldn't be read. */ if (byte == '*') { l_dirent->access = CBM_A_WO; byte = cbm_k_basin(); } /* Determine the file type */ l_dirent->type = _cbm_filetype (byte); /* Notice whether it's a directory or a deleted file. */ if (cbm_k_basin() == 'i' && byte == 'd') { l_dirent->type = CBM_T_DIR; } cbm_k_basin(); /* Locked files shouldn't be written. */ if ((byte = cbm_k_basin()) == '<') { l_dirent->access = (l_dirent->access == CBM_A_WO) ? 0 : CBM_A_RO; } } /* Read to the end of the line. */ while (byte != 0) { /* prevent endless loop */ if (cbm_k_readst()) { rv = 6; goto ret_val; } byte = cbm_k_basin(); } rv = 0; goto ret_val; } } ret_val: cbm_k_clrch(); return rv; } void __fastcall__ cbm_closedir (unsigned char lfn) { cbm_close(lfn); }
799
./cc65/libsrc/cbm/seekdir.c
/* * Ullrich von Bassewitz, 2012-06-03. Based on code by Groepaz. */ #include <fcntl.h> #include <unistd.h> #include <errno.h> #include "dir.h" void __fastcall__ seekdir (register DIR* dir, long offs) { unsigned o; unsigned char count; unsigned char buf[128]; /* Make sure we have a reasonable value for offs */ if (offs > 0x1000) { errno = EINVAL; return; } /* Close the directory file descriptor */ close (dir->fd); /* Reopen it using the old name */ dir->fd = open (dir->name, O_RDONLY); if (dir->fd < 0) { /* Oops! */ return; } /* Skip until we've reached the target offset in the directory */ o = dir->off = offs; while (o) { /* Determine size of next chunk to read */ if (o > sizeof (buf)) { count = sizeof (buf); o -= sizeof (buf); } else { count = offs; o = 0; } /* Skip */ if (!_dirread (dir, buf, count)) { return; } } }
800
./cc65/libsrc/cbm/cbm_save.c
/* * Marc 'BlackJack' Rintsch, 11.03.2001 * * unsigned char cbm_save(const char* name, * char device, * unsigned char* data, * unsigned int size); */ #include <cbm.h> #include <errno.h> /* saves a memory area from start to end-1 to a file. */ unsigned char __fastcall__ cbm_save (const char* name, unsigned char device, const void* data, unsigned int size) { cbm_k_setlfs(0, device, 0); cbm_k_setnam(name); return _oserror = cbm_k_save((unsigned int)data, ((unsigned int)data) + size); }