repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
MartinPippel/DAmar
|
lib/borders.h
|
#pragma once
#include "db/DB.h"
#include "dalign/align.h"
#include "lib/pass.h"
#define EVENT_BEGIN 1
#define EVENT_END 2
typedef struct
{
int ovl;
unsigned short pos;
unsigned short type;
unsigned short ovh;
unsigned short span;
} Event;
typedef struct
{
Event* peb;
Event* pee;
int eb, ee;
int type;
int link;
int done;
} Border;
void find_borders(Border** ppBorder, int* bmax, int* bcur, Event** pEvents, int l, int r,
float min_density, int min_events, int max_dist);
|
MartinPippel/DAmar
|
lib/read_loader.h
|
<reponame>MartinPippel/DAmar<filename>lib/read_loader.h
#pragma once
#include "db/DB.h"
typedef struct _Read_Loader Read_Loader;
struct _Read_Loader
{
HITS_DB* db;
size_t max_mem;
char* reads; // storage for loaded reads
uint64 maxreads; // size of reads
char** index; // pointers into reads, indexed by read id
int* rid;
int currid;
int nrid;
};
Read_Loader* rl_init(HITS_DB* db, size_t max_mem);
void rl_add(Read_Loader* rl, int rid);
void rl_load(Read_Loader* rl, int* reads, int nreads);
void rl_load_added(Read_Loader* rl);
void rl_load_read(Read_Loader* rl, int rid, char* read, int ascii);
void rl_free(Read_Loader* rl);
|
MartinPippel/DAmar
|
utils/kmers.c
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <assert.h>
#include <math.h>
#include <sys/param.h>
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/pass.h"
#include "lib/tracks.h"
#include "lib/utils.h"
#include "lib/lasidx.h"
#include "db/DB.h"
#include "dalign/align.h"
#define DEF_ARG_E 12
#define DEF_ARG_M 0
#define BINS_NORMAL 0
#define BINS_NOISE 1
#define BINS_REPEAT 2
#define VERBOSE
#undef DEBUG
#undef DEBUG_CLASSIFY
typedef uint64 KMER;
typedef unsigned char KMER_COUNT;
#define KMER_COUNT_MAX 255
// typedef uint16 KMER_COUNT;
// #define KMER_COUNT_MAX 65535
typedef struct
{
HITS_DB* db;
char* pathDb;
// k-mer k
int k;
uint16 error;
uint16 coverage;
uint16 genomesize;
uint16 merge;
uint16 noise;
uint16 over;
double over_expected;
double noise_expected;
// window size
int wnd;
// kmer occurance counts. capped at KMER_COUNT_MAX
KMER_COUNT* kcounts;
uint64 kcount;
// kmer occurance histogram
uint64* histo_counts;
uint64 histo_sum;
// expected window sum
double ews;
double ews_nocap_sigma;
double ews_nocap_mu;
} KmersContext;
// getopt
extern char* optarg;
extern int optind, opterr, optopt;
void print_bits(size_t const size, void const * const ptr)
{
unsigned char* b = (unsigned char*) ptr;
unsigned char byte;
int i, j;
for (i = size - 1; i >= 0; i--)
{
for (j = 7; j >= 0; j--)
{
byte = (b[i] >> j) & 1;
printf("%u", byte);
}
printf(" ");
}
puts("");
}
static void track_add(track_anno* anno, track_data** _data, track_anno* _dmax, track_anno* _dcur, int merge, int rid, int beg, int end)
{
track_data* data = *_data;
track_anno dmax = *_dmax;
track_anno dcur = *_dcur;
if ( dcur + 2 >= dmax )
{
dmax = dmax * 1.2 + 1000;
data = realloc( data, sizeof(track_data) * dmax );
}
if ( anno[rid] > 0 && data[dcur - 1] + merge >= beg )
{
data[ dcur - 1 ] = end;
}
else
{
// printf("%d @ %5d..%5d\n", read, i, i + j);
anno[ rid ] += sizeof(track_data) * 2;
data[ dcur ] = beg;
data[ dcur + 1 ] = end;
dcur += 2;
}
*_data = data;
*_dmax = dmax;
*_dcur = dcur;
}
static int kmer_count_noise(KmersContext* kctx)
{
// double prob_kmer_conserved = exp( -1.0 * (kctx->error / 100.0) * kctx->k );
double err = kctx->error / 100.0;
int k = kctx->k;
double prob_kmer_conserved = pow(1-err, k+1) + (1.0/k) * ( pow(1-err, k-1) - pow(1-err, 2*k - 1) );
double exp_kmer_count = MAX( 1.0, kctx->genomesize * 1000.0 * 1000.0 * 0.5 / pow(4, kctx->k) );
return floorl( exp_kmer_count * kctx->coverage * prob_kmer_conserved );
}
static void compute_cutoffs(KmersContext* kctx)
{
#ifdef VERBOSE
printf("computing k-mer cutoffs\n");
#endif
uint64 sum = 0;
int i = KMER_COUNT_MAX;
uint64 histo_sum = kctx->histo_sum;
uint64* histo_counts = kctx->histo_counts;
uint64 count = 0;
while ( (double)(sum) / histo_sum < 0.01 )
{
count += histo_counts[i] * i;
sum += histo_counts[i];
i -= 1;
}
double exp = 1.0 * count / ( kctx->genomesize * 1000.0 * 1000.0 * kctx->coverage * 0.5 );
int wnd = kctx->wnd - kctx->k + 1;
printf("cutoff repeat @ %d sum %lld count %lld -> %.2f %.2f\n", i, sum, count, exp, exp * wnd);
kctx->over_expected = exp;
kctx->over = i;
kctx->noise = kmer_count_noise(kctx);
i = kctx->noise;
sum = 0;
count = 0;
while ( i != 0 )
{
count += histo_counts[i] * i;
sum += histo_counts[i];
i -= 1;
}
exp = 1.0 * count / ( kctx->genomesize * 1000.0 * 1000.0 * kctx->coverage * 0.5 );
printf("cutoff noise @ %d sum %lld count %lld -> %.2f %.2f\n", kctx->noise, sum, count, exp, exp * wnd);
kctx->noise_expected = exp;
}
static int classify_bins(KmersContext* kctx, uint64* bins, uint64* _nnoise, uint64* _nnormal, uint64* _nover)
{
KMER_COUNT noise = kctx->noise;
KMER_COUNT over = kctx->over;
uint64 nnoise = 0;
uint64 nnormal = 0;
uint64 nover = 0;
uint64 i;
for ( i = 0 ; i < noise ; i++ )
{
nnoise += bins[i];
}
for ( ; i < over ; i++ )
{
nnormal += bins[i];
}
for ( ; i <= KMER_COUNT_MAX ; i++ )
{
nover += bins[i];
}
*_nnoise = nnoise;
*_nnormal = nnormal;
*_nover = nover;
int wnd = kctx->wnd - kctx->k + 1;
double over_expected = kctx->over_expected * ( wnd - nnoise );
double noise_expected = kctx->noise_expected * wnd;
if ( nover > over_expected )
{
return BINS_REPEAT;
}
else if ( nnoise > noise_expected )
{
return BINS_NOISE;
}
else
{
return BINS_NORMAL;
}
}
static void create_track(KmersContext* kctx, int maxreads)
{
printf("creating k-mer repeat track\n");
char* pathDb = kctx->pathDb;
KMER_COUNT* kcounts = kctx->kcounts;
uint64 kcount = kctx->kcount;
int wnd = kctx->wnd;
int k = kctx->k;
int merge = kctx->merge;
uint64 kmask = kcount - 1;
HITS_DB db;
char fname[PATH_MAX];
sprintf(fname, "bstats.%d.txt", kctx->k);
FILE* fileOutBase = fopen(fname, "w");
sprintf(fname, "wstats.%d.txt", kctx->k);
FILE* fileOutWnd = fopen(fname, "w");
Open_DB(pathDb, &db);
KMER* readmers = malloc( sizeof(KMER) * db.maxlen );
track_anno* anno = malloc(sizeof(track_anno) * (DB_NREADS(&db) + 1));
track_anno dmax = DB_NREADS(&db) * 2;
track_anno dcur = 0;
track_data* data = malloc(sizeof(track_data) * dmax);
bzero(anno, sizeof(track_anno) * (DB_NREADS(&db) + 1));
track_anno* noise_anno = malloc(sizeof(track_anno) * (DB_NREADS(&db) + 1));
track_anno noise_dmax = DB_NREADS(&db) * 2;
track_anno noise_dcur = 0;
track_data* noise_data = malloc(sizeof(track_data) * noise_dmax);
bzero(noise_anno, sizeof(track_anno) * (DB_NREADS(&db) + 1));
uint64* bins = malloc(sizeof(uint64) * (KMER_COUNT_MAX + 1));
uint64 nnoise, nnormal, nover;
int nblocks = DB_Blocks(pathDb);
int block;
for (block = 1; block <= nblocks; block++)
{
printf("block %d/%d\n", block, nblocks);
// if ( block != 25 ) continue;
HITS_DB dbb;
Open_DB_Block(pathDb, &dbb, block);
Read_All_Sequences(&dbb, 0);
int read;
for (read = 0; read < dbb.nreads; read++)
{
int idx = 0;
KMER kmer = 0;
char* bases = dbb.bases + dbb.reads[read].boff;
int rlen = dbb.reads[read].rlen;
int rid = dbb.ufirst + read;
bzero(readmers, db.maxlen);
while (idx < k - 1)
{
kmer = (kmer << 2) + bases[idx];
idx++;
}
while (idx < rlen)
{
kmer = ( (kmer << 2) & kmask ) + bases[idx];
readmers[idx] = kmer;
idx++;
}
int i;
if ( read < maxreads )
{
for (i = k - 1; i < rlen; i++)
{
fprintf(fileOutBase, "%d %d %d\n", rid, i, kcounts[ readmers[i] ]);
}
}
for (i = 0; i < rlen - wnd; i++)
{
bzero(bins, sizeof(uint64) * (KMER_COUNT_MAX + 1));
int j;
int sum = 0;
for (j = k - 1; j < wnd; j++) {
kmer = readmers[i + j];
sum += kcounts[kmer];
bins[kcounts[kmer]] += 1;
}
#ifdef DEBUG_CLASSIFY
printf("%d..%d -> ", i, i + j);
#endif
switch ( classify_bins(kctx, bins, &nnoise, &nnormal, &nover) )
{
case BINS_REPEAT:
track_add(anno, &data, &dmax, &dcur, merge, rid, i, i + j);
break;
case BINS_NOISE:
track_add(noise_anno, &noise_data, &noise_dmax, &noise_dcur, merge, rid, i, i + j);
break;
}
if (read < maxreads)
{
fprintf(fileOutWnd, "%d %d %d %lld %lld %lld\n", rid, i, i + wnd - 1, nnoise, nnormal, nover);
}
i += wnd;
}
switch ( classify_bins(kctx, bins, &nnoise, &nnormal, &nover) )
{
case BINS_REPEAT:
track_add(anno, &data, &dmax, &dcur, merge, rid, i, rlen);
break;
case BINS_NOISE:
track_add(noise_anno, &noise_data, &noise_dmax, &noise_dcur, merge, rid, i, rlen);
break;
}
//break;
}
Close_DB(&dbb);
break;
}
int i;
track_anno coff, off;
track_anno noise_off;
noise_off = off = 0;
for (i = 0; i <= DB_NREADS(&db); i++)
{
coff = anno[i];
anno[i] = off;
off += coff;
coff = noise_anno[i];
noise_anno[i] = noise_off;
noise_off += coff;
}
track_write(&db, TRACK_KREPEATS, 0, anno, data, dcur);
track_write(&db, TRACK_KNOISE, 0, noise_anno, noise_data, noise_dcur);
free(noise_anno);
free(noise_data);
free(anno);
free(data);
free(readmers);
fclose(fileOutBase);
fclose(fileOutWnd);
Close_DB(&db);
}
/*
static void print_histograms(KmersContext* kctx)
{
uint64 total, count;
total = count = 0;
uint64* bins = kctx->histo_counts;
uint64 i;
for ( i = 0 ; i <= KMER_COUNT_MAX ; i++ )
{
printf("%lld %lld\n", i, bins[i]);
if (i > 0)
{
total += i * bins[i];
count += bins[i];
}
}
printf("avg %.2f (with %d)\n", (double)(total) / count, KMER_COUNT_MAX);
total -= KMER_COUNT_MAX * bins[KMER_COUNT_MAX];
count -= bins[KMER_COUNT_MAX];
printf("avg %.2f\n", (double)(total) / count);
}
*/
static int load_kcounts(KmersContext* kctx)
{
int k = kctx->k;
char* pathDb = kctx->pathDb;
HITS_DB* db = kctx->db;
uint64 kcount = kctx->kcount = (1llu << (2*k));
uint64 kmask = kcount - 1;
KMER_COUNT* kcounts = kctx->kcounts = malloc( sizeof(KMER_COUNT) * kcount );
bzero(kcounts, sizeof(KMER_COUNT) * kcount);
if (kcounts == NULL)
{
fprintf(stderr, "failed to allocate kcounts\n");
return 0;
}
int read = 0;
char pcPathKmers[PATH_MAX];
sprintf(pcPathKmers, "%s.%dmers", pathDb, k);
FILE* fileKmers = fopen(pcPathKmers, "r");
if ( fileKmers )
{
#ifdef VERBOSE
printf("loading k-mer counts\n");
#endif
if ( fread(kcounts, sizeof(KMER_COUNT), kcount, fileKmers) != kcount )
{
fprintf(stderr, "ERROR: failed to load kmer counts\n");
exit(1);
}
fclose(fileKmers);
}
else
{
#ifdef VERBOSE
printf("computing k-mer counts\n");
#endif
int nblocks = DB_Blocks(pathDb);
int block;
for (block = 1; block <= nblocks; block++)
{
fprintf(stderr, "%s %d/%d\n", pathDb, block, nblocks);
Open_DB_Block(pathDb, db, block);
// pass
Read_All_Sequences(db, 0);
for (read = 0; read < db->nreads; read++)
{
char* bases = db->bases + db->reads[read].boff;
int rlen = db->reads[read].rlen;
int idx = 0;
KMER kmer = 0;
while (idx < k - 1)
{
kmer = (kmer << 2) + bases[idx];
idx++;
}
while (idx < rlen)
{
kmer = ( (kmer << 2) + bases[idx] ) & kmask;
idx++;
if (kcounts[kmer] < KMER_COUNT_MAX)
{
kcounts[kmer] += 1;
}
}
}
Close_DB(db);
}
FILE* fileOut = fopen(pcPathKmers, "w");
fwrite(kcounts, sizeof(KMER_COUNT), kcount, fileOut);
fclose(fileOut);
}
// create k-mer occurance count histogram
#ifdef VERBOSE
printf("computing k-mer histogram\n");
#endif
uint64* bins = kctx->histo_counts = malloc( sizeof(uint64) * (KMER_COUNT_MAX + 1) );
bzero(bins, sizeof(uint64) * (KMER_COUNT_MAX + 1));
uint64 i;
for ( i = 0 ; i < kcount ; i++ )
{
bins[ kcounts[i] ] += 1;
}
uint64 sum = 0;
for ( i = 1 ; i < KMER_COUNT_MAX ; i++ )
{
sum += bins[i];
}
kctx->histo_sum = sum;
return 1;
}
static void usage()
{
printf("usage: [-e <error>] [-m <merge>] <db> <k> <coverage> <genome.mb>\n");
printf("options: -e sequence error rate (default %d)\n", DEF_ARG_E);
printf(" -m merge distance for repeat intervals (default k)\n");
printf(" -r only report computed cutoffs\n");
}
int main(int argc, char* argv[])
{
KmersContext kctx;
HITS_DB db;
int c;
int do_work = 1;
bzero(&kctx, sizeof(KmersContext));
kctx.db = &db;
kctx.error = DEF_ARG_E;
// TODO -- hardcoded
kctx.wnd = 250;
kctx.merge = DEF_ARG_M;
// process arguments
opterr = 0;
while ((c = getopt(argc, argv, "re:m:")) != -1)
{
switch (c)
{
case 'e':
kctx.error = atoi(optarg);
break;
case 'm':
kctx.merge = atoi(optarg);
break;
case 'r':
do_work = 0;
break;
default:
printf("Unknow option: %s\n", argv[optind - 1]);
usage();
exit(1);
}
}
if (argc - optind < 4)
{
usage();
exit(1);
}
kctx.pathDb = argv[optind++];
kctx.k = atoi( argv[optind++] );
kctx.coverage = atoi( argv[optind++] );
kctx.genomesize = atoi( argv[optind++] );
if (kctx.merge == 0 && kctx.merge < kctx.k)
{
kctx.merge = kctx.k;
}
#ifdef VERBOSE
printf("k = %d coverage = %d genome size = %dMB merge = %d\n", kctx.k, kctx.coverage, kctx.genomesize, kctx.merge);
#endif
if (!load_kcounts(&kctx))
{
exit(1);
}
// print_sequence(&kctx, 200);
// return 1;
compute_cutoffs(&kctx);
// print_histograms(&kctx);
// return 1;
#ifdef VERBOSE
printf("0 < noise < %d < normal < %d < overrepresented < %d\n", kctx.noise, kctx.over, KMER_COUNT_MAX);
#endif
if ( do_work )
{
create_track(&kctx, 200);
}
// cleanup
free(kctx.kcounts);
free(kctx.histo_counts);
return 0;
}
|
MartinPippel/DAmar
|
dalign/DMctl.c
|
<reponame>MartinPippel/DAmar<gh_stars>10-100
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include "../lib/dmask.h"
#include "../lib/dmask_proto.h"
#define DEF_ARG_H "localhost" // host
#define DEF_ARG_P DMASK_DEFAULT_PORT // listen port
static void usage()
{
printf("usage: [-h <host>] [-p <port>] <command>\n");
printf("options: -h ... mask server host (%s)\n", DEF_ARG_H);
printf(" -p ... mask server port (%d)\n", DEF_ARG_P);
printf("commands: shutdown ... terminate dmask server process\n");
printf(" lock ... disable coverage statistics updates\n");
printf(" unlock ... enable coverage statistics updates\n");
printf(" intervals ... write intervals to disk\n");
printf(" track ... write track\n");
printf(" done dir|*.las ... send block done signal for all overlap files in dir or a list of las file\n");
}
int main(int argc, char* argv[])
{
int port = DEF_ARG_P;
char* host = DEF_ARG_H;
// process arguments
int c;
opterr = 0;
while ((c = getopt(argc, argv, "h:p:")) != -1)
{
switch (c)
{
case 'p':
port = atoi(optarg);
break;
case 'h':
host = optarg;
break;
default:
usage();
exit(1);
}
}
if (port == 0)
{
fprintf(stderr, "invalid listen port %d\n", port);
exit(1);
}
if (optind+1 > argc)
{
usage();
exit(1);
}
char* command = argv[optind++];
DynamicMask* dm = dm_init(host, port);
if (dm == NULL)
{
fprintf(stderr, "failed to initialise dynamic dust\n");
exit(1);
}
if (strcasecmp(command, "shutdown") == 0)
{
dm_shutdown(dm);
}
else if (strcasecmp(command, "lock") == 0)
{
dm_lock(dm);
}
else if (strcasecmp(command, "unlock") == 0)
{
dm_unlock(dm);
}
else if (strcasecmp(command, "intervals") == 0)
{
dm_intervals(dm);
}
else if (strcasecmp(command, "track") == 0)
{
dm_write_track(dm);
}
else if (strcasecmp(command, "done") == 0)
{
char **files;
int maxf = 100;
int curf = 0;
int i, len, dirLen;
files = (char**) malloc(sizeof(char*) * maxf);
while (argc - optind > 0)
{
struct stat sb;
stat(argv[optind], &sb);
if (S_ISDIR(sb.st_mode))
{
DIR *dp;
struct dirent *ep;
dp = opendir(argv[optind]);
if (dp != NULL)
{
dirLen = strlen(argv[optind]);
while ((ep = readdir(dp)))
{
if (curf == maxf)
{
maxf = maxf * 1.2 + 10;
files = (char**) realloc(files, sizeof(char*) * maxf);
}
len = strlen(ep->d_name);
// check for las file name extension
if ((len < 4) || ((strcasecmp(ep->d_name + (len - 4), ".las") != 0)))
continue;
files[curf] = (char*) malloc(dirLen + len + 20);
sprintf(files[curf], "%s/%s", argv[optind], ep->d_name);
curf++;
}
(void) closedir(dp);
}
else
perror("Couldn't open the directory");
}
else if (S_ISREG(sb.st_mode))
{
if (curf == maxf)
{
maxf = maxf * 1.2 + 10;
files = (char**) realloc(files, sizeof(char*)*maxf);
}
len = strlen(argv[optind]);
if ((len > 4) && ((strcasecmp(argv[optind] + (len - 4), ".las") == 0)))
{
files[curf] = (char*) malloc(len + 10);
memcpy(files[curf], argv[optind], len);
files[curf][len] = '\0';
curf++;
}
}
else
{
fprintf(stderr, "warning: file %s is not accepted!\n", argv[optind]);
}
optind++;
}
files[curf] = NULL;
// i = 0;
// while (files[i] != NULL)
// {
// printf("file[%d]: %s\n", i, files[i]);
// i++;
// }
// exit(1);
if (!dm_done(dm, files))
fprintf(stderr, "server did not get results\n");
for (i = 0; i < curf; i++)
free(files[i]);
free(files);
}
else
{
usage();
}
dm_free(dm);
return 0;
}
|
MartinPippel/DAmar
|
scrub/TANmask.c
|
<gh_stars>10-100
/************************************************************************************\
* *
* Copyright (c) 2014, Dr. <NAME> (EWM). 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. *
* *
* · The name of EWM may not be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY EWM ”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 EWM 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. *
* *
* For any issues regarding this software and its use, contact EWM at: *
* *
* <NAME>r. *
* Bautzner Str. 122e *
* 01099 Dresden *
* GERMANY *
* Email: <EMAIL> *
* *
\************************************************************************************/
/*******************************************************************************************
*
* MASKtan takes as input a .las file of self alignments (produced by datandem) and
* builds a .tan mask track that encodes the union of all self-overlapping LA's (signature)
* of a tandem repeat) of length greater than MIN_LEN (set by -l parameter).
*
* Author: <NAME>
* Date : March 27 2016
*
*******************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <math.h>
#include <getopt.h>
#include "db/DB.h"
#include "dalign/align.h"
#ifdef HIDE_FILES
#define PATHSEP "/."
#else
#define PATHSEP "/"
#endif
#define DEF_ARG_M "tan"
extern char *optarg;
extern int optind, opterr, optopt;
static void usage()
{
fprintf(stderr, "usage: \n\n");
fprintf(stderr, "TANmask [-v] [-l<int>] [-m<track(tan)>] <source:db> <overlaps:las> ...\n\n");
fprintf(stderr, "options: -v ... verbose\n");
fprintf(stderr, " -l ... minimum alignment length (default: 500)\n");
fprintf(stderr, " -m ... output track name (default: %s)\n", DEF_ARG_M);
}
// Partition Constants
#define SEP_FUZZ 20
// Global Data Structures
static int VERBOSE;
static int MIN_LEN;
static HITS_DB _DB, *DB = &_DB; // Data base
static int DB_PART; // Input is an Overlap block
static int DB_FIRST; // for reads DB_FIRST to DB_LAST-1
static int DB_LAST;
static int TRACE_SPACING; // Trace spacing (from .las file)
static int TBYTES; // Bytes per trace segment (from .las file)
static FILE *TN_AFILE; // .tan.anno
static FILE *TN_DFILE; // .tan.data
static int64 TN_INDEX; // Current index into .tan.data file as it is being written
// Statistics
static int64 nreads, totlen;
static int64 nmasks, masked;
static int ISORT(const void *l, const void *r)
{ int x = *((int *) l);
int y = *((int *) r);
return (x-y);
}
static void TANDEM(int aread, Overlap *ovls, int novl)
{ static int nmax = -1;
static int *add = NULL;
static int *del;
int evnum;
(void) aread;
if (VERBOSE)
{ nreads += 1;
totlen += DB->reads[aread].rlen;
}
if (novl == 0)
{ fwrite(&TN_INDEX,sizeof(int64),1,TN_AFILE);
return;
}
#ifdef DEBUG
printf("\nAREAD %d:\n",aread);
#endif
if (novl > nmax)
{ nmax = 1.2*novl + 500;
add = (int *) Realloc(add,4*sizeof(int)*nmax,"Allocating sort vector");
if (add == NULL)
exit (1);
del = add + nmax;
}
// For each overlapping LA record mask interval as an add and del event
// that are then sorted
{ int i;
Path *ipath;
evnum = 0;
for (i = 0; i < novl; i++)
{ ipath = &(ovls[i].path);
if (ipath->abpos - ipath->bepos <= SEP_FUZZ)
{ if (ipath->aepos - ipath->bbpos > MIN_LEN)
{ add[evnum] = ipath->bbpos;
del[evnum] = ipath->aepos;
evnum += 1;
}
}
}
qsort(add,evnum,sizeof(int),ISORT);
qsort(del,evnum,sizeof(int),ISORT);
}
// Output the union of the mask intervals to the .tan track
{ int i, j, x, a;
x = a = 0;
i = j = 0;
while (j < evnum)
if (i < evnum && add[i] <= del[j])
{ if (x == 0)
{ fwrite(add+i,sizeof(int),1,TN_DFILE);
TN_INDEX += sizeof(int);
#ifdef DEBUG
printf(" + %5d: %3d\n",add[i],x);
#endif
a = add[i];
}
x += 1;
i += 1;
}
else
{ x -= 1;
if (x == 0)
{ fwrite(del+j,sizeof(int),1,TN_DFILE);
TN_INDEX += sizeof(int);
#ifdef DEBUG
printf(" - %5d: %3d\n",del[j],x);
#endif
if (VERBOSE)
{ masked += del[j]-a;
nmasks += 1;
}
}
j += 1;
}
#ifdef DEBUG
printf(" %lld\n",TN_INDEX);
#endif
fwrite(&TN_INDEX,sizeof(int64),1,TN_AFILE);
}
}
// Read in each successive pile and call ACTION on it. Read in the traces only if
// "trace" is nonzero
static int make_a_pass(FILE *input, void (*ACTION)(int, Overlap *, int), int trace)
{ static Overlap *ovls = NULL;
static int omax = 500;
static uint16 *paths = NULL;
static int pmax = 100000;
int64 i, j, novl;
int n, a;
int pcur;
int max;
if (ovls == NULL)
{ ovls = (Overlap *) Malloc(sizeof(Overlap)*omax,"Allocating overlap buffer");
if (ovls == NULL)
exit (1);
}
if (trace && paths == NULL)
{ paths = (uint16 *) Malloc(sizeof(uint16)*pmax,"Allocating path buffer");
if (paths == NULL)
exit (1);
}
rewind(input);
fread(&novl,sizeof(int64),1,input);
fread(&TRACE_SPACING,sizeof(int),1,input);
if (TRACE_SPACING <= TRACE_XOVR)
TBYTES = sizeof(uint8);
else
TBYTES = sizeof(uint16);
if (Read_Overlap(input,ovls) != 0)
ovls[0].aread = INT32_MAX;
else if (trace)
{ if (ovls[0].path.tlen > pmax)
{ pmax = 1.2*(ovls[0].path.tlen)+10000;
paths = (uint16 *) Realloc(paths,sizeof(uint16)*pmax,"Expanding path buffer");
if (paths == NULL) exit (1);
}
fread(paths,TBYTES,ovls[0].path.tlen,input);
if (TBYTES == 1)
{ ovls[0].path.trace = paths;
Decompress_TraceTo16(ovls);
}
}
else
fseek(input,TBYTES*ovls[0].path.tlen,SEEK_CUR);
if (ovls[0].aread < DB_FIRST)
{ fprintf(stderr,"%s: .las file overlaps don't correspond to reads in block %d of DB\n",
Prog_Name,DB_PART);
exit (1);
}
pcur = 0;
n = max = 0;
for (j = DB_FIRST; j < DB_LAST; j++)
{ ovls[0] = ovls[n];
a = ovls[0].aread;
if (a != j)
n = 0;
else
{ if (trace)
memmove(paths,paths+pcur,sizeof(uint16)*ovls[0].path.tlen);
n = 1;
pcur = ovls[0].path.tlen;
while (1)
{ if (Read_Overlap(input,ovls+n) != 0)
{ ovls[n].aread = INT32_MAX;
break;
}
if (trace)
{ if (pcur + ovls[n].path.tlen > pmax)
{ pmax = 1.2*(pcur+ovls[n].path.tlen)+10000;
paths = (uint16 *) Realloc(paths,sizeof(uint16)*pmax,"Expanding path buffer");
if (paths == NULL) exit (1);
}
fread(paths+pcur,TBYTES,ovls[n].path.tlen,input);
if (TBYTES == 1)
{ ovls[n].path.trace = paths+pcur;
Decompress_TraceTo16(ovls+n);
}
}
else
fseek(input,TBYTES*ovls[n].path.tlen,SEEK_CUR);
if (ovls[n].aread != a)
break;
pcur += ovls[n].path.tlen;
n += 1;
if (n >= omax)
{ omax = 1.2*n + 100;
ovls = (Overlap *) Realloc(ovls,sizeof(Overlap)*omax,"Expanding overlap buffer");
if (ovls == NULL) exit (1);
}
}
if (n >= max)
max = n;
pcur = 0;
for (i = 0; i < n; i++)
{ ovls[i].path.trace = paths+pcur;
pcur += ovls[i].path.tlen;
}
}
ACTION(j,ovls,n);
}
if (ovls[n].aread < INT32_MAX)
{ fprintf(stderr,"%s: .las file overlaps don't correspond to reads in block %d of DB\n",
Prog_Name,DB_PART);
exit (1);
}
return (max);
}
int main(int argc, char *argv[])
{ FILE *input;
char *root, *dpwd;
char *las, *lpwd;
int c;
char *MASK_NAME = DEF_ARG_M;
int MIN_LEN;
// Process arguments
{ MIN_LEN = 500;
// parse arguments
int c;
opterr = 0;
while ((c = getopt(argc, argv, "vl:m:")) != -1)
{
switch (c)
{
case 'v':
VERBOSE = 1;
break;
case 'l':
MIN_LEN = atoi(optarg);
break;
case 'm':
MASK_NAME = optarg;
break;
default:
fprintf(stderr, "Unsupported option: %s\n", argv[optind - 1]);
usage();
exit(1);
}
}
if (optind + 2 > argc)
{
fprintf(stderr, "[ERROR] - at least one subject block and one LAS file are required\n\n");
usage();
exit(1);
}
}
// Open trimmed DB
{ int status;
status = Open_DB(argv[optind],DB);
if (status < 0)
exit (1);
if (DB->part)
{ fprintf(stderr,"%s: Cannot be called on a block: %s\n",Prog_Name,argv[1]);
exit (1);
}
}
// Initialize statistics gathering
if (VERBOSE)
{ int i;
nreads = 0;
totlen = 0;
masked = 0;
nmasks = 0;
printf("\nTANmask -l%d -m%s %s",MIN_LEN,MASK_NAME,argv[1]);
for (i = 2; i < argc; i++)
printf(" %s",argv[i]);
printf("\n");
}
// Determine if overlap block is being processed and if so get first and last read
// from .db file
dpwd = PathTo(argv[optind]);
root = Root(argv[optind],".db");
for (c = optind + 1; c < argc; c++)
{ las = Root(argv[c],".las");
DB_PART = 0;
DB_FIRST = 0;
DB_LAST = DB->nreads;
{ FILE *dbfile;
char buffer[2*MAX_NAME+100];
char *p, *eptr;
int i, part, nfiles, nblocks;
int64 size;
p = rindex(las,'.');
if (p != NULL)
{ part = strtol(p+1,&eptr,10);
if (*eptr == '\0' && eptr != p+1)
{ dbfile = Fopen(Catenate(dpwd,"/",root,".db"),"r");
if (dbfile == NULL)
exit (1);
if (fscanf(dbfile,DB_NFILE,&nfiles) != 1)
{
fprintf(stderr, "[ERROR] TANmask: DB %s is empty.\n", argv[optind]);
SYSTEM_READ_ERROR
}
for (i = 0; i < nfiles; i++)
if (fgets(buffer,2*MAX_NAME+100,dbfile) == NULL)
{
fprintf(stderr, "[ERROR] TANmask: DB %s has no fasta names.\n", argv[optind]);
SYSTEM_READ_ERROR
}
if (fscanf(dbfile,DB_NBLOCK,&nblocks) != 1)
{
fprintf(stderr, "[ERROR] TANmask: DB %s has no blocks.\n", argv[optind]);
SYSTEM_READ_ERROR
}
if (fscanf(dbfile,DB_PARAMS,&size) != 1)
{
fprintf(stderr, "[ERROR] TANmask: DB %s has no block size.\n", argv[optind]);
SYSTEM_READ_ERROR
}
for (i = 1; i <= part; i++)
if (fscanf(dbfile,DB_BDATA,&DB_FIRST) != 1)
SYSTEM_READ_ERROR
if (fscanf(dbfile,DB_BDATA,&DB_LAST) != 1)
SYSTEM_READ_ERROR
fclose(dbfile);
DB_PART = part;
*p = '\0';
}
}
}
// Set up mask track
{ int len, size;
char ans[strlen(MASK_NAME)+7];
char dts[strlen(MASK_NAME)+7];
strcpy(ans,Catenate(".",MASK_NAME,".","anno"));
strcpy(dts,Catenate(".",MASK_NAME,".","data"));
if (DB_PART > 0)
{ TN_AFILE = Fopen(Catenate(dpwd,PATHSEP,root,
Numbered_Suffix(".",DB_PART,ans)),"w");
TN_DFILE = Fopen(Catenate(dpwd,PATHSEP,root,
Numbered_Suffix(".",DB_PART,dts)),"w");
}
else
{ TN_AFILE = Fopen(Catenate(dpwd,PATHSEP,root,ans),"w");
TN_DFILE = Fopen(Catenate(dpwd,PATHSEP,root,dts),"w");
}
if (TN_AFILE == NULL || TN_DFILE == NULL)
exit (1);
len = DB_LAST - DB_FIRST;
size = 8;
fwrite(&len,sizeof(int),1,TN_AFILE);
fwrite(&size,sizeof(int),1,TN_AFILE);
TN_INDEX = 0;
fwrite(&TN_INDEX,sizeof(int64),1,TN_AFILE);
}
// Open overlap file
lpwd = PathTo(argv[c]);
if (DB_PART > 0)
input = Fopen(Catenate(lpwd,"/",las,Numbered_Suffix(".",DB_PART,".las")),"r");
else
input = Fopen(Catenate(lpwd,"/",las,".las"),"r");
if (input == NULL)
exit (1);
free(lpwd);
free(las);
// Process each read pile
make_a_pass(input,TANDEM,0);
fclose(TN_AFILE);
fclose(TN_DFILE);
}
if (VERBOSE)
{ printf("\nInput: ");
Print_Number((int64) nreads,7,stdout);
printf(" (100.0%%) reads ");
Print_Number(totlen,12,stdout);
printf(" (100.0%%) bases\n");
printf("Masks: ");
Print_Number(nmasks,7,stdout);
printf(" (%5.1f%%) masks ",(100.*nmasks)/nreads);
Print_Number(masked,12,stdout);
printf(" (%5.1f%%) bases\n",(100.*masked)/totlen);
}
free(dpwd);
free(root);
Close_DB(DB);
free(Prog_Name);
exit (0);
}
|
MartinPippel/DAmar
|
lib/dmask.h
|
<filename>lib/dmask.h
#pragma once
#define DMASK
#include <sys/socket.h>
#include <resolv.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "dalign/align.h"
#include "db/DB.h"
#include "lib/tracks.h"
#define DMASK_DEFAULT_PORT 12345
typedef struct
{
int sockfd;
struct sockaddr_in dest;
int send_next;
} DynamicMask;
DynamicMask* dm_init(const char* host, uint16 port);
void dm_free(DynamicMask* dm);
void dm_write_track(DynamicMask* dm);
void dm_shutdown(DynamicMask* dm);
void dm_lock(DynamicMask* dm);
void dm_unlock(DynamicMask* dm);
void dm_intervals(DynamicMask* dm);
int dm_done(DynamicMask* dm, char** files);
HITS_TRACK* dm_load_track(HITS_DB* db, DynamicMask* dm, char* trackName);
int dm_send_block_done(DynamicMask* dm, int run,
HITS_DB* blocka, char* namea,
HITS_DB* blockb, char* nameb);
void dm_send_next(DynamicMask* dm, int run,
HITS_DB* blocka, char* namea,
HITS_DB* blockb, char* nameb);
|
MartinPippel/DAmar
|
lib/tracks.h
|
<gh_stars>10-100
#pragma once
#include "db/DB.h"
#include <inttypes.h>
#define TRACK_ANNO "anno"
#define TRACK_DUST "dust"
#define TRACK_MASK_R "maskr"
#define TRACK_MASK_C "maskc"
#define TRACK_EDGES "edges"
#define TRACK_FULL_EDGES "fedges"
#define TRACK_Q "q"
#define TRACK_REPEATS "repeats"
#define TRACK_SOURCE "source"
#define TRACK_TRIM "trim"
#define TRACK_DDREPEATS "ddrepeats"
#define TRACK_HREPEATS "hrepeats"
#define TRACK_KREPEATS "krepeats"
#define TRACK_KNOISE "knoise"
#define TRACK_PACBIO_HEADER "pacbio" // pacbio header (well, beg, end)
#define TRACK_PACBIO_RQ "RQ" // pacbio RQ value "read quality"
#define TRACK_PACBIO_CHEM "chemistry" // pacbio chemistry (BindingKit, SequencingKit, SoftwareVersion, [SequencingChemistry])
#define TRACK_SCAFFOLD "scaffold" // used in DAM, to keep track of putative N's (contigNumber, contigOffset)
#define TRACK_SEQID "seqID" // sequence identifier, keeps track of sequence in original fasta file
#define TRACK_SPR "spr" // slow polymerase region
#define TRACK_RPOINTS "rpoints"
#define TRACK_JSOURCE "jsource"
#define TRACK_VERSION_2 2
typedef int track_header_len;
typedef int track_header_size;
typedef uint64 track_header_offset;
typedef uint64 track_anno;
typedef int track_data;
typedef struct
{
uint16_t version;
uint16_t size;
uint32_t pad1;
uint64_t len;
uint64_t clen;
uint64_t cdlen;
uint64_t reserved1;
uint64_t reserved2;
uint64_t reserved3;
uint64_t reserved4;
} track_anno_header;
HITS_TRACK* track_load(HITS_DB *db, char* track);
void track_close(HITS_TRACK* track);
int track_delete(HITS_DB* db, const char* track);
void track_write(HITS_DB* db, const char* track, int block, track_anno* anno, track_data* data, uint64_t dlen);
char* track_name(HITS_DB* db, const char* track, int block);
void write_track_trimmed(HITS_DB* db, const char* track, int block, track_anno* anno, track_data* data, uint64_t dlen);
void write_track_untrimmed(HITS_DB* db, const char* track, int block, track_anno* anno, track_data* data, uint64_t dlen);
|
MartinPippel/DAmar
|
lib/dmask_proto.h
|
#pragma once
#include "../db/DB.h"
typedef struct
{
unsigned char version; // protocol version
unsigned char type; // message type DM_TYPE_xxx
uint64 length; // amount of data
uint64 reserved1;
uint64 reserved2;
uint64 reserved3;
uint64 reserved4;
} DmHeader;
#define DM_VERSION 0x1
#define DM_TYPE_LAS_AVAILABLE (0x1 << 0) // c -> s ... contains NULL separated paths as data after header
#define DM_TYPE_REQUEST_TRACK (0x1 << 1) // c -> s ... request track. reserved1 = bfirst, reserved2 = nreads
#define DM_TYPE_RESPONSE_TRACK (0x1 << 2) // c <- s ... dust track for the requested offset/block (bfirst & nreads)
#define DM_TYPE_SHUTDOWN (0x1 << 3) // c -> s ... initiate server shutdown
#define DM_TYPE_LOCK (0x1 << 4) // c -> s ... lock (do not update) coverage statistics
#define DM_TYPE_UNLOCK (0x1 << 5) // c -> s ... unlock coverage statistics
#define DM_TYPE_INTERVALS (0x1 << 6) // c -> s ... dump dusted intervals to text file
#define DM_TYPE_WRITE_TRACK (0x1 << 7) // c -> s ... write track
|
MartinPippel/DAmar
|
lib/compression.h
|
<reponame>MartinPippel/DAmar
#include <inttypes.h>
void uncompress_chunks(void* ibuf, uint64_t ilen, void* obuf, uint64_t olen);
void compress_chunks(void* ibuf, uint64_t ilen, void** _obuf, uint64_t* _olen);
|
MartinPippel/DAmar
|
utils/LAmergeUtils.c
|
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include <ctype.h>
#include "LAmergeUtils.h"
#include "lib/oflags.h"
static char* Usage = "[-hksv] [-C nsStA] [-n numFiles(8)] [-S fileSuffix] [-f files.txt] <db> <out.las> [<directory>| <in.1.las in.2.las ...>]";
void printUsage(char *prog, FILE* out)
{
fprintf(out, "\nUsage:\t%s\t%s\n\n", prog, Usage);
fprintf(out, " -h prints this usage info\n");
fprintf(out, " -v verbose output\n");
fprintf(out, " -s sort files before merging takes place\n");
fprintf(out, " -k keep intermediate merge results\n");
fprintf(out, " -C n|s|S|t|A perform sanity checks. Multiple options are possible.\n");
fprintf(out, " n ... file names must be consistent with database.\n");
fprintf(out, " s ... small sort order check: lp.read.ID < rp.read.ID\n");
fprintf(out, " S ... large sort order check: lp.read.ID < rp.read.ID && lp.read.COMP < rp.read.COMP && lp.read.abpos < rp.read.abpos\n");
fprintf(out, " t ... check trace points\n");
fprintf(out, " A ... check all (corresponds to: nSt)\n");
fprintf(out, " -n NUM specify number of files that are merged simultaneously [2, 255], (Default: 8).\n");
fprintf(out, " -S suffix specify a file suffix, e.g. ovh, or rescued, (default: not set)\n");
fprintf(out, " -f file file that contains a list of overlap files that should be merged. (One file per line)\n");
fprintf(out, " db database name\n");
fprintf(out, " directory specify directory where the overlaps are located.\n");
}
int SORT_OVL(const void *x, const void *y)
{
Overlap* l = (Overlap *) x;
Overlap* r = (Overlap *) y;
int al, ar;
int bl, br;
al = l->aread;
bl = l->bread;
ar = r->aread;
br = r->bread;
if (al != ar)
return (al - ar);
if (bl != br)
return (bl - br);
if (COMP(l->flags) > COMP(r->flags))
return 1;
if (COMP(l->flags) < COMP(r->flags))
return -1;
if (l->path.abpos != r->path.abpos)
return (l->path.abpos - r->path.abpos);
if (l->path.aepos != r->path.aepos)
return (l->path.aepos - r->path.aepos);
if (l->path.bbpos != r->path.bbpos)
return (l->path.bbpos - r->path.bbpos);
return (l->path.bepos - r->path.bepos);
}
#define COMPARE(lp,rp) \
if (lp->aread > rp->aread) \
bigger = 1; \
else if (lp->aread < rp->aread) \
bigger = 0; \
else if (lp->bread > rp->bread) \
bigger = 1; \
else if (lp->bread < rp->bread) \
bigger = 0; \
else if (COMP(lp->flags) > COMP(rp->flags)) \
bigger = 1; \
else if (COMP(lp->flags) < COMP(rp->flags)) \
bigger = 0; \
else if (lp->path.abpos > rp->path.abpos) \
bigger = 1; \
else if (lp->path.abpos < rp->path.abpos) \
bigger = 0; \
else if (lp->path.aepos > rp->path.aepos) \
bigger = 0; \
else if (lp->path.aepos < rp->path.aepos) \
bigger = 1; \
else if (lp->path.bbpos > rp->path.bbpos) \
bigger = 1; \
else if (lp->path.bbpos < rp->path.bbpos) \
bigger = 0; \
else if (lp->path.bepos > rp->path.bepos) \
bigger = 0; \
else if (lp->path.bepos < rp->path.bepos) \
bigger = 1; \
else \
bigger = 0;
void reheap(int s, Overlap **heap, int hsize)
{
int c, l, r;
int bigger;
Overlap *hs, *hr, *hl;
c = s;
hs = heap[s];
while ((l = 2 * c) <= hsize)
{
r = l + 1;
hl = heap[l];
if (r > hsize)
bigger = 1;
else
{
hr = heap[r];
COMPARE(hr, hl)
}
if (bigger)
{
COMPARE(hs, hl)
if (bigger)
{
heap[c] = hl;
c = l;
}
else
break;
}
else
{
COMPARE(hs, hr)
if (bigger)
{
heap[c] = hr;
c = r;
}
else
break;
}
}
if (c != s)
heap[c] = hs;
}
void ovl_reload(IO_block *in, int64 bsize)
{
int64 remains;
remains = in->top - in->ptr;
if (remains > 0)
memcpy(in->block, in->ptr, remains);
in->ptr = in->block;
in->top = in->block + remains;
in->top += fread(in->top, 1, bsize - remains, in->stream);
}
void showheap(Overlap **heap, int hsize)
{
int i;
printf("\n");
for (i = 1; i <= hsize; i++)
printf(" %3d: %5d, %5d\n", i, heap[i]->aread, heap[i]->bread);
}
static void check_pre(PassContext* pctx, CheckContext* cctx)
{
cctx->twidth = pctx->twidth;
cctx->prev_a = 0;
}
static void check_post(PassContext* pctx, CheckContext* cctx, char *filename)
{
if (!cctx->error && pctx->novl != cctx->novl)
{
fprintf(stderr, "[ERROR] - LAmerge: In file: %s -> novl of %lld doesn't match actual overlap count of %lld\n", filename, pctx->novl, cctx->novl);
cctx->error = 1;
}
}
#define CMP(a, b) cmp = (a) - (b); if (cmp != 0) return cmp;
inline static int compare_sort(Overlap* o1, Overlap* o2, int sort)
{
int cmp;
if (sort == 0)
return 0;
if (sort == 1)
{
CMP(o1->aread, o2->aread);
CMP(o1->bread, o2->bread);
}
else
{
CMP(o1->aread, o2->aread);
CMP(o1->bread, o2->bread);
CMP(o1->flags & OVL_COMP, o2->flags & OVL_COMP);
CMP(o1->path.abpos, o2->path.abpos);
CMP(o1->path.aepos, o2->path.aepos);
}
return cmp;
}
static int check_process(void* _ctx, Overlap* ovl, int novl)
{
CheckContext* ctx = (CheckContext*) _ctx;
int i, lena, lenb;
for (i = 0; i < novl; i++)
{
ctx->novl++;
if (i == 0)
{
if (ctx->check_sort && ctx->prev_a > ovl[i].aread)
{
fprintf(stderr, "overlap %lld: not sorted\n", ctx->novl);
ctx->error = 1;
}
}
else
{
int cmp = compare_sort(ovl + (i - 1), ovl + i, ctx->check_sort);
if (cmp > 0 && ctx->check_sort)
{
printf("%d %d\n", ovl[i - 1].aread, ovl[i - 1].bread);
fprintf(stderr, "overlap %lld: not sorted\n", ctx->novl);
ctx->error = 1;
}
}
lena = DB_READ_LEN(ctx->db, ovl[i].aread);
lenb = DB_READ_LEN(ctx->db, ovl[i].bread);
if (ovl[i].path.abpos < 0)
{
fprintf(stderr, "overlap %lld: abpos < 0: %d vs %d %c a[%d, %d] b[%d, %d] l[%d,%d]\n", ctx->novl, ovl[i].aread, ovl[i].bread, (ovl[i].flags & OVL_COMP) ? 'C' : 'N', ovl[i].path.abpos, ovl[i].path.aepos, ovl[i].path.bbpos, ovl[i].path.bepos, lena, lenb);
ctx->error = 1;
}
if (ovl[i].path.bbpos < 0)
{
fprintf(stderr, "overlap %lld: bbpos < 0: %d vs %d %c a[%d, %d] b[%d, %d] l[%d,%d]\n", ctx->novl, ovl[i].aread, ovl[i].bread, (ovl[i].flags & OVL_COMP) ? 'C' : 'N', ovl[i].path.abpos, ovl[i].path.aepos, ovl[i].path.bbpos, ovl[i].path.bepos, lena, lenb);
ctx->error = 1;
}
if (ovl[i].path.aepos > lena)
{
fprintf(stderr, "overlap %lld: aepos > lena: %d vs %d %c a[%d, %d] b[%d, %d] l[%d,%d]\n", ctx->novl, ovl[i].aread, ovl[i].bread, (ovl[i].flags & OVL_COMP) ? 'C' : 'N', ovl[i].path.abpos, ovl[i].path.aepos, ovl[i].path.bbpos, ovl[i].path.bepos, lena, lenb);
ctx->error = 1;
}
if (ovl[i].path.bepos > lenb)
{
fprintf(stderr, "overlap %lld: bepos > lenb: %d vs %d %c a[%d, %d] b[%d, %d] l[%d,%d]\n", ctx->novl, ovl[i].aread, ovl[i].bread, (ovl[i].flags & OVL_COMP) ? 'C' : 'N', ovl[i].path.abpos, ovl[i].path.aepos, ovl[i].path.bbpos, ovl[i].path.bepos, lena, lenb);
ctx->error = 1;
}
if (ovl[i].path.tlen < 0)
{
fprintf(stderr, "overlap %lld: invalid tlen %d\n", ctx->novl, ovl[i].path.tlen);
ctx->error = 1;
}
if (ctx->check_ptp)
{
ovl_trace* trace = ovl[i].path.trace;
int apos = ovl[i].path.abpos;
int bpos = ovl[i].path.bbpos;
int j;
for (j = 0; j < ovl[i].path.tlen; j += 2)
{
apos += (apos / ctx->twidth + 1) * ctx->twidth;
bpos += trace[j + 1];
}
if (bpos != ovl[i].path.bepos)
{
fprintf(stderr, "overlap %lld (%d x %d) %c a[%d, %d] b[%d, %d] l[%d,%d]: pass-through points inconsistent be = %d (expected %d)\n", ctx->novl, ovl[i].aread, ovl[i].bread, (ovl[i].flags & OVL_COMP) ? 'C' : 'N', ovl[i].path.abpos, ovl[i].path.aepos, ovl[i].path.bbpos, ovl[i].path.bepos, lena, lenb, bpos, ovl[i].path.bepos);
ctx->error = 1;
}
}
}
ctx->prev_a = ovl->aread;
return !ctx->error;
}
int checkOverlapFile(MERGE_OPT *mopt, char *filename, int silent)
{
if (!silent || mopt->VERBOSE > 2)
printf("Check file: %s\n", filename);
// general sanity checks
// check if file empty
{
struct stat st;
stat(filename, &st);
if (st.st_size == 0)
{
if (!silent || mopt->VERBOSE > 2)
printf(" --> failed (Overlap file %s is empty)\n", filename);
return 1;
}
}
// check if file is accessible and has valid header
{
FILE *fileOvlIn;
if ((fileOvlIn = fopen(filename, "r")) == NULL)
{
if (!silent || mopt->VERBOSE > 2)
printf(" --> failed could not open '%s'\n", filename);
return 1;
}
ovl_header_novl novl;
ovl_header_twidth twidth;
if (!ovl_header_read(fileOvlIn, &(novl), &(twidth)))
{
if (!silent || mopt->VERBOSE > 2)
printf(" --> failed invalid header in file '%s'\n", filename);
fclose(fileOvlIn);
return 1;
}
fclose(fileOvlIn);
}
// check file name
if (mopt->CHECK_NAME)
{
// check if filename has .las file extension
{
char * pch;
pch = strrchr(filename, '.');
if (pch == NULL)
{
if (mopt->VERBOSE > 2)
printf(" --> failed (No .las file extension)\n");
else if (!silent)
fprintf(stderr, "[WARNING] - LAmerge: Overlap file %s does not have the proper .las file extension.\n", filename);
return 1;
}
if (strcmp(pch, ".las") != 0)
{
if (mopt->VERBOSE > 2)
printf(" --> failed (No .las file extension)\n");
else if (!silent)
fprintf(stderr, "[WARNING] - LAmerge: Overlap file %s does not have the proper .las file extension.\n", filename);
return 1;
}
// check if file matches suffix (if present)
if (strlen(mopt->suffix) > 0)
{
*pch = '\0';
char * ppch;
ppch = strrchr(filename, '.');
if (ppch == NULL)
{
if (mopt->VERBOSE > 2)
printf(" --> failed (Overlap file %s.las does not match suffix pattern %s)\n", filename, mopt->suffix);
else if (!silent)
fprintf(stderr, "[WARNING] - LAmerge: Overlap file %s.las does not match suffix pattern %s\n", filename, mopt->suffix);
return 1;
}
if (strcmp(ppch, mopt->suffix) != 0)
{
if (mopt->VERBOSE > 2)
printf(" --> failed (Overlap file %s.las does not match suffix pattern %s)\n", filename, mopt->suffix);
else if (!silent)
fprintf(stderr, "[WARNING] - LAmerge: Overlap file %s.las does not match suffix pattern %s\n", filename, mopt->suffix);
return 1;
}
*pch = '.';
}
}
// check if filename, belongs to database
{
char *root = Root(filename, ".las");
if (strncmp(mopt->nameDB, root, strlen(mopt->nameDB)) != 0)
{
if (mopt->VERBOSE > 2)
printf(" --> failed (Overlap file name %s does not match database name %s)\n", root, mopt->nameDB);
free(root);
return 1;
}
free(root);
}
if (!silent || mopt->VERBOSE > 2)
printf(" --> succeeded\n");
}
// check
if (mopt->CHECK_SORT_ORDER || mopt->CHECK_TRACE_POINTS)
{
FILE *fileOvlIn;
if ((fileOvlIn = fopen(filename, "r")) == NULL)
{
if (!silent)
fprintf(stderr, "could not open '%s'\n", filename);
return 1;
}
PassContext* pctx;
CheckContext cctx;
bzero(&cctx, sizeof(CheckContext));
cctx.db = mopt->db;
cctx.check_ptp = mopt->CHECK_TRACE_POINTS;
cctx.check_sort = mopt->CHECK_SORT_ORDER;
pctx = pass_init(fileOvlIn, NULL);
pctx->split_b = 0;
pctx->load_trace = cctx.check_ptp;
pctx->unpack_trace = cctx.check_ptp;
pctx->data = &cctx;
check_pre(pctx, &cctx);
pass(pctx, check_process);
check_post(pctx, &cctx, filename);
pass_free(pctx);
fclose(fileOvlIn);
return cctx.error;
}
return 0;
}
void addInputFile(MERGE_OPT *mopt, char *fileName)
{
if (mopt->numOfFilesToMerge == mopt->maxIFiles)
{
mopt->maxIFiles = (mopt->maxIFiles * 1.2 + 100);
mopt->iFileNames = (char**) realloc(mopt->iFileNames, sizeof(char*) * mopt->maxIFiles);
if (mopt->iFileNames == NULL)
{
fprintf(stderr, "[ERROR] - LAmerge: Unable to increase input file buffer!\n");
exit(1);
}
}
int len = strlen(fileName);
mopt->iFileNames[mopt->numOfFilesToMerge] = malloc(len + 10);
if (mopt->iFileNames[mopt->numOfFilesToMerge] == NULL)
{
fprintf(stderr, "[ERROR] - LAmerge: Unable to allocate file name buffer for %s\n", fileName);
exit(1);
}
memcpy(mopt->iFileNames[mopt->numOfFilesToMerge], fileName, len + 1);
if (mopt->VERBOSE)
printf("Add input file: %s\n", fileName);
mopt->numOfFilesToMerge++;
}
static char *trimFileString(char *str)
{
char *end;
// Trim leading space
while (isspace(*str))
str++;
if (*str == 0) // All spaces?
return str;
// Trim trailing space
end = str + strlen(str) - 1;
while (end > str && isspace(*end))
end--;
// Write new null terminator
*(end + 1) = 0;
return str;
}
void getFilesBySuffix(MERGE_OPT *mopt)
{
char *fileName;
fileName = malloc(strlen(mopt->suffix) + strlen(mopt->pathDB) + 20);
if (fileName == NULL)
{
fprintf(stderr, "[ERROR] - LAmerge : Cannot allocate file name buffer\n");
exit(1);
}
char *dbPath = PathTo(mopt->pathDB);
// look for files in the same directory where the database is located
int i;
int failed = 0;
for (i = 1; i <= mopt->nBlocks; i++)
{
sprintf(fileName, "%s/%s.%d%s.las", dbPath, mopt->nameDB, i, mopt->suffix);
if (checkOverlapFile(mopt, fileName, 1))
{
fprintf(stderr, "[ERROR] - LAmerge : Overlap file %s did not pass check!\n", fileName);
failed = 1;
}
}
if (failed)
{
fprintf(stderr, "[ERROR] - LAmerge : Some overlap files are not valid. Merging by suffix requires "
"that all Overlaps files [1, numBlocks] to be valid! Stop here!\n");
exit(1);
}
for (i = 1; i <= mopt->nBlocks; i++)
{
sprintf(fileName, "%s/%s.%d%s.las", dbPath, mopt->nameDB, i, mopt->suffix);
addInputFile(mopt, fileName);
}
free(dbPath);
free(fileName);
}
void getFilesFromFile(MERGE_OPT* mopt)
{
if (mopt->inputFileList == NULL)
return;
FILE *in = fopen(mopt->inputFileList, "r");
if (in == NULL)
{
fprintf(stderr, "[WARNING] - LAmerge : Cannot open input file %s\n.\n", mopt->inputFileList);
return;
}
const size_t line_size = MAX_NAME;
char* line = malloc(line_size);
int failed = 0;
while (fgets(line, line_size, in) != NULL)
{
// get rid of newline and blanks
char *mline = trimFileString(line);
if(checkOverlapFile(mopt, mline, 0))
failed++;
else
addInputFile(mopt, mline);
}
free(line);
fclose(in);
if (failed)
{
fprintf(stderr, "[ERROR] - LAmerge : %d files do not pass check. Stop!\n", failed);
exit(1);
}
}
void getFilesFromDir(MERGE_OPT *mopt, char *dirName)
{
DIR *dir;
struct dirent *ent;
char *fullPath;
int fileNameLen;
int dirNameLen = strlen(dirName);
int fullPathLen = dirNameLen + 2 * strlen(mopt->nameDB) + 100;
fullPath = (char*) malloc(fullPathLen);
int failed = 0;
if ((dir = opendir(dirName)) != NULL)
{
/* print all the files and directories within directory */
while ((ent = readdir(dir)) != NULL)
{
fileNameLen = strlen(ent->d_name);
if (fileNameLen + 2 + dirNameLen > fullPathLen)
{
fullPathLen = (fileNameLen + 2 + dirNameLen) * 1.2;
fullPath = (char*) realloc(fullPath, fullPathLen);
if (fullPath == NULL)
{
fprintf(stderr, "[WARNING]: Cannot increase path buffer. Skip file: %s/%s.\n", dirName, ent->d_name);
continue;
}
}
if(ent->d_name[0] == '.')
continue;
sprintf(fullPath, "%s/%s", dirName, ent->d_name);
// check if file extension is las
{
size_t len = strlen(ent->d_name);
if(strcmp(ent->d_name + (len - 4), ".las"))
{
if(mopt->VERBOSE)
fprintf(stderr, "Ignore File %s.\n", fullPath);
continue;
}
if(strlen(mopt->suffix))
{
size_t slen = strlen(mopt->suffix);
ent->d_name[len-4] = '\0';
if(strcmp(ent->d_name + (len - slen), mopt->suffix))
{
if(mopt->VERBOSE)
fprintf(stderr, "Ignore File %s.\n", fullPath);
continue;
}
ent->d_name[len-4] = '.';
}
}
if(checkOverlapFile(mopt, fullPath, 1))
failed++;
else
addInputFile(mopt, fullPath);
}
closedir(dir);
}
else
fprintf(stderr, "[WARNING] - LAmerge: Could not open directory: %s\n", dirName);
if (failed)
{
fprintf(stderr, "[ERROR]: %d input overlap files are corrupt. Stop!\n", failed);
exit(1);
}
free(fullPath);
}
MERGE_OPT* parseMergeOptions(int argc, char* argv[])
{
MERGE_OPT *mopt = (MERGE_OPT*) malloc(sizeof(MERGE_OPT));
// set default values
mopt->VERBOSE = 0;
mopt->KEEP = 0;
mopt->SORT = 0;
mopt->fway = 8;
mopt->CHECK_TRACE_POINTS = 0;
mopt->CHECK_SORT_ORDER = 0;
mopt->CHECK_NAME = 0;
mopt->suffix = (char*) malloc(10);
mopt->suffix[0] = '\0';
mopt->dir = (char*) malloc(10);
sprintf(mopt->dir, ".");
mopt->numOfFilesToMerge = 0;
mopt->oFile = NULL;
mopt->maxIFiles = 100;
mopt->iFileNames = (char**) malloc(sizeof(char*) * mopt->maxIFiles);
mopt->inputFileList = NULL;
int c;
while (1)
{
static struct option long_options[] =
{
{ "help", no_argument, 0, 'h' },
{ "keep", no_argument, 0, 'k' },
{ "sort", no_argument, 0, 's' },
{ "verbose", no_argument, 0, 'v' },
{ "nFiles", required_argument, 0, 'n' },
{ "in", required_argument, 0, 'f' },
{ "suffix", required_argument, 0, 'S' },
{ "check", required_argument, 0, 'C' } };
/* getopt_long stores the option index here. */
int option_index = 0;
c = getopt_long(argc, argv, "hksvn:S:f:C:", long_options, &option_index);
/* Detect the end of the options. */
if (c == -1)
break;
switch (c)
{
case 0:
/* If this option set a flag, do nothing else now. */
if (long_options[option_index].flag != 0)
break;
break;
case 'h':
printUsage(argv[0], stderr);
exit(1);
case 'v':
mopt->VERBOSE++;
break;
case 'k':
mopt->KEEP = 1;
break;
case 's':
mopt->SORT = 1;
break;
case '?':
printUsage(argv[0], stderr);
exit(1);
case 'n':
{
mopt->fway = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument of numFiles (-j ARG)! Must be an integer in [2, 255]\n");
exit(1);
}
if (mopt->fway < 2 || mopt->fway > 255)
{
fprintf(stderr, "Number of files to merge is not accpeted! Must be an integer in [2, 255]\n");
exit(1);
}
}
break;
case 'C':
{
int len = strlen(optarg);
int i;
for (i = 0; i < len; i++)
{
switch (optarg[i])
{
case 'A':
mopt->CHECK_NAME = 1;
mopt->CHECK_TRACE_POINTS = 1;
mopt->CHECK_SORT_ORDER = 2;
break;
case 's':
if (mopt->CHECK_SORT_ORDER < 2)
mopt->CHECK_SORT_ORDER = 1;
break;
case 'S':
mopt->CHECK_SORT_ORDER = 2;
break;
case 't':
mopt->CHECK_TRACE_POINTS = 1;
break;
case 'n':
mopt->CHECK_NAME = 1;
break;
default:
fprintf(stderr, "[WARNING] - LAmerge: skip unknown check option: %c.\n", optarg[i]);
break;
}
}
}
break;
case 'S':
{
mopt->suffix = (char*) realloc(mopt->suffix, strlen(optarg) + 5);
if (strlen(optarg) == 0)
{
/* suffix remains empty, i.e. merge all overlap files DB.1.las ... DB.Nblocks.las */
mopt->suffix[0]='\0';
}
else if (optarg[0] == '.')
sprintf(mopt->suffix, "%s", optarg);
else
sprintf(mopt->suffix, ".%s", optarg);
}
break;
case 'f':
mopt->inputFileList = optarg;
break;
default:
printUsage(argv[0], stderr);
exit(1);
}
}
if (optind + 1 > argc)
{
fprintf(stderr, "At least a database is required!\n");
printUsage(argv[0], stderr);
exit(1);
}
// if -s option is used: reset CHECK_SORT to 0, the final overlap file is always checked for CHECK_SORT=1
if(mopt->SORT)
mopt->CHECK_SORT_ORDER=0;
// parse database
{
int len = strlen(argv[optind]);
mopt->pathDB = malloc(len + 10);
memcpy(mopt->pathDB, argv[optind], len + 1);
// parse number of blocks
mopt->nBlocks = DB_Blocks(mopt->pathDB);
if (mopt->nBlocks < 0)
{
fprintf(stderr, "Cannot determine number of blocks of database file %s!\n", mopt->pathDB);
exit(1);
}
// set name of db (without directory and without extension)
mopt->nameDB = Root(mopt->pathDB, ".db");
// open database
mopt->db = (HITS_DB*) malloc(sizeof(HITS_DB));
Open_DB(mopt->pathDB, mopt->db);
if (mopt->db == NULL)
{
fprintf(stderr, "[ERROR] - LAmerge : Cannot open database \'%s\'!\n", mopt->pathDB);
exit(1);
}
optind++;
}
if (optind == argc)
{
fprintf(stderr, "[ERROR] - LAmerge: The output file is required!\n");
printUsage(argv[0], stderr);
exit(1);
}
struct stat sb;
// get output file name, and trim .las extension
{
int len = strlen(argv[optind]);
mopt->oFile = (char*) malloc(len + 10);
memcpy(mopt->oFile, argv[optind], len + 1);
if ((len > 4) && ((strcmp(argv[optind] + (len - 4), ".las") == 0)))
mopt->oFile[len - 4] = '\0';
if (stat(argv[optind], &sb) != -1)
{
if (S_ISDIR(sb.st_mode))
{
fprintf(stderr, "[ERROR] - LAmerge: The output overlap file cannot be an existing directory: %s!\n", argv[optind]);
exit(1);
}
if (S_ISREG(sb.st_mode))
fprintf(stderr, "[WARNING] - LAmerge: The output overlap file %s will be overwritten!\n", argv[optind]);
}
optind++;
}
while (optind < argc)
{
if (stat(argv[optind], &sb) == -1)
{
fprintf(stderr, "[ERROR] - LAmerge: Cannot determine file type from argument: %s\n", argv[optind]);
exit(1);
}
if (S_ISDIR(sb.st_mode))
{
getFilesFromDir(mopt, argv[optind]);
}
else if (S_ISREG(sb.st_mode) || S_ISLNK(sb.st_mode))
{
if (checkOverlapFile(mopt, argv[optind], 1))
fprintf(stderr, "[WARNING] - LAmerge: skip file %s. File check fails!", argv[optind]);
else
addInputFile(mopt, argv[optind]);
}
else
fprintf(stderr, "[WARNING] - LAmerge: Cannot handle file type from argument: %s\n", argv[optind]);
optind++;
}
// parse file with list of overlap files (each line contains one overlap file)
getFilesFromFile(mopt);
// get input files solely by suffix
if (mopt->numOfFilesToMerge == 0)
{
getFilesBySuffix(mopt);
}
return mopt;
}
void printOptions(FILE* out, MERGE_OPT* mopt)
{
if (mopt && out)
{
fprintf(out, "############ merge options ###########\n");
fprintf(out, "VERBOSE: %d\n", mopt->VERBOSE);
fprintf(out, "KEEP: %d\n", mopt->KEEP);
fprintf(out, "SORT: %d\n", mopt->SORT);
fprintf(out, "#DB BLOCKS: %d\n", mopt->nBlocks);
fprintf(out, "#FWAY MERGE: %d\n", mopt->fway);
fprintf(out, "OUT: %s.las\n", mopt->oFile);
fprintf(out, "NUM: %d\n", mopt->numOfFilesToMerge);
int i;
for (i = 0; i < mopt->numOfFilesToMerge; i++)
fprintf(out, "IN [%3d]: %s.las\n", i + 1, mopt->iFileNames[i]);
fprintf(out, "DIR: %s\n", mopt->dir);
fprintf(out, "DB PATH: %s\n", mopt->pathDB);
fprintf(out, "DB NAME: %s\n", mopt->nameDB);
}
}
void clearMergeOptions(MERGE_OPT* mopt)
{
if (!mopt)
return;
if (mopt->dir)
free(mopt->dir);
if (mopt->pathDB)
free(mopt->pathDB);
if (mopt->nameDB)
free(mopt->nameDB);
if (mopt->suffix)
free(mopt->suffix);
int i;
if (mopt->oFile)
free(mopt->oFile);
if (mopt->iFileNames)
{
for (i = 0; i < mopt->numOfFilesToMerge; i++)
if (mopt->iFileNames[i])
free(mopt->iFileNames[i]);
}
free(mopt);
}
|
MartinPippel/DAmar
|
utils/CTtrim.c
|
/*******************************************************************************************
*
* Trims contigs based on valid contig chain overlaps
*
* Author : <NAME>
*
* Date : May 2020
*
*******************************************************************************************/
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <unistd.h>
#include <ctype.h>
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/pass.h"
#include "lib/read_loader.h"
#include "lib/tracks.h"
#include "lib/trim.h"
#include "lib/utils.h"
#include "dalign/align.h"
#include "db/DB.h"
#include "CTtrim.h"
#define MIN_BIONANO_GAP_SIZE 13
#define TRIM_OFFSET 100
#define FUZZY_BASES 1500
#define FASTA_LINEWIDTH 80
#define MAX_TANDEMTRIM_PERC 70
#define DEBUG_MASKING
#undef DEBUG_MASKING2
void ensureLASchainBuffer(TrimEvidence *t, int numNewElements)
{
assert(t != NULL);
if (t->nLASchains + abs(numNewElements) >= t->maxLASchains)
{
int i = t->maxLASchains * 1.1 + MAX(numNewElements, 10);
t->chains = (LASchain*) realloc(t->chains, sizeof(LASchain) * i);
assert(t->chains != NULL);
bzero(t->chains + t->maxLASchains, sizeof(LASchain) * (i - t->maxLASchains));
t->maxLASchains = i;
}
}
void ensureBionanoGapBuffer(TrimEvidence *t, int numNewElements)
{
assert(t != NULL);
if (t->nBioNanoGaps + abs(numNewElements) >= t->maxBionanoGaps)
{
int i = t->maxBionanoGaps * 1.1 + MAX(numNewElements, 10);
t->gaps = (BionanoGap*) realloc(t->gaps, sizeof(BionanoGap) * i);
assert(t->gaps != NULL);
bzero(t->gaps + t->maxBionanoGaps, sizeof(BionanoGap) * (i - t->maxBionanoGaps));
t->maxBionanoGaps = i;
}
}
void addBionanoGAPInfoToTrimEvidence(TrimContext *ctx, int contigA, int aPartBeg, int aPartEnd, int contigB, int bPartBeg, int bPartEnd, int AdjustedGapLength)
{
TrimEvidence *ta = find_TrimEvidence(ctx, contigA, contigB);
TrimEvidence *tb = find_TrimEvidence(ctx, contigB, contigA);
if (ta == NULL)
{
printf("[Warning] addBionanoGAPInfoToTrimEvidence: Could not find Bionano gap feature between contig %d and contig %d.\n", contigA, contigB);
return;
}
if (tb == NULL)
{
printf("[Warning] addBionanoGAPInfoToTrimEvidence: Could not find Bionano gap feature between contig %d and contig %d.\n", contigB, contigA);
return;
}
// check if the same gap feature is already present: it must be present;
int i;
BionanoGap *b;
for (i = 0; i < ta->nBioNanoGaps; i++)
{
b = ta->gaps + i;
if (((b->aBeg == aPartBeg && b->aEnd == aPartEnd) || (b->aBeg == aPartEnd && b->aEnd == aPartBeg)) && ((b->bBeg == bPartBeg && b->bEnd == bPartEnd) || (b->bBeg == bPartEnd && b->bEnd == bPartBeg)))
{
break;
}
}
if (i == ta->nBioNanoGaps)
{
char *aName = getContigName(ctx, contigA);
char *bName = getContigName(ctx, contigB);
printf("[ERROR] - addBionanoGAPInfoToTrimEvidence 1: Cannot find bionano gap feature: Contig %d (%s) and Contig %d (%s): a[%d, %d] b[%d, %d] gapLen %d\n", contigA, aName, contigB, bName, aPartBeg, aPartEnd, bPartBeg, bPartEnd, AdjustedGapLength);
for (i = 0; i < ta->nBioNanoGaps; i++)
{
b = ta->gaps + i;
printBionanpGap(ctx, contigA, contigB, b);
}
return;
}
b->bionanoGapSize = AdjustedGapLength;
for (i = 0; i < tb->nBioNanoGaps; i++)
{
b = tb->gaps + i;
if (((b->aBeg == bPartEnd && b->aEnd == bPartBeg) || (b->aBeg == bPartBeg && b->aEnd == bPartEnd)) && ((b->bBeg == aPartBeg && b->bEnd == aPartEnd) || (b->bBeg == aPartEnd && b->bEnd == aPartBeg)))
{
break;
}
}
if (i == tb->nBioNanoGaps)
{
char *aName = getContigName(ctx, contigA);
char *bName = getContigName(ctx, contigB);
printf("[ERROR] - addBionanoGAPInfoToTrimEvidence 2: Cannot find bionano gap feature: Contig %d (%s) and Contig %d (%s): a[%d, %d] b[%d, %d] gapLen %d\n", contigB, aName, contigA, bName, bPartEnd, bPartBeg, aPartEnd, aPartBeg, AdjustedGapLength);
for (i = 0; i < tb->nBioNanoGaps; i++)
{
b = tb->gaps + i;
printBionanpGap(ctx, contigA, contigB, b);
}
return;
}
b->bionanoGapSize = AdjustedGapLength;
}
char* getContigName(TrimContext *ctx, int id)
{
assert(id >= 0);
assert(id < DB_NREADS(ctx->db));
int map = 0;
while (id < ctx->findx[map - 1])
map -= 1;
while (id >= ctx->findx[map])
map += 1;
return ctx->flist[map];
}
void addBionanoAGPInfoToTrimEvidence(TrimContext *ctx, int contigA, int fromA, int toA, int contigB, int fromB, int toB, int gapLen)
{
TrimEvidence *t;
t = find_TrimEvidence(ctx, contigA, contigB);
int sort = 0;
if (t == NULL)
{
sort = 1;
t = insert_TrimEvidence(ctx, contigA, contigB);
}
assert(t != NULL);
// add contigA vs contigB
ensureBionanoGapBuffer(t, 1);
// check if the same gap feature is already present
int i;
BionanoGap *b;
for (i = 0; i < t->nBioNanoGaps; i++)
{
b = t->gaps + i;
if (intersect(b->aBeg, b->aEnd, fromA, toA) > 0 || intersect(b->bBeg, b->bEnd, fromB, toB) != 0)
{
printf("[ERROR] - 1: ambiguous Bioano gap for Contig %d and Contig %d: a[%d, %d] b[%d, %d] gapLen %d, "
"collides witrh existing gap: Contig %d and Contig %d: a[%d, %d] b[%d, %d] gapLen %d\n", contigA, contigB, fromA, toA, fromB, toB, gapLen, contigA, contigB, b->aBeg, b->aEnd, b->bBeg, b->bEnd, b->agpGapSize);
exit(1); // todo remove later, for now check if this occurs
}
}
// add gap feature
b = t->gaps + t->nBioNanoGaps;
b->aBeg = fromA;
b->aEnd = toA;
b->bBeg = fromB;
b->bEnd = toB;
b->agpGapSize = gapLen;
t->nBioNanoGaps++;
t = find_TrimEvidence(ctx, contigB, contigA);
if (t == NULL)
{
sort = 1;
t = insert_TrimEvidence(ctx, contigB, contigA);
}
assert(t != NULL);
// add contigB vs contigA
ensureBionanoGapBuffer(t, 1);
for (i = 0; i < t->nBioNanoGaps; i++)
{
b = t->gaps + i;
if (intersect(b->aBeg, b->aEnd, toB, fromB) > 0 || intersect(b->bBeg, b->bEnd, toA, fromA) != 0)
{
printf("[ERROR] - 2: ambiguous Bioano gap for Contig %d and Contig %d: a[%d, %d] b[%d, %d] gapLen %d, "
"collides witrh existing gap: Contig %d and Contig %d: a[%d, %d] b[%d, %d] gapLen %d\n", contigB, contigA, toB, fromB, toA, fromA, gapLen, contigB, contigA, b->aBeg, b->aEnd, b->bBeg, b->bEnd, b->agpGapSize);
exit(1); // todo remove later, for now check if this occurs
}
}
// add gap feature
b = t->gaps + t->nBioNanoGaps;
b->aBeg = toB;
b->aEnd = fromB;
b->bBeg = toA;
b->bEnd = fromA;
b->agpGapSize = gapLen;
t->nBioNanoGaps++;
// ensure sort order
if (sort)
{
qsort(ctx->trimEvid, ctx->numTrimEvidence, sizeof(TrimEvidence), TrimEvidence_cmp);
}
}
int addLASchainInfoToTrimEvidence(TrimContext *ctx, int aread, int bread, int alnLen, int unAlnLen, float erate, int cutPosInA)
{
TrimEvidence *t = find_TrimEvidence(ctx, aread, bread);
int result = 1;
int sort = 0;
if (t == NULL)
{
sort = 1;
t = insert_TrimEvidence(ctx, aread, bread);
result = 0; // create new TrimEvidence (i.e. no bionano evidence avaliable)
}
assert(t != NULL);
// add contigA vs contigB
ensureLASchainBuffer(t, 1);
int i;
LASchain *c;
char *aName = getContigName(ctx, aread);
char *bName = getContigName(ctx, bread);
printf("addLASchainInfoToTrimEvidence %d (%s) vs %d (%s), aln %d, unAln: %d, err: %.3f, cut: %d\n", aread, aName, bread, bName, alnLen, unAlnLen, erate, cutPosInA);
for (i = 0; i < t->nLASchains; i++)
{
c = t->chains + i;
if ((c->trimPos < 0 && cutPosInA < 0) || (c->trimPos > 0 && cutPosInA > 0))
{
printf("[ERROR] addLASchainInfoToTrimEvidence: ambiguous contig %d (%s) vs contig %d (%s) overlap present!\n", aread, aName, bread, bName);
printf(" new LASchain evidence: alnLen %d unAlnLen: %d, erate %f, cutPos: %d collides with: previously added LASchain evidence: alnLen %d unAlnLen: %d, erate %f, cutPos: %d\n", alnLen, unAlnLen, erate, cutPosInA, c->alnLen, c->unalignedBases, c->eRate,
c->trimPos);
return 2;
}
}
c = t->chains + t->nLASchains;
c->alnLen = alnLen;
c->eRate = erate;
c->unalignedBases = unAlnLen;
c->trimPos = cutPosInA;
t->nLASchains++;
// ensure sort order
if (sort)
{
qsort(ctx->trimEvid, ctx->numTrimEvidence, sizeof(TrimEvidence), TrimEvidence_cmp);
}
return result;
}
TrimEvidence*
find_TrimEvidence(TrimContext *ctx, const int contigA, const int contigB)
{
TrimEvidence target;
target.contigA = contigA;
target.contigB = contigB;
return bsearch(&target, ctx->trimEvid, ctx->numTrimEvidence, sizeof(TrimEvidence), TrimEvidence_cmp);
}
TrimEvidence*
insert_TrimEvidence(TrimContext *ctx, const int contigA, const int contigB)
{
if (ctx->numTrimEvidence + 3 >= ctx->maxTrimEvidence)
{
int i = ctx->maxTrimEvidence * 1.2 + 10;
ctx->trimEvid = (TrimEvidence*) realloc(ctx->trimEvid, sizeof(TrimEvidence) * i);
assert(ctx->trimEvid != NULL);
bzero(ctx->trimEvid + ctx->maxTrimEvidence, sizeof(TrimEvidence) * (i - ctx->maxTrimEvidence));
ctx->maxTrimEvidence = i;
}
assert(ctx->trimEvid != NULL);
TrimEvidence *result = ctx->trimEvid + ctx->numTrimEvidence;
ctx->numTrimEvidence++;
result->contigA = contigA;
result->contigB = contigB;
return result;
}
static void trim_pre(PassContext *pctx, TrimContext *tctx)
{
if (tctx->verbose)
{
printf( ANSI_COLOR_GREEN "PASS contig trimming\n" ANSI_COLOR_RESET);
printf( ANSI_COLOR_RED "OPTIONS\n" ANSI_COLOR_RESET);
printf( ANSI_COLOR_RED " verbose %d\n" ANSI_COLOR_RESET, tctx->verbose);
printf( ANSI_COLOR_RED " minBionanoGapLen %d\n" ANSI_COLOR_RESET, tctx->minBionanoGapLen);
printf( ANSI_COLOR_RED " maxTrimLength %d\n" ANSI_COLOR_RESET, tctx->maxTrimLength);
printf( ANSI_COLOR_RED " maxLowCompTrimPerc %d\n" ANSI_COLOR_RESET, tctx->maxLowCompTrimPerc);
printf( ANSI_COLOR_RED " trimOffset %d\n" ANSI_COLOR_RESET, tctx->trimOffset);
printf( ANSI_COLOR_RED " maxFuzzyBases %d\n" ANSI_COLOR_RESET, tctx->maxFuzzyBases);
if (tctx->trackDust)
printf( ANSI_COLOR_RED " dust Track %s\n" ANSI_COLOR_RESET, tctx->trackDust->name);
if (tctx->trackTan)
printf( ANSI_COLOR_RED " tandem Track %s\n" ANSI_COLOR_RESET, tctx->trackTan->name);
}
if (pctx != NULL)
tctx->twidth = pctx->twidth;
tctx->maxTrimEvidence = 100;
tctx->numTrimEvidence = 0;
tctx->trimEvid = (TrimEvidence*) malloc(sizeof(TrimEvidence) * tctx->maxTrimEvidence);
assert(tctx->trimEvid != NULL);
bzero(tctx->trimEvid, sizeof(TrimEvidence) * tctx->maxTrimEvidence);
int i;
tctx->trimCoord = (TrimCoordinates*) malloc(sizeof(TrimCoordinates) * DB_NREADS(tctx->db));
bzero(tctx->trimCoord, sizeof(TrimCoordinates) * DB_NREADS(tctx->db));
for (i = 0; i < DB_NREADS(tctx->db); i++)
{
TrimCoordinates *tc = tctx->trimCoord + i;
tc->numCoordPairs = 1;
tc->maxCoordPairs = 1;
tc->coord = malloc(sizeof(int) * tc->numCoordPairs * 3);
tc->coord[0] = 0;
tc->coord[1] = DB_READ_LEN(tctx->db, i);
tc->coord[2] = 0;
}
}
static void trim_post(TrimContext *ctx)
{
if (ctx->verbose)
{
if (ctx->statsTrimmedContigs > 0)
{
printf("#trimmed contigs %d\n", ctx->statsTrimmedContigs);
}
if (ctx->statsTrimmedBases > 0)
{
printf("#trimmed bases: %d\n", ctx->statsTrimmedBases);
}
if (ctx->statsNumValidLASchains > 0)
{
printf("#valid chains %d\n", ctx->statsNumValidLASchains);
}
if (ctx->statsNumInValidLASchains > 0)
{
printf("#invalid chains %d\n", ctx->statsNumInValidLASchains);
}
if (ctx->statsBionanoTrimmedContigs > 0)
{
printf("Bionano Gaps # contigs trimmed: %d; #trimmed bases: %d\n", ctx->statsBionanoTrimmedContigs, ctx->statsBionanoTrimmedBases);
}
if (ctx->statsBionanoGapsMissed > 0)
{
printf("#not trimmed bionano gaps <= %d: %d\n", ctx->minBionanoGapLen, ctx->statsBionanoGapsMissed);
}
if (ctx->statsBionanoGapsAll > 0)
{
printf("binano agp file: #ALL gaps: %d; #gaps (<= %d bases): %d, #gaps (<= %d bases at ContigBreaks): %d \n", ctx->statsBionanoGapsAll, ctx->minBionanoGapLen, ctx->statsBionanoGapsLtMinThresh, ctx->minBionanoGapLen, ctx->statsBionanoGapsLtMinThreshContigBreak);
}
}
}
int getTrimPositionsFromLAS(TrimContext *ctx, Overlap *ovl, int pointA, int *cutA, int *cutB)
{
int abeg = ovl->path.abpos;
int aend = ovl->path.aepos;
int bbeg = ovl->path.bbpos;
int bend = ovl->path.bepos;
int twidth = ctx->twidth;
if (pointA < abeg || pointA > aend)
return 1;
//printf("getTrimPositions %d x %d, a(%d, %d) %c b(%d, %d) pointA: %d\n", ovl->aread, ovl->bread, abeg, aend, (ovl->flags & OVL_COMP) ? 'C' : 'N', bbeg, bend, pointA);
int dist = pointA - abeg;
int apos, bpos;
if (ovl->path.tlen)
{
ovl_trace *trace = ovl->path.trace;
apos = abeg;
bpos = ovl->path.bbpos;
int j = 0;
while (j < ovl->path.tlen)
{
// printf("apos %6d, bpos %6d, oldDist %6d, newDist %6d\n", apos, bpos, dist, abs(pointA-((apos / twidth + 1) * twidth)));
if (dist < abs(pointA - ((apos / twidth + 1) * twidth)))
break;
apos = (apos / twidth + 1) * twidth;
bpos += trace[j + 1];
//printf("apos %6d, bpos %6d\n", apos, bpos);
dist = abs(pointA - apos);
j += 2;
}
}
else
{
apos = pointA;
bpos = bbeg + dist;
}
// printf("apos: %d, bpos: %d\n", apos, bpos);
*cutA = apos;
*cutB = bpos;
if (*cutA < abeg || *cutA > aend)
return 1;
if (*cutB < bbeg || *cutB > bend)
return 1;
//printf("final range: %d, %d\n", *cutA, *cutB);
return 0;
}
int analyzeContigOverlaps(TrimContext *ctx, Overlap *ovl, int novl)
{
int i;
int aLen = DB_READ_LEN(ctx->db, ovl->aread);
int bLen = DB_READ_LEN(ctx->db, ovl->bread);
char *aName = getContigName(ctx, ovl->aread);
char *bName = getContigName(ctx, ovl->bread);
// assumption: input overlaps must be chained with LAfilterChains !!!
// one chain at the end and one chain at the beginning of a contig are possible! But BOT with the same contigA and contigB
// sanity check
Overlap *o1 = ovl;
int cutA = -1;
int cutB = -1;
if (novl == 1)
{
// check if overlaps is valid
// 1. check if overlap is a valid chain!!
if ((o1->path.abpos > ctx->maxFuzzyBases && o1->path.aepos < aLen - ctx->maxFuzzyBases) || (o1->path.bbpos > ctx->maxFuzzyBases && o1->path.bepos < bLen - ctx->maxFuzzyBases))
{
if (ctx->verbose)
{
printf("[WARNGING] fuzzy base check failed! Ignore invalid chain [%d, %d] a[%d,%d] %c b[%d,%d]!\n", o1->aread, o1->bread, o1->path.abpos, o1->path.aepos, (o1->flags & OVL_COMP) ? 'c' : 'n', o1->path.bbpos, o1->path.bepos);
}
ctx->statsNumInValidLASchains++;
ctx->statsNumInValidLASchainOverlaps += novl;
return 1;
}
// 2. check if one contig is contained within another one!!
else if ((o1->path.abpos <= aLen / 2 && (aLen - o1->path.aepos) <= aLen / 2) || (o1->path.bbpos <= bLen / 2 && (bLen - o1->path.bepos) <= bLen / 2))
{
printf("[WARNGING] Containment found! Ignore invalid chain [%d, %d] a[%d,%d] %c b[%d,%d]!\n", o1->aread, o1->bread, o1->path.abpos, o1->path.aepos, (o1->flags & OVL_COMP) ? 'c' : 'n', o1->path.bbpos, o1->path.bepos);
ctx->statsNumInValidLASchains++;
ctx->statsNumInValidLASchainOverlaps += novl;
return 1;
}
int pointA = o1->path.abpos + (o1->path.aepos - o1->path.abpos) / 2;
if (getTrimPositionsFromLAS(ctx, o1, pointA, &cutA, &cutB))
{
printf("Unable to get cutPosition for OVL [%d,%d] a[%d,%d] %c b[%d,%d] and pointA: %d\n", o1->aread, o1->bread, o1->path.abpos, o1->path.aepos, (o1->flags & OVL_COMP) ? 'c' : 'n', o1->path.bbpos, o1->path.bepos, pointA);
ctx->statsNumInValidLASchains++;
ctx->statsNumInValidLASchainOverlaps += novl;
return 1;
}
assert((cutA - ctx->trimOffset > 0) && (cutA + ctx->trimOffset < aLen));
assert((cutB - ctx->trimOffset > 0) && (cutB + ctx->trimOffset < bLen));
float erate = (200. * ovl->path.diffs) / ((ovl->path.aepos - ovl->path.abpos) + (ovl->path.bepos - ovl->path.bbpos));
int resA = 2;
// set cut position of contig_A
if (o1->path.abpos < aLen - o1->path.aepos) // trim off contig at begin
{
resA = addLASchainInfoToTrimEvidence(ctx, ovl->aread, ovl->bread, ovl->path.aepos - ovl->path.abpos, ovl->path.abpos, erate, -(cutA + ctx->trimOffset));
}
else if (o1->path.abpos > aLen - o1->path.aepos) // trim off contig at end
{
resA = addLASchainInfoToTrimEvidence(ctx, ovl->aread, ovl->bread, ovl->path.aepos - ovl->path.abpos, aLen - ovl->path.aepos, erate, cutA - ctx->trimOffset);
}
else // containment
{
printf("[WARNGING] Containment found! Ignore invalid chain [%d (%s), %d (%s)] a[%d,%d] %c b[%d,%d]!\n", o1->aread, aName, o1->bread, bName, o1->path.abpos, o1->path.aepos, (o1->flags & OVL_COMP) ? 'c' : 'n', o1->path.bbpos, o1->path.bepos);
exit(1);
}
int resB = 2;
// set cut position of contig_B
if (o1->path.bbpos < bLen - o1->path.bepos) // trim off contig at begin
{
if (o1->flags & OVL_COMP)
{
resB = addLASchainInfoToTrimEvidence(ctx, ovl->bread, ovl->aread, ovl->path.bepos - ovl->path.bbpos, ovl->path.bbpos, erate, bLen - (cutB + ctx->trimOffset));
}
else
{
resB = addLASchainInfoToTrimEvidence(ctx, ovl->bread, ovl->aread, ovl->path.bepos - ovl->path.bbpos, ovl->path.bbpos, erate, -(cutB + ctx->trimOffset));
}
}
else if (o1->path.bbpos > bLen - o1->path.bepos) // trim off contig at end
{
if (o1->flags & OVL_COMP)
{
resB = addLASchainInfoToTrimEvidence(ctx, ovl->bread, ovl->aread, ovl->path.bepos - ovl->path.bbpos, bLen - ovl->path.bepos, erate, -(bLen - (cutB - ctx->trimOffset)));
}
else
{
resB = addLASchainInfoToTrimEvidence(ctx, ovl->bread, ovl->aread, ovl->path.bepos - ovl->path.bbpos, bLen - ovl->path.bepos, erate, cutB - ctx->trimOffset);
}
}
assert(resA == resB);
// check return value of res and update stats
if (resA == 2)
{
ctx->statsNumValidLASchains++;
ctx->statsNumValidLASchainOverlaps += novl;
ctx->statsNumDuplicatedChains++;
ctx->statsNumDuplicatedChains += novl;
}
else if (resA == 1)
{
ctx->statsNumValidLASchains++;
ctx->statsNumValidLASchainOverlaps += novl;
ctx->statsNumLASChainsWithBionanoSupport++;
}
else
{
ctx->statsNumValidLASchains++;
ctx->statsNumValidLASchainOverlaps += novl;
ctx->statsNumLASChainsWithoutBionanoSupport++;
}
}
else
{
int validChain = 1;
float avgErate = (200. * o1->path.diffs) / ((o1->path.aepos - o1->path.abpos) + (o1->path.bepos - o1->path.bbpos));
int alignedBasesInA = o1->path.aepos - o1->path.abpos;
int alignedBasesInB = o1->path.bepos - o1->path.bbpos;
int unalignedBasesInA = MIN(o1->path.abpos, aLen - ovl[novl - 1].path.aepos);
int unalignedBasesInB = MIN(o1->path.bbpos, bLen - ovl[novl - 1].path.bepos);
int resA = 2;
int resB = 2;
Overlap *o2;
// first: sanity check for LAS chain
for (i = 1; i < novl; i++)
{
o2 = ovl + i;
if (abs(o1->path.aepos - o2->path.abpos) > ctx->maxFuzzyBases || ((o1->flags & OVL_COMP) != (o2->flags & OVL_COMP)))
{
validChain = 0;
break;
}
alignedBasesInA += (o2->path.aepos - o2->path.abpos);
alignedBasesInB += (o2->path.bepos - o2->path.bbpos);
if (o1->path.aepos > o2->path.abpos)
{
alignedBasesInA -= (o1->path.aepos - o2->path.abpos);
}
else
{
unalignedBasesInA += (o2->path.abpos - o1->path.aepos);
}
if (o1->path.bepos > o2->path.bbpos)
{
alignedBasesInB -= (o1->path.bepos - o2->path.bbpos);
}
else
{
unalignedBasesInB += (o2->path.bbpos - o1->path.bepos);
}
avgErate += (200. * o2->path.diffs) / ((o2->path.aepos - o2->path.abpos) + (o2->path.bepos - o2->path.bbpos));
o1 = o2;
}
// reset overlap pointer o1 and o2 to first and last overlap of LASchain respectively
o1 = ovl;
o2 = ovl + (novl - 1);
avgErate /= novl;
// check for containment
if (validChain)
{
if ((o1->path.abpos <= aLen / 2 && (aLen - o2->path.aepos) <= aLen / 2) || (o1->path.bbpos <= bLen / 2 && (bLen - o2->path.bepos) <= bLen / 2))
{
validChain = 0;
}
if (!validChain)
{
// special case for small contigs, with very good alignments allow up to 2/3 overlap and 1/3 overhang
if (avgErate < 2.0 && unalignedBasesInA < ctx->maxFuzzyBases && unalignedBasesInB < ctx->maxFuzzyBases && (o1->path.abpos >= aLen / 3 || (aLen - o2->path.aepos) >= aLen / 3) && (o1->path.bbpos >= bLen / 3 || (bLen - o2->path.bepos) >= bLen / 3))
{
validChain = 1;
printf("[WARNING] Containment found BUT IS KEPT %d in %d (e %.2f, aln: %d unaln: %d)! Ignore invalid chain [%d (%s), %d (%s)] a[%d,%d] %c b[%d,%d]!\n", o1->aread, o1->bread, avgErate, alignedBasesInA, unalignedBasesInA, o1->aread, aName, o1->bread, bName, o1->path.abpos, o2->path.aepos,
(o1->flags & OVL_COMP) ? 'c' : 'n', o1->path.bbpos, o2->path.bepos);
}
else
{
printf("[WARNING] Containment found %d in %d (e %.2f, aln: %d unaln: %d)! Ignore invalid chain [%d (%s), %d (%s)] a[%d,%d] %c b[%d,%d]!\n", o1->aread, o1->bread, avgErate, alignedBasesInA, unalignedBasesInA, o1->aread, aName, o1->bread, bName, o1->path.abpos, o2->path.aepos,
(o1->flags & OVL_COMP) ? 'c' : 'n', o1->path.bbpos, o2->path.bepos);
}
}
}
if (!validChain)
{
ctx->statsNumInValidLASchains++;
ctx->statsNumInValidLASchainOverlaps += novl;
if (ctx->verbose)
{
printf("INVALID chain: %d (%s) vs %d (%s)\n", ovl->aread, aName, ovl->bread, bName);
for (i = 0; i < novl; i++)
{
printf(" a[%d,%d] %c b[%d,%d]\n", ovl[i].path.abpos, ovl[i].path.aepos, (ovl[i].flags & OVL_COMP) ? 'c' : 'n', ovl[i].path.bbpos, ovl[i].path.bepos);
}
}
return 1;
}
// set cut position of contig_A
if (o1->path.abpos < aLen - o2->path.aepos) // trim off contig at begin
{
if (o2->path.abpos >= o1->path.aepos)
{
cutA = o2->path.abpos + ctx->trimOffset;
}
else
{
cutA = o1->path.aepos + ctx->trimOffset;
}
resA = addLASchainInfoToTrimEvidence(ctx, o1->aread, o1->bread, alignedBasesInA, unalignedBasesInA, avgErate, -(cutA));
}
else if (o1->path.abpos > aLen - o2->path.aepos) // trim off contig at end
{
if (o2->path.abpos >= o1->path.aepos)
{
cutA = o1->path.aepos - ctx->trimOffset;
}
else
{
cutA = o2->path.abpos - ctx->trimOffset;
}
resA = addLASchainInfoToTrimEvidence(ctx, o1->aread, o1->bread, alignedBasesInA, unalignedBasesInA, avgErate, cutA);
}
else // containment
{
printf("Contained overlap (c1): [%d (%s),%d (%s)] a[%d,%d] %c b[%d,%d]\n", o1->aread, aName, o1->bread, bName, o1->path.abpos, o1->path.aepos, (o1->flags & OVL_COMP) ? 'c' : 'n', o1->path.bbpos, o1->path.bepos);
ctx->statsNumInValidLASchains++;
ctx->statsNumInValidLASchainOverlaps += novl;
return 1;
}
// set cut position of contig_B
if (o1->path.bbpos < bLen - o2->path.bepos) // trim off contig at begin
{
if (o2->path.bbpos >= o1->path.bepos)
{
cutB = o2->path.bbpos + ctx->trimOffset;
if (o1->flags & OVL_COMP)
{
resB = addLASchainInfoToTrimEvidence(ctx, o1->bread, o1->aread, alignedBasesInB, unalignedBasesInB, avgErate, bLen - cutB);
}
else
{
resB = addLASchainInfoToTrimEvidence(ctx, o1->bread, o1->aread, alignedBasesInB, unalignedBasesInB, avgErate, -(cutB));
}
}
else
{
cutB = o1->path.bepos + ctx->trimOffset;
if (o1->flags & OVL_COMP)
{
resB = addLASchainInfoToTrimEvidence(ctx, o1->bread, o1->aread, alignedBasesInB, unalignedBasesInB, avgErate, bLen - cutB);
}
else
{
resB = addLASchainInfoToTrimEvidence(ctx, o1->bread, o1->aread, alignedBasesInB, unalignedBasesInB, avgErate, -(cutB));
}
}
}
else if (o1->path.bbpos > bLen - o2->path.bepos) // trim off contig at end
{
if (o2->path.bbpos >= o1->path.bepos)
{
cutB = o1->path.bepos - ctx->trimOffset;
if (o1->flags & OVL_COMP)
{
resB = addLASchainInfoToTrimEvidence(ctx, o1->bread, o1->aread, alignedBasesInB, unalignedBasesInB, avgErate, -(bLen - cutB));
}
else
{
resB = addLASchainInfoToTrimEvidence(ctx, o1->bread, o1->aread, alignedBasesInB, unalignedBasesInB, avgErate, cutB);
}
}
else
{
cutB = o2->path.bbpos - ctx->trimOffset;
if (o1->flags & OVL_COMP)
{
resB = addLASchainInfoToTrimEvidence(ctx, o1->bread, o1->aread, alignedBasesInB, unalignedBasesInB, avgErate, -(bLen - cutB));
}
else
{
resB = addLASchainInfoToTrimEvidence(ctx, o1->bread, o1->aread, alignedBasesInB, unalignedBasesInB, avgErate, cutB);
}
}
}
else // containment
{
printf("Contained overlap (c2): [%d (%s),%d (%s)] a[%d,%d] %c b[%d,%d]\n", o1->aread, aName, o1->bread, bName, o1->path.abpos, o1->path.aepos, (o1->flags & OVL_COMP) ? 'c' : 'n', o1->path.bbpos, o1->path.bepos);
ctx->statsNumInValidLASchains++;
ctx->statsNumInValidLASchainOverlaps += novl;
return 1;
}
assert(resA == resB);
// check return value of res and update stats
if (resA == 2)
{
ctx->statsNumValidLASchains++;
ctx->statsNumValidLASchainOverlaps += novl;
ctx->statsNumDuplicatedChains++;
ctx->statsNumDuplicatedChains += novl;
}
else if (resA == 1)
{
ctx->statsNumValidLASchains++;
ctx->statsNumValidLASchainOverlaps += novl;
ctx->statsNumLASChainsWithBionanoSupport++;
}
else
{
ctx->statsNumValidLASchains++;
ctx->statsNumValidLASchainOverlaps += novl;
ctx->statsNumLASChainsWithoutBionanoSupport++;
}
}
return 0;
}
static int trim_handler(void *_ctx, Overlap *ovl, int novl)
{
TrimContext *ctx = (TrimContext*) _ctx;
// analyze overlaps and find contig trim position
analyzeContigOverlaps(ctx, ovl, novl);
return 1;
}
int getMaskedBases(TrimContext *ctx, HITS_TRACK *t, int contigID, int beg, int end)
{
#ifdef DEBUG_MASKING
printf("call getMaskedBases on track %s, contigID: %d, in: [%d, %d]\n", t->name, contigID, beg, end);
#endif
if (t == NULL)
{
#ifdef DEBUG_MASKING
printf(" --> masked bases 0 (track is Null)\n");
#endif
return 0;
}
track_anno *mask_anno = t->anno;
track_data *mask_data = t->data;
if (contigID < 0 || contigID >= DB_NREADS(ctx->db))
{
fprintf(stderr, "[ERROR] - getMaskedBases contigID: %d out of bounds [0, %d]\n", contigID, DB_NREADS(ctx->db) - 1);
fflush(stderr);
exit(1);
}
track_anno rb, re;
int maskBases = 0;
int rBeg, rEnd;
// repeat bases in a-read
rb = mask_anno[contigID] / sizeof(track_data);
re = mask_anno[contigID + 1] / sizeof(track_data);
while (rb < re)
{
rBeg = mask_data[rb];
rEnd = mask_data[rb + 1];
maskBases += intersect(beg, end, rBeg, rEnd);
#ifdef DEBUG_MASKING2
printf(" repInterval: [%d, %d] intersection with [%d, %d] is %d. cum sum %d\n", rBeg, rEnd, beg, end, intersect(beg, end, rBeg, rEnd), maskBases);
#endif
rb += 2;
}
#ifdef DEBUG_MASKING
printf(" --> masked bases %d\n", maskBases);
#endif
return maskBases;
}
char* trimwhitespace(char *str)
{
//printf("trimwhitespace: %s\n", str);
char *end;
// Trim leading space
while (isspace(*str))
str++;
if (*str == 0) // All spaces?
return str;
// Trim trailing space
end = str + strlen(str) - 1;
while (end > str && isspace(*end))
end--;
// Write new null terminator
*(end + 1) = '\0';
return str;
}
int getDBcontigID(TrimContext *ctx, char *contigName, int *from, int *to)
{
// printf("getDBcontigID(%s)\n", contigName);
int i;
for (i = 0; i < ctx->nfiles; i++)
{
if (strcmp(ctx->flist[i], contigName) == 0)
{
return i;
}
}
int cNameLen;
char *pchrf, *pchrl;
pchrf = strstr(contigName, "_subseq_");
if (pchrf == NULL)
return -1;
pchrl = strstr(pchrf, ":");
if (pchrl == NULL)
return -1;
int agpCNameLen = pchrf - contigName;
// printf("contigNameLen from %s is %d\n", contigName, agpCNameLen);
for (i = 0; i < ctx->nfiles; i++)
{
cNameLen = strlen(ctx->flist[i]);
if (agpCNameLen == cNameLen && strncmp(ctx->flist[i], contigName, cNameLen) == 0)
{
*pchrl = '\0';
*from = strtol(pchrf + 8, NULL, 10);
*pchrl = ':';
*to = strtol(pchrl + 1, NULL, 10);
// printf("found: from: %d and to: %d\n", *from, *to);
// sanity checks
if (*from < 1 || *from > *to || *from > DB_READ_LEN(ctx->db, i) || *to > DB_READ_LEN(ctx->db, i))
{
*from = -1;
*to = -1;
return -1;
}
return i;
}
}
return -1;
}
void parseBionanoGAPfile(TrimContext *ctx, char *pathInBionanoGAP)
{
FILE *fileInBionanoGaps = NULL;
if ((fileInBionanoGaps = fopen(pathInBionanoGAP, "r")) == NULL)
{
fprintf(stderr, "[ERROR] could not open %s\n", pathInBionanoGAP);
exit(1);
}
char NGSId1[MAX_NAME];
char NGSId2[MAX_NAME];
int SuperScaffoldId;
int XmapGapLength;
int AdjustedGapLength;
float NGSLength1;
float NGSLength2;
char *line = NULL;
size_t maxline = 0;
int nline = 0;
int len;
int r;
int contigA = -1;
int contigB = -1;
int numInvalidLines = 0;
printf("parseBionanoGapfile: %s\n", pathInBionanoGAP);
while ((len = getline(&line, &maxline, fileInBionanoGaps)) > 0)
{
nline++;
char *tline = trimwhitespace(line);
if (tline[0] == '#')
continue;
r = sscanf(tline, "%s\t%s\t%d\t%d\t%d\t%f\t%f\n", NGSId1, NGSId2, &SuperScaffoldId, &XmapGapLength, &AdjustedGapLength, &NGSLength1, &NGSLength2);
if (r != 7)
{
fprintf(stderr, "[ERROR] invalid bionano GAP file format %s. Expecting 7 columns, BUT parsed %d columns in line %d\n", pathInBionanoGAP, r, nline);
exit(1);
}
// printf("line %d: %s\n", nline, tline);
// try to match contig name with with DB contig ID
int aPartBeg = -1;
int aPartEnd = -1;
int bPartBeg = -1;
int bPartEnd = -1;
contigA = getDBcontigID(ctx, NGSId1, &aPartBeg, &aPartEnd);
contigB = getDBcontigID(ctx, NGSId2, &bPartBeg, &bPartEnd);
if (contigA < 0 || contigB < 0)
{
printf("[WARNING] Could not match GAP contig names: %s and/or %s in current db! Ignore line %d in GAP file %s.\n", NGSId1, NGSId2, nline, pathInBionanoGAP);
numInvalidLines++;
continue;
}
// contig orientation is unknown !!!!
if (aPartBeg < 0 || aPartEnd < 0)
{
aPartBeg = 1;
aPartEnd = DB_READ_LEN(ctx->db, contigA);
}
if (bPartBeg < 0 || bPartEnd < 0)
{
bPartBeg = 1;
bPartEnd = DB_READ_LEN(ctx->db, contigB);
}
assert(aPartBeg < aPartEnd);
assert(bPartBeg < bPartEnd);
// ignore lines were contigA equals contigB. Why do they exist?
if (contigA == contigB)
{
continue;
}
addBionanoGAPInfoToTrimEvidence(ctx, contigA, aPartBeg, aPartEnd, contigB, bPartBeg, bPartEnd, AdjustedGapLength);
}
int negativeGaps = 0;
int i, j;
for (i = 0; i < ctx->numTrimEvidence; i++)
{
TrimEvidence *t = ctx->trimEvid + i;
if (t->contigA > t->contigB)
continue;
for (j = 0; j < t->nBioNanoGaps; j++)
{
BionanoGap *b = t->gaps + j;
if (b->bionanoGapSize < 0)
negativeGaps++;
}
}
printf("[INFO] Number of invalid lines: %d (either format issues, or AGP contig names could not be matched to DB contig names.)\n", numInvalidLines);
printf("[INFO] #Bionano gaps < 0: %10d\n", negativeGaps);
free(line);
fclose(fileInBionanoGaps);
}
void printBionanpGap(TrimContext *ctx, int contigA, int contigB, BionanoGap *g)
{
assert(g != NULL);
char *aName = getContigName(ctx, contigA);
char *bName = getContigName(ctx, contigB);
printf("Bionano Gap: %d(%s)[%d,%d]-------GAP[%d, %d]------%d(%s)[%d,%d]\n", contigA, aName, g->aBeg, g->aEnd, g->agpGapSize, g->bionanoGapSize, contigB, bName, g->bBeg, g->bEnd);
}
void printLASchain(TrimContext *ctx, int contigA, int contigB, LASchain *c)
{
assert(c != NULL);
char *aName = getContigName(ctx, contigA);
char *bName = getContigName(ctx, contigB);
printf("LASchain: %3d (%s) vs %3d (%s): #alnBases: %6d #unalnBases: %6d eRate: %5.2f trimPosOfA: %6d\n", contigA, aName, contigB, bName, c->alnLen, c->unalignedBases, c->eRate, c->trimPos);
}
void addBionanoContigCoordinates(TrimContext *ctx, int contig, int from, int to)
{
// some sanity checks
int i;
if (from > to)
{
i = from;
from = to;
to = i;
}
printf("call addBionanoContigCoordinates(TrimContext *ctx, %d, %d, %d)\n", contig, from, to);
from--;
printf("change coordinate system from 1-based [%d, %d, x] to 0-based [%d,%d)", from+1, to, from ,to);
assert(ctx != NULL);
assert(contig >= 0);
assert(contig < DB_NREADS(ctx->db));
assert(from >= 0);
assert(to <= DB_READ_LEN(ctx->db, contig));
TrimCoordinates *tc = ctx->trimCoord + contig;
// ignore full contig lengths
if (to - from + 1 >= DB_READ_LEN(ctx->db, contig))
{
printf("[WARNING]: Ignore full contig: %d %d %d\n", contig, from, to);
return;
}
// check if coordinates are already present
for (i = 0; i < tc->numCoordPairs; i++)
{
int its=intersect(tc->coord[i*3],tc->coord[i*3+1], from, to);
if(its)
{
printf("replace trim coordinates at %d [%d, %d, %d] with [%d, %d, %d] overlap: %d\n", i, tc->coord[i*3], tc->coord[i*3+1], tc->coord[i*3+2], from, to, 0, its);
tc->coord[i*3] = from;
tc->coord[i*3+1] = to;
break;
}
}
if(i==tc->numCoordPairs)
{
printf("append new trim Coordinates to position %d [%d, %d, %d]", i, from, to, 0);
if(tc->numCoordPairs + 1 >= tc->maxCoordPairs)
{
tc->maxCoordPairs = tc->numCoordPairs + 1;
tc->coord = (int *) realloc(tc->coord, sizeof(int)*3*tc->maxCoordPairs);
}
tc->coord[i*3] = from;
tc->coord[i*3+1] = to;
tc->coord[i*3+2] = 0;
tc->numCoordPairs++;
}
}
void parseBionanoAGPfile(TrimContext *ctx, char *pathInBionanoAGP)
{
FILE *fileInBionanoGaps = NULL;
if ((fileInBionanoGaps = fopen(pathInBionanoAGP, "r")) == NULL)
{
fprintf(stderr, "[ERROR] could not open %s\n", pathInBionanoAGP);
exit(1);
}
char Prev_Obj_Name[MAX_NAME];
char Obj_Name[MAX_NAME];
int Obj_Start;
int Obj_End;
int PartNum;
char Compnt_Type;
char CompntId_GapLength[MAX_NAME];
char CompntStart_GapType[MAX_NAME];
char CompntEnd_Linkage[MAX_NAME];
char Orientation_LinkageEvidence[MAX_NAME];
char *line = NULL;
size_t maxline = 0;
int nline = 0;
int len;
int r;
int contigA = -1;
int oriA = 0;
int fromA, toA;
char contigNameA[MAX_NAME];
int gapLen = -1;
int contigB = -1;
int oriB = 0;
int fromB, toB;
char contigNameB[MAX_NAME];
printf("[INFO] parseBionanoAGPfile: %s\n", pathInBionanoAGP);
int numInvalidLines = 0;
int prevContigID = -1;
int Prev_PartNum = -1;
while ((len = getline(&line, &maxline, fileInBionanoGaps)) > 0)
{
nline++;
char *tline = trimwhitespace(line);
if (tline[0] == '#')
continue;
r = sscanf(tline, "%s\t%d\t%d\t%d\t%c\t%s\t%s\t%s\t%s\n", Obj_Name, &Obj_Start, &Obj_End, &PartNum, &Compnt_Type, CompntId_GapLength, CompntStart_GapType, CompntEnd_Linkage, Orientation_LinkageEvidence);
if (r != 9)
{
fprintf(stderr, "[ERROR] invalid AGP file format %s. Expecting 9 columns, BUT parsed %d columns in line %d\n", pathInBionanoAGP, r, nline);
exit(1);
}
if (ctx->verbose > 2)
printf("line %d: %s\n", nline, tline);
// try to match contig name with with DB contig ID
if (Compnt_Type == 'W')
{
int from = -1;
int to = -1;
if (strcmp(Prev_Obj_Name, Obj_Name) != 0)
{
if (Prev_PartNum == 1)
{
printf(" SINGLETON ContigA %d prev: %s cur: %s\n", prevContigID, Prev_Obj_Name, Obj_Name);
}
strcpy(Prev_Obj_Name, Obj_Name);
contigA = getDBcontigID(ctx, CompntId_GapLength, &from, &to);
strcpy(contigNameA, CompntId_GapLength);
if (contigA < 0)
{
printf("[WARNING] Could not match agp contig name: %s in current db! Ignore AGP file.\n", CompntId_GapLength);
Prev_Obj_Name[0] = '\0'; // restart from scratch
numInvalidLines++;
continue;
}
if (strcmp(Orientation_LinkageEvidence, "+") == 0)
{
oriA = 1;
}
else if (strcmp(Orientation_LinkageEvidence, "-") == 0)
{
oriA = -1;
}
else
{
fprintf(stderr, "[ERROR] invalid AGP file format %s. Unknown orientation %s in line %d\n", pathInBionanoAGP, Orientation_LinkageEvidence, nline);
Prev_Obj_Name[0] = '\0'; // restart from scratch
numInvalidLines++;
continue;
}
if (from == -1)
{
from = 1;
to = DB_READ_LEN(ctx->db, contigA);
}
if (oriA < 0)
{
fromA = to;
toA = from;
}
else
{
fromA = from;
toA = to;
}
Prev_PartNum = PartNum;
prevContigID = contigA;
// add trim coordinates
addBionanoContigCoordinates(ctx, contigA, fromA, toA);
}
else
{
Prev_PartNum = PartNum;
contigB = getDBcontigID(ctx, CompntId_GapLength, &from, &to);
strcpy(contigNameB, CompntId_GapLength);
if (contigB < 0)
{
printf("[WARNING] Could not match agp contig name: %s in current db! Ignore AGP file.\n", CompntId_GapLength);
Prev_Obj_Name[0] = '\0'; // restart from scratch
numInvalidLines++;
continue;
}
if (strcmp(Orientation_LinkageEvidence, "+") == 0)
{
oriB = 1;
}
else if (strcmp(Orientation_LinkageEvidence, "-") == 0)
{
oriB = -1;
}
else
{
fprintf(stderr, "[ERROR] invalid AGP file format %s. Unknown orientation %s in line %d\n", pathInBionanoAGP, Orientation_LinkageEvidence, nline);
Prev_Obj_Name[0] = '\0'; // restart from scratch
numInvalidLines++;
continue;
}
if (from == -1)
{
from = 1;
to = DB_READ_LEN(ctx->db, contigB);
}
if (oriB < 0)
{
fromB = to;
toB = from;
}
else
{
fromB = from;
toB = to;
}
printf("2: fromB: %d, toB: %d\n", fromB, toB);
assert(gapLen > -1);
// add trim evidence symmetrically: i.e. contigA-gap-contigB and contigB-gap-contigA
// change coordinate system from 1-based [1, x] to 0-based [0,x)
addBionanoAGPInfoToTrimEvidence(ctx, contigA, fromA-1, toA, contigB, fromB-1, toB, gapLen);
contigA = contigB;
strcpy(contigNameA, contigNameB);
oriA = oriB;
fromA = fromB;
toA = toB;
// reset gap size
gapLen = -1;
// add trim coordinates
addBionanoContigCoordinates(ctx, contigB, fromB, toB);
//fprintf(stdout, "Assign B to A: ContigA[%d,%s,%d,%d,%d] - GAP [%d] - ContigB[%d,%s,%d,%d,%d]\n", contigA, contigNameA, oriA, fromA, toA, gapLen, contigB, contigNameB, oriB, fromB, toB);
}
}
else if (Compnt_Type == 'N')
{
//printf("found gap\n");
gapLen = strtol(CompntId_GapLength, NULL, 10);
if (gapLen < 1)
{
//fprintf(stderr, "[ERROR] invalid AGP file format %s. Negative gap length: %s in line %d\n", pathInBionanoAGP, CompntId_GapLength, nline);
}
}
}
if (Prev_PartNum == 1)
{
printf(" SINGLETON ContigA %d prev: %s cur: %s\n", prevContigID, Prev_Obj_Name, Obj_Name);
}
printf("[INFO] Number of invalid lines: %d (either format issues, or AGP contig names could not be matched to DB contig names.)\n", numInvalidLines);
int numGaps = 0;
int numGapsSmallerThreshold = 0;
int numContigBreaksPartOfAGap = 0;
int numContigBreaksNotClosable = 0;
int i, j;
for (i = 0; i < ctx->numTrimEvidence; i++)
{
TrimEvidence *t = ctx->trimEvid + i;
if (t->contigA > t->contigB)
continue;
int aLen = DB_READ_LEN(ctx->db, t->contigA);
int bLen = DB_READ_LEN(ctx->db, t->contigB);
for (j = 0; j < t->nBioNanoGaps; j++)
{
BionanoGap *b = t->gaps + j;
if (ctx->verbose)
printBionanpGap(ctx, t->contigA, t->contigB, b);
numGaps++;
if (b->agpGapSize <= ctx->minBionanoGapLen)
{
numGapsSmallerThreshold++;
}
if ((b->aBeg != 1 && b->aBeg != aLen) || (b->aEnd != 1 && b->aEnd != aLen))
{
numContigBreaksPartOfAGap++;
if (ctx->verbose)
{
printf("BreaksPartOfAGap: if ((b->aBeg != 1 && b->aBeg != aLen) || (b->aEnd != 1 && b->aEnd != aLen))\n");
printBionanpGap(ctx, t->contigA, t->contigB, b);
}
}
else if ((b->bBeg != 1 && b->bBeg != bLen) || (b->bEnd != 1 && b->bEnd != bLen))
{
numContigBreaksPartOfAGap++;
if (ctx->verbose)
{
printf("BreaksPartOfAGap: if ((b->bBeg != 1 && b->bBeg != bLen) || (b->bEnd != 1 && b->bEnd != bLen))\n");
printBionanpGap(ctx, t->contigA, t->contigB, b);
}
}
if ((b->aEnd != 1 && b->aEnd != aLen) || (b->bBeg != 1 && b->bBeg != bLen))
{
numContigBreaksNotClosable++;
if (ctx->verbose)
{
printf("NotClosable: if((b->aEnd != 1 && b->aEnd != aLen) || (b->bBeg != 1 && b->bBeg != bLen))\n");
printBionanpGap(ctx, t->contigA, t->contigB, b);
}
}
}
}
ctx->statsBionanoGapsAll = numGaps;
ctx->statsBionanoGapsLtMinThresh = numGapsSmallerThreshold;
ctx->statsBionanoContigBreaksPartOfAGap = numContigBreaksPartOfAGap;
ctx->statsBionanoContigBreaksNotClosable = numContigBreaksNotClosable;
printf("[INFO] #BionanoGaps: %15d\n", numGaps);
printf("[INFO] #BionanoGaps (<= %d): %7d\n", ctx->minBionanoGapLen, numGapsSmallerThreshold);
printf("[INFO] #ContigBreaksPartOfAGap: %4d\n", numContigBreaksPartOfAGap);
printf("[INFO] #ContigBreaksNotClosable: %3d\n", numContigBreaksNotClosable);
free(line);
fclose(fileInBionanoGaps);
}
void getDBFastaHeader(TrimContext *ctx, char *fullDBPath)
{
char *pwd, *root;
FILE *dstub;
int i;
root = Root(fullDBPath, ".db");
pwd = PathTo(fullDBPath);
if (ctx->db->part > 0)
{
fprintf(stderr, "[ERROR] - CTtrim can not work on blocks!");
exit(1);
}
dstub = Fopen(Catenate(pwd, "/", root, ".db"), "r");
if (dstub == NULL)
{
fprintf(stderr, "[ERROR] - Cannot open database file: %s\n", Catenate(pwd, "/", root, ".db"));
exit(1);
}
free(pwd);
free(root);
if (fscanf(dstub, DB_NFILE, &(ctx->nfiles)) != 1)
{
fclose(dstub);
fprintf(stderr, "[ERROR] - Cannot read files line '%s' in database file: %s\n",
DB_NFILE, Catenate(pwd, "/", root, ".db"));
exit(1);
}
ctx->flist = (char**) Malloc(sizeof(char*) * ctx->nfiles, "Allocating file list");
ctx->hlist = (char**) Malloc(sizeof(char*) * ctx->nfiles, "Allocating header list");
ctx->findx = (int*) Malloc(sizeof(int*) * (ctx->nfiles + 1), "Allocating file index");
if (ctx->flist == NULL || ctx->findx == NULL || ctx->hlist == NULL)
{
fclose(dstub);
fprintf(stderr, "[ERROR] - Cannot allocate file name and file index buffers!");
exit(1);
}
ctx->findx += 1;
ctx->findx[-1] = 0;
for (i = 0; i < ctx->nfiles; i++)
{
char headername[MAX_NAME], filename[MAX_NAME];
if (fscanf(dstub, DB_FDATA, ctx->findx + i, filename, headername) != 3)
{
fclose(dstub);
fprintf(stderr, "[ERROR] - Cannot read %d-th fasta entry in database file %s\n", i + 1, Catenate(pwd, "/", root, ".db"));
exit(1);
}
if ((ctx->flist[i] = Strdup(filename, "Adding to file list")) == NULL)
exit(1);
if ((ctx->hlist[i] = Strdup(headername, "Adding to file list")) == NULL)
exit(1);
}
fclose(dstub);
}
//void trim_contigs(TrimContext *ctx)
/*{
// open file handler
FILE *trimmedContigsAll = NULL;
FILE *purgedContigsAll = NULL;
FILE *statsContigsAll = NULL;
FILE *trimmedContigsNoTandem = NULL;
FILE *purgedContigsNoTandem = NULL;
FILE *statsContigsNoTandem = NULL;
char *fout = malloc(strlen(ctx->fileOutPattern) + 50);
assert(fout != NULL);
sprintf(fout, "%s.trimmedContigs.fasta", ctx->fileOutPattern);
printf("create file: %s\n", fout);
if ((trimmedContigsAll = (FILE*) fopen(fout, "w")) == NULL)
{
fprintf(stderr, "[ERROR] - could not open file %s\n", fout);
exit(1);
}
sprintf(fout, "%s.purgedContigs.fasta", ctx->fileOutPattern);
if ((purgedContigsAll = (FILE*) fopen(fout, "w")) == NULL)
{
fprintf(stderr, "[ERROR] - could not open file %s\n", fout);
exit(1);
}
sprintf(fout, "%s.trimmedContigs.stats", ctx->fileOutPattern);
if ((statsContigsAll = (FILE*) fopen(fout, "w")) == NULL)
{
fprintf(stderr, "[ERROR] - could not open file %s\n", fout);
exit(1);
}
sprintf(fout, "%s.ignoreTANtrimmedContigs.fasta", ctx->fileOutPattern);
printf("create file: %s\n", fout);
if ((trimmedContigsNoTandem = (FILE*) fopen(fout, "w")) == NULL)
{
fprintf(stderr, "[ERROR] - could not open file %s\n", fout);
exit(1);
}
sprintf(fout, "%s.ignoreTANpurgedContigs.fasta", ctx->fileOutPattern);
if ((purgedContigsNoTandem = (FILE*) fopen(fout, "w")) == NULL)
{
fprintf(stderr, "[ERROR] - could not open file %s\n", fout);
exit(1);
}
sprintf(fout, "%s.ignoreTANtrimmedContigs.stats", ctx->fileOutPattern);
if ((statsContigsNoTandem = (FILE*) fopen(fout, "w")) == NULL)
{
fprintf(stderr, "[ERROR] - could not open file %s\n", fout);
exit(1);
}
fprintf(statsContigsAll, "#ContigID\tContigName\tnewContigLength\ttrimBegin\ttrimEnd\tcomments\n");
fprintf(statsContigsNoTandem, "#ContigID\tContigName\tnewContigLength\ttrimBegin\ttrimEnd\tcomments\n");
// debug report trim positions
int nContigs = DB_NREADS(ctx->db);
int i, j;
char *read = New_Read_Buffer(ctx->db);
for (i = 0; i < nContigs; i++)
{
int maxBeg = 0;
int maxBegContigID = -1;
int cLen = DB_READ_LEN(ctx->db, i);
int minEnd = cLen;
int minEndContigID = -1;
for (j = 0; j < nContigs; j++)
{
int cutPos = ctx->LAStrimMatrix[i * nContigs + j];
if (cutPos < 0 && abs(cutPos) > maxBeg)
{
maxBeg = abs(cutPos);
maxBegContigID = j;
}
if (cutPos > 0 && cutPos < minEnd)
{
minEnd = cutPos;
minEndContigID = j;
}
if (cutPos != 0)
printf("FOUND CONTIG TRIM POSITION: CONTIG %d; TRIM: %d, TRIMLEN (%d) (OVL with: %d)\n", i, cutPos, (cutPos < 0) ? abs(cutPos) : cLen - cutPos, j);
}
float dustBegFract, dustEndFract, tanBegFract, tanEndFract;
dustBegFract = dustEndFract = tanBegFract = tanEndFract = 0.0;
if (maxBeg > 0 || minEnd != cLen)
{
if (maxBeg > 0)
{
dustBegFract = getMaskedBases(ctx, ctx->trackDust, i, 0, maxBeg) * 100.0 / maxBeg;
tanBegFract = getMaskedBases(ctx, ctx->trackTan, i, 0, maxBeg) * 100.0 / maxBeg;
}
if (minEnd != cLen)
{
dustEndFract = getMaskedBases(ctx, ctx->trackDust, i, minEnd, cLen * 100.0 / cLen - minEnd);
tanEndFract = getMaskedBases(ctx, ctx->trackTan, i, minEnd, cLen * 100.0 / cLen - minEnd);
}
printf(" --> final trim Interval: [%d, %d] -> trimmed [%d, %d] dustFract(in %%) [%.2f, %.2f] tanFract(in %%) [%.2f,%.2f]\n", maxBeg, minEnd, maxBeg, cLen - minEnd, dustBegFract, dustEndFract, tanBegFract, tanEndFract);
}
// int flags, qv;
int map = 0;
while (i < ctx->findx[map - 1])
map -= 1;
while (i >= ctx->findx[map])
map += 1;
Load_Read(ctx->db, i, read, 2);
// write out trimmed contigs
{
fprintf(trimmedContigsAll, ">%s\n", ctx->flist[map]);
for (j = maxBeg; j + ctx->lineWidth < minEnd; j += ctx->lineWidth)
fprintf(trimmedContigsAll, "%.*s\n", ctx->lineWidth, read + j);
if (j < minEnd)
fprintf(trimmedContigsAll, "%.*s\n", minEnd - j, read + j);
// write out purged sequence at begin of contig
if (maxBeg > 0)
{
fprintf(purgedContigsAll, ">%s purged=%d,%d purgedLen=%d\n", ctx->flist[map], 0, maxBeg, maxBeg);
for (j = 0; j + ctx->lineWidth < maxBeg; j += ctx->lineWidth)
fprintf(purgedContigsAll, "%.*s\n", ctx->lineWidth, read + j);
if (j < maxBeg)
fprintf(purgedContigsAll, "%.*s\n", maxBeg - j, read + j);
}
// write out purged sequence at end of contig
if (minEnd < cLen)
{
fprintf(purgedContigsAll, ">%s purged=%d,%d purgedLen=%d\n", ctx->flist[map], minEnd, cLen, cLen - minEnd);
for (j = minEnd; j + ctx->lineWidth < cLen; j += ctx->lineWidth)
fprintf(purgedContigsAll, "%.*s\n", ctx->lineWidth, read + j);
if (j < cLen)
fprintf(purgedContigsAll, "%.*s\n", cLen - j, read + j);
}
fprintf(statsContigsAll, "%d\t%s\t%d\t%d\t%d\ttrimBeg:LC=%.2f%%,TAN=%.2f%%;trimEnd=LC=%.2f%%,TAN=%.2f%%", i, ctx->flist[map], minEnd - maxBeg, maxBeg, cLen - minEnd, dustBegFract, tanBegFract, dustEndFract, tanEndFract);
// contig support for trimBegin
if (maxBeg != 0)
{
int bmap = 0;
while (maxBegContigID < ctx->findx[bmap - 1])
bmap -= 1;
while (maxBegContigID >= ctx->findx[bmap])
bmap += 1;
fprintf(statsContigsAll, ";trimBegSupport:ID=%d,name=%s", maxBegContigID, ctx->flist[bmap]);
}
// contig support for trimEnd
if (minEnd != cLen)
{
int bmap = 0;
while (minEndContigID < ctx->findx[bmap - 1])
bmap -= 1;
while (minEndContigID >= ctx->findx[bmap])
bmap += 1;
fprintf(statsContigsAll, ";trimEndSupport:ID=%d,name=%s", minEndContigID, ctx->flist[bmap]);
}
fprintf(statsContigsAll, "\n");
}
// write out trimmed contigs but ignore tandem-induced overlaps
{
int tanMaxBeg = maxBeg;
int tanMinEnd = minEnd;
if (dustBegFract > ctx->maxLowCompTrimPerc || tanBegFract > ctx->maxLowCompTrimPerc)
{
tanMaxBeg = 0;
}
if (dustEndFract > ctx->maxLowCompTrimPerc || tanEndFract > ctx->maxLowCompTrimPerc)
{
tanMinEnd = cLen;
}
fprintf(trimmedContigsNoTandem, ">%s\n", ctx->flist[map]);
for (j = tanMaxBeg; j + ctx->lineWidth < tanMinEnd; j += ctx->lineWidth)
fprintf(trimmedContigsNoTandem, "%.*s\n", ctx->lineWidth, read + j);
if (j < tanMinEnd)
fprintf(trimmedContigsNoTandem, "%.*s\n", tanMinEnd - j, read + j);
// write out purged sequence at begin of contig
if (tanMaxBeg > 0)
{
fprintf(purgedContigsNoTandem, ">%s purged=%d,%d purgedLen=%d\n", ctx->flist[map], 0, tanMaxBeg, tanMaxBeg);
for (j = 0; j + ctx->lineWidth < tanMaxBeg; j += ctx->lineWidth)
fprintf(purgedContigsNoTandem, "%.*s\n", ctx->lineWidth, read + j);
if (j < tanMaxBeg)
fprintf(purgedContigsNoTandem, "%.*s\n", tanMaxBeg - j, read + j);
}
// write out purged sequence at end of contig
if (tanMinEnd < cLen)
{
fprintf(purgedContigsNoTandem, ">%s purged=%d,%d purgedLen=%d\n", ctx->flist[map], tanMinEnd, cLen, cLen - tanMinEnd);
for (j = tanMinEnd; j + ctx->lineWidth < cLen; j += ctx->lineWidth)
fprintf(purgedContigsNoTandem, "%.*s\n", ctx->lineWidth, read + j);
if (j < cLen)
fprintf(purgedContigsNoTandem, "%.*s\n", cLen - j, read + j);
}
fprintf(statsContigsNoTandem, "%d\t%s\t%d\t%d\t%d\ttrimBeg:LC=%.2f%%,TAN=%.2f%%;trimEnd=LC=%.2f%%,TAN=%.2f%%", i, ctx->flist[map], tanMinEnd - tanMaxBeg, tanMaxBeg, cLen - tanMinEnd, dustBegFract, tanBegFract, dustEndFract, tanEndFract);
// contig support for trimBegin
if (tanMaxBeg != 0)
{
int bmap = 0;
while (maxBegContigID < ctx->findx[bmap - 1])
bmap -= 1;
while (maxBegContigID >= ctx->findx[bmap])
bmap += 1;
fprintf(statsContigsNoTandem, ";trimBegSupport:ID=%d,name=%s", maxBegContigID, ctx->flist[bmap]);
}
// contig support for trimEnd
if (tanMinEnd != cLen)
{
int bmap = 0;
while (minEndContigID < ctx->findx[bmap - 1])
bmap -= 1;
while (minEndContigID >= ctx->findx[bmap])
bmap += 1;
fprintf(statsContigsNoTandem, ";trimEndSupport:ID=%d,name=%s", minEndContigID, ctx->flist[bmap]);
}
fprintf(statsContigsNoTandem, "\n");
}
}
// write out bionano agp gaps
if (ctx->BionanoAGPMatrix != NULL)
{
FILE *trimmedContigsBionano = NULL;
FILE *purgedContigsBionano = NULL;
FILE *statsContigsBionano = NULL;
sprintf(fout, "%s.BionanoBasedTrimmedContigs.fasta", ctx->fileOutPattern);
printf("create file: %s\n", fout);
if ((trimmedContigsBionano = (FILE*) fopen(fout, "w")) == NULL)
{
fprintf(stderr, "[ERROR] - could not open file %s\n", fout);
exit(1);
}
sprintf(fout, "%s.BionanoBasedPurgedContigs.fasta", ctx->fileOutPattern);
if ((purgedContigsBionano = (FILE*) fopen(fout, "w")) == NULL)
{
fprintf(stderr, "[ERROR] - could not open file %s\n", fout);
exit(1);
}
sprintf(fout, "%s.BionanoBasedContigs.stats", ctx->fileOutPattern);
if ((statsContigsBionano = (FILE*) fopen(fout, "w")) == NULL)
{
fprintf(stderr, "[ERROR] - could not open file %s\n", fout);
exit(1);
}
fprintf(statsContigsBionano, "#ContigID\tContigName\tnewContigLength\ttrimBegin\ttrimEnd\tcomments\n");
for (i = 0; i < nContigs; i++)
{
int maxBeg = 0;
int maxBegContigID = -1;
int cLen = DB_READ_LEN(ctx->db, i);
int minEnd = cLen;
int minEndContigID = -1;
for (j = 0; j < nContigs; j++)
{
int cutPos = ctx->LAStrimMatrix[i * nContigs + j];
int bionanoGap = ctx->BionanoAGPMatrix[i * nContigs + j];
if (bionanoGap != 0 && cutPos != 0)
{
if (abs(bionanoGap) <= ctx->minBionanoGapLen)
{
printf("found matching bionano gap and contig ovl for contigs: %d vs %d, OVL: %d, GAP: %d\n", i, j, cutPos, bionanoGap);
if (cutPos < 0 && abs(cutPos) > maxBeg)
{
maxBeg = abs(cutPos);
maxBegContigID = j;
}
if (cutPos > 0 && cutPos < minEnd)
{
minEnd = cutPos;
minEndContigID = j;
}
}
else
{
printf("found matching bionano gap and contig ovl for contigs: %d vs %d, OVL: %d, GAP: %d - BUT GAP IS TO LARGE\n", i, j, cutPos, bionanoGap);
}
}
else
{
if (bionanoGap != 0)
{
if (abs(bionanoGap) <= ctx->minBionanoGapLen)
{
printf("found bionano gap BUT NO contig ovl for contigs: %d vs %d, OVL: %d, GAP: %d\n", i, j, cutPos, bionanoGap);
if (abs(bionanoGap) < 3000)
printf("BIONANO GAP TO SMALL to find chains %d!\n", abs(bionanoGap));
if (i < j)
ctx->statsBionanoGapsMissed++;
}
}
else if (cutPos != 0)
{
printf("found NO bionano gap but contig ovl for contigs: %d vs %d, OVL: %d, GAP: %d\n", i, j, cutPos, bionanoGap);
}
}
}
float dustBegFract, dustEndFract, tanBegFract, tanEndFract;
dustBegFract = dustEndFract = tanBegFract = tanEndFract = 0.0;
if (maxBeg > 0 || minEnd != cLen) // contig i must be trimmed either at end or at begin, this corresponds with the Bionano AGP file
{
if (maxBeg > 0)
{
dustBegFract = getMaskedBases(ctx, ctx->trackDust, i, 0, maxBeg) * 100.0 / maxBeg;
tanBegFract = getMaskedBases(ctx, ctx->trackTan, i, 0, maxBeg) * 100.0 / maxBeg;
}
if (minEnd != cLen)
{
dustEndFract = getMaskedBases(ctx, ctx->trackDust, i, minEnd, cLen * 100.0 / cLen - minEnd);
tanEndFract = getMaskedBases(ctx, ctx->trackTan, i, minEnd, cLen * 100.0 / cLen - minEnd);
}
ctx->statsBionanoTrimmedContigs++;
ctx->statsBionanoTrimmedBases += abs(maxBeg) + (cLen - minEnd);
printf(" --> final trim Interval: [%d, %d] -> trimmed [%d, %d] dustFract(in %%) [%.2f, %.2f] tanFract(in %%) [%.2f,%.2f]\n", maxBeg, minEnd, maxBeg, cLen - minEnd, dustBegFract, dustEndFract, tanBegFract, tanEndFract);
}
int map = 0;
while (i < ctx->findx[map - 1])
map -= 1;
while (i >= ctx->findx[map])
map += 1;
Load_Read(ctx->db, i, read, 2);
// write out trimmed contigs
{
fprintf(trimmedContigsBionano, ">%s\n", ctx->flist[map]);
for (j = maxBeg; j + ctx->lineWidth < minEnd; j += ctx->lineWidth)
fprintf(trimmedContigsBionano, "%.*s\n", ctx->lineWidth, read + j);
if (j < minEnd)
fprintf(trimmedContigsBionano, "%.*s\n", minEnd - j, read + j);
// write out purged sequence at begin of contig
if (maxBeg > 0)
{
fprintf(purgedContigsBionano, ">%s purged=%d,%d purgedLen=%d\n", ctx->flist[map], 0, maxBeg, maxBeg);
for (j = 0; j + ctx->lineWidth < maxBeg; j += ctx->lineWidth)
fprintf(purgedContigsBionano, "%.*s\n", ctx->lineWidth, read + j);
if (j < maxBeg)
fprintf(purgedContigsBionano, "%.*s\n", maxBeg - j, read + j);
}
// write out purged sequence at end of contig
if (minEnd < cLen)
{
fprintf(purgedContigsBionano, ">%s purged=%d,%d purgedLen=%d\n", ctx->flist[map], minEnd, cLen, cLen - minEnd);
for (j = minEnd; j + ctx->lineWidth < cLen; j += ctx->lineWidth)
fprintf(purgedContigsBionano, "%.*s\n", ctx->lineWidth, read + j);
if (j < cLen)
fprintf(purgedContigsBionano, "%.*s\n", cLen - j, read + j);
}
fprintf(statsContigsBionano, "%d\t%s\t%d\t%d\t%d\ttrimBeg:LC=%.2f%%,TAN=%.2f%%;trimEnd=LC=%.2f%%,TAN=%.2f%%", i, ctx->flist[map], minEnd - maxBeg, maxBeg, cLen - minEnd, dustBegFract, tanBegFract, dustEndFract, tanEndFract);
// contig support for trimBegin
if (maxBeg != 0)
{
int bmap = 0;
while (maxBegContigID < ctx->findx[bmap - 1])
bmap -= 1;
while (maxBegContigID >= ctx->findx[bmap])
bmap += 1;
fprintf(statsContigsBionano, ";trimBegSupport:ID=%d,name=%s", maxBegContigID, ctx->flist[bmap]);
}
// contig support for trimEnd
if (minEnd != cLen)
{
int bmap = 0;
while (minEndContigID < ctx->findx[bmap - 1])
bmap -= 1;
while (minEndContigID >= ctx->findx[bmap])
bmap += 1;
fprintf(statsContigsBionano, ";trimEndSupport:ID=%d,name=%s", minEndContigID, ctx->flist[bmap]);
}
fprintf(statsContigsBionano, "\n");
}
}
fclose(trimmedContigsBionano);
fclose(purgedContigsBionano);
fclose(statsContigsBionano);
}
fclose(trimmedContigsAll);
fclose(purgedContigsAll);
fclose(statsContigsAll);
fclose(trimmedContigsNoTandem);
fclose(purgedContigsNoTandem);
fclose(statsContigsNoTandem);
free(read - 1);
free(fout);
}*/
void trim_contigs(TrimContext *ctx)
{
assert(ctx != NULL);
int i, j, k, l;
// split bionano gaps only
if (ctx->purgeOpt == 1)
{
// do nothing, but cut at the given Bionano split coordinates
}
else if (ctx->purgeOpt == 1)
{
j = k = 0;
while (j < ctx->numTrimEvidence)
{
while (k < ctx->numTrimEvidence - 1 && ctx->trimEvid[j].contigA == ctx->trimEvid[k + 1].contigA)
{
k++;
}
int n = k - j + 1;
int aLen = DB_READ_LEN(ctx->db, ctx->trimEvid[j].contigA);
int maxStart = 1;
int minEnd = aLen;
int tmp = 0;
for (i = 0; i < n; i++)
{
TrimEvidence *te = ctx->trimEvid + j + i;
for (l = 0; l < te->nBioNanoGaps; l++)
{
if (te->gaps[l].bionanoGapSize < ctx->minBionanoGapLen)
{
// todo: remember min and max cut positions
//trimmedContigs++;
printBionanpGap(ctx, te->contigA, te->contigB, te->gaps + l);
if (te->gaps[l].aEnd == 1)
{
tmp = (1 + abs(te->gaps[l].bionanoGapSize) / 2 + ctx->trimOffset);
if (tmp > maxStart)
{
maxStart = tmp;
}
}
else if (te->gaps[l].aEnd == aLen)
{
tmp = aLen - (1 + abs(te->gaps[l].bionanoGapSize) / 2 + ctx->trimOffset);
if (tmp < minEnd)
{
minEnd = tmp;
}
}
}
}
}
if (maxStart > 1 || minEnd < aLen)
{
printf("CUT POSITIONS (%d - %d, %d): %d, %d\n", ctx->trimEvid[j].contigA, 0, aLen, maxStart, minEnd);
ctx->trimCoord[ctx->trimEvid[j].contigA].coord[0] = maxStart;
ctx->trimCoord[ctx->trimEvid[j].contigA].coord[1] = minEnd;
}
k++;
j = k;
}
printf("[INFO] num trim evidence: %d: \n", ctx->numTrimEvidence);
}
else if (ctx->purgeOpt == 2)
{
j = k = 0;
while (j < ctx->numTrimEvidence)
{
while (k < ctx->numTrimEvidence - 1 && ctx->trimEvid[j].contigA == ctx->trimEvid[k + 1].contigA)
{
k++;
}
int n = k - j + 1;
int aLen = DB_READ_LEN(ctx->db, ctx->trimEvid[j].contigA);
int newStart = -1;
int newEnd = -aLen;
int tmp = 0;
// ensure that buffer for cut positions is always big enough
if (ctx->trimEvid[j].nBioNanoGaps > 1)
{
int tmp = (1 + ctx->trimEvid[j].nBioNanoGaps);
ctx->trimCoord[ctx->trimEvid[j].contigA].coord = (int*) realloc(ctx->trimCoord[ctx->trimEvid[j].contigA].coord, sizeof(int) * 3 * tmp);
for (j = 1; j < tmp; j++)
{
ctx->trimCoord[ctx->trimEvid[j].contigA].coord[3 * j] = 1;
ctx->trimCoord[ctx->trimEvid[j].contigA].coord[3 * j + 1] = aLen;
ctx->trimCoord[ctx->trimEvid[j].contigA].coord[3 * j + 2] = 0;
}
ctx->trimCoord[ctx->trimEvid[j].contigA].maxCoordPairs = tmp;
}
for (i = 0; i < n; i++)
{
TrimEvidence *te = ctx->trimEvid + j + i;
for (l = 0; l < te->nBioNanoGaps; l++)
{
// normal gap, i.e. bionano did not cut the contigs before scaffolding them
if (((te->gaps[l].aEnd == 1) || (te->gaps[l].aEnd == aLen)) && ((te->gaps[l].bBeg == 1) || (te->gaps[l].aBeg == aLen)))
{
// check for negative gap
if (te->gaps[l].bionanoGapSize < ctx->minBionanoGapLen)
{
if (te->gaps[l].aEnd == 1)
{
tmp = (1 + abs(te->gaps[l].bionanoGapSize) / 2 + ctx->trimOffset);
// newStart
int m;
for (m = 0; m < ctx->trimCoord[ctx->trimEvid[j].contigA].maxCoordPairs; m++)
{
if (intersect(abs(ctx->trimCoord[ctx->trimEvid[j].contigA].coord[m * 2]), abs(ctx->trimCoord[ctx->trimEvid[j].contigA].coord[m * 2 + 1]), te->gaps[l].aEnd, te->gaps[l].aBeg))
{
break;
}
}
assert(m < ctx->trimCoord[ctx->trimEvid[j].contigA].maxCoordPairs);
ctx->trimCoord[ctx->trimEvid[j].contigA].coord[m * 2] = tmp;
ctx->trimCoord[ctx->trimEvid[j].contigA].coord[m * 2 + 1] = te->gaps[l].aBeg;
}
else if (te->gaps[l].aEnd == aLen)
{
tmp = aLen - (1 + abs(te->gaps[l].bionanoGapSize) / 2 + ctx->trimOffset);
// newEnd
int m;
for (m = 0; m < ctx->trimCoord[ctx->trimEvid[j].contigA].maxCoordPairs; m++)
{
if (intersect(abs(ctx->trimCoord[ctx->trimEvid[j].contigA].coord[m * 2]), abs(ctx->trimCoord[ctx->trimEvid[j].contigA].coord[m * 2 + 1]), te->gaps[l].aBeg, te->gaps[l].aEnd))
{
break;
}
}
assert(m < ctx->trimCoord[ctx->trimEvid[j].contigA].maxCoordPairs);
ctx->trimCoord[ctx->trimEvid[j].contigA].coord[m * 2] = te->gaps[l].aBeg;
ctx->trimCoord[ctx->trimEvid[j].contigA].coord[m * 2 + 1] = tmp;
}
else // should not occur
{
assert(0);
}
}
}
else // at least one contig at current gap was split before the scaffolding
{
}
}
}
k++;
j = k;
}
printf("[INFO] num trim evidence: %d: \n", ctx->numTrimEvidence);
}
else if (ctx->purgeOpt == 3)
{
}
else if (ctx->purgeOpt == 4)
{
}
else if (ctx->purgeOpt == 5)
{
}
else if (ctx->purgeOpt == 6)
{
}
else
{
/// UNKNOWN OPTION
}
// CUT CONTIGS!!!
// open file handler
FILE *trimmedContigs = NULL;
FILE *removedContigParts = NULL;
FILE *statsContigs = NULL;
char *fout = malloc(strlen(ctx->fileOutPattern) + 50);
assert(fout != NULL);
sprintf(fout, "%s.trimmedContigs.fasta", ctx->fileOutPattern);
printf("create file: %s\n", fout);
if ((trimmedContigs = (FILE*) fopen(fout, "w")) == NULL)
{
fprintf(stderr, "[ERROR] - could not open file %s\n", fout);
exit(1);
}
sprintf(fout, "%s.removedContigParts.fasta", ctx->fileOutPattern);
if ((removedContigParts = (FILE*) fopen(fout, "w")) == NULL)
{
fprintf(stderr, "[ERROR] - could not open file %s\n", fout);
exit(1);
}
sprintf(fout, "%s.trim.stats", ctx->fileOutPattern);
if ((statsContigs = (FILE*) fopen(fout, "w")) == NULL)
{
fprintf(stderr, "[ERROR] - could not open file %s\n", fout);
exit(1);
}
free(fout);
fprintf(statsContigs, "#ContigID\tContigName\tnewContigLength\ttrimBegin\ttrimEnd\tcomments\n");
char *read = New_Read_Buffer(ctx->db);
for (i = 0; i < DB_NREADS(ctx->db); i++)
{
// debug report trim position
Load_Read(ctx->db, i, read, 2);
TrimCoordinates *tc = ctx->trimCoord + i;
int aLen = DB_READ_LEN(ctx->db, i);
int amap = 0;
while (i < ctx->findx[amap - 1])
amap -= 1;
while (i >= ctx->findx[amap])
amap += 1;
// write out removed part a the beginning !!!
if (tc->coord[0] > 1)
{
ctx->statsRemovedContigPartBases += tc->coord[0];
ctx->statsRemovedContigParts++;
fprintf(removedContigParts, ">%s part=%d,%d\n", ctx->flist[amap], 1, tc->coord[0]);
for (k = 0; k + ctx->lineWidth < tc->coord[0]; k += ctx->lineWidth)
fprintf(removedContigParts, "%.*s\n", ctx->lineWidth, read + k);
if (k < tc->coord[0])
fprintf(removedContigParts, "%.*s\n", tc->coord[0] - k, read + k);
}
for (j = 0; j < tc->numCoordPairs; j++)
{
int index = j * 3;
ctx->statsTrimmedBases += tc->coord[index + 1] - tc->coord[index];
ctx->statsTrimmedContigs++;
fprintf(trimmedContigs, ">%s part=%d,%d\n", ctx->flist[amap], tc->coord[index], tc->coord[index + 1]);
for (k = tc->coord[index]; k + ctx->lineWidth < tc->coord[index + 1]; k += ctx->lineWidth)
fprintf(trimmedContigs, "%.*s\n", ctx->lineWidth, read + k);
if (k < tc->coord[index + 1])
fprintf(trimmedContigs, "%.*s\n", tc->coord[index + 1] - k, read + k);
if (j + 1 < tc->numCoordPairs)
{
assert(tc->coord[index + 3] >= tc->coord[index + 1]);
ctx->statsRemovedContigPartBases += tc->coord[index + 3] - tc->coord[index + 1];
ctx->statsRemovedContigParts++;
fprintf(removedContigParts, ">%s part=%d,%d\n", ctx->flist[amap], tc->coord[index + 1], tc->coord[index + 3]);
for (k = tc->coord[index + 1]; k + ctx->lineWidth < tc->coord[index + 3]; k += ctx->lineWidth)
fprintf(removedContigParts, "%.*s\n", ctx->lineWidth, read + k);
if (k < tc->coord[index + 3])
fprintf(removedContigParts, "%.*s\n", tc->coord[index + 3] - k, read + k);
}
}
// write out removed part at the end!!!
if (tc->coord[tc->numCoordPairs * 3 - 2] < aLen)
{
ctx->statsRemovedContigPartBases += aLen - tc->coord[tc->numCoordPairs * 3 - 2];
ctx->statsRemovedContigParts++;
fprintf(removedContigParts, ">%s part=%d,%d\n", ctx->flist[amap], tc->coord[tc->numCoordPairs * 3 - 2], aLen);
for (k = tc->coord[tc->numCoordPairs * 3 - 2]; k + ctx->lineWidth < aLen; k += ctx->lineWidth)
fprintf(removedContigParts, "%.*s\n", ctx->lineWidth, read + k);
if (k < aLen)
fprintf(removedContigParts, "%.*s\n", aLen - k, read + k);
}
}
fclose(trimmedContigs);
fclose(removedContigParts);
fclose(statsContigs);
free(read - 1);
}
void usage()
{
fprintf(stderr, "[-v] [-GTLOFwt <int>] [-ago <file>] [-dt <track>] <db> <contigs_out_prefix>\n");
fprintf(stderr, "options: -v verbose\n");
fprintf(stderr, " -d <trc> low complexity track (e.g. dust)\n");
fprintf(stderr, " -t <trc> tandem repeat track (e,f, tan)\n");
fprintf(stderr, " -a <file> bionano agp file");
fprintf(stderr, " If a bionano-agp file is given, then only gaps up the minimum gaps size of (default: %d) and a valid overlap chain are trimmed\n", MIN_BIONANO_GAP_SIZE);
fprintf(stderr, " -g <file> bionano gap file");
fprintf(stderr, " -o <file> overlap file that was filtered with LAfilterChain");
fprintf(stderr, " -G <int> min Bionano gap size (default: %d)\n", MIN_BIONANO_GAP_SIZE);
fprintf(stderr, " -T <int> maximum trim length (default: -1)\n");
fprintf(stderr, " -L <int> maximum tandem repeat overlap fraction (in %%) (default: %d, valid range: [0,100])\n", MAX_TANDEMTRIM_PERC);
fprintf(stderr, " -O <int> trim offset in bases (default %d), i.e. in best case (if we have single overlap between 2 contigs) a gap of size 2xtrim_offset is created )\n", TRIM_OFFSET);
fprintf(stderr, " in case a valid alignment chain consisting of multiple alignments is present (representing heterozygous variations). The first last and the last alignment are used, (- trimOffset and + trimOffset, accordingly) \n");
fprintf(stderr, " (- trimOffset and + trimOffset, accordingly) creates a larger gap size, but heopefully removes the heterozygous difference.\n");
fprintf(stderr, " -F <int> number of fuzzy bases for chaining. For sanity check only, must correspond to -f of LAfilterChain. (default: %d)\n", FUZZY_BASES);
fprintf(stderr, " -w <int> specify number of characters per fasta line (default: %d)\n", FASTA_LINEWIDTH);
fprintf(stderr, " -p <int> trim Options, as follows:\n");
fprintf(stderr, " 0: split contigs at bionano split coordinates (requires bionano AGP file)\n");
fprintf(stderr, " 1: only trim negative bionano gaps (requires bionano AGP and GAP files)\n");
fprintf(stderr, " 2: -t 0 AND split and trim contigs if bionano AGP file reports a contig break (requires bionano AGP and GAP files)\n");
fprintf(stderr, " 3: trimming based on LAS chains only (requires a chain filtered overlap file)\n");
fprintf(stderr, " 4: -t 2 BUT tandem induced contig overlap are not trimmed (requires chain filtered overlap file and tandem repeat track) - \n");
fprintf(stderr, " 5: intersection of -t 0 and -t 2, i.e. LAS chains based trimming only if negative Bionano gaps support them + small negative Bionano gaps that are below the minimum daligner alignment length cutoff\n");
fprintf(stderr, " 6: -t 4 AND LAS chain based trimming of small contigs that are below the bionano minimum length threshold (<150K)\n");
}
int main(int argc, char *argv[])
{
HITS_DB db;
TrimContext tctx;
PassContext *pctx = NULL;
FILE *fileOvlIn = NULL;
bzero(&tctx, sizeof(TrimContext));
tctx.db = &db;
// args
char *pcTrackDust = NULL;
char *pcTrackTan = NULL;
char *pathInBionanoAGP = NULL;
char *pathInBionanoGAP = NULL;
char *pcPathReadsIn = NULL;
char *pcPathOverlapsIn = NULL;
int c, tmp;
tctx.minBionanoGapLen = MIN_BIONANO_GAP_SIZE;
tctx.maxTrimLength = -1;
tctx.maxLowCompTrimPerc = MAX_TANDEMTRIM_PERC;
tctx.trimOffset = TRIM_OFFSET;
tctx.maxFuzzyBases = FUZZY_BASES;
tctx.lineWidth = FASTA_LINEWIDTH;
opterr = 0;
while ((c = getopt(argc, argv, "vd:t:a:g:o:G:T:L:O:F:w:p:")) != -1)
{
switch (c)
{
case 'v':
tctx.verbose++;
break;
case 'd':
pcTrackDust = optarg;
break;
case 't':
pcTrackTan = optarg;
break;
case 'a':
pathInBionanoAGP = optarg;
break;
case 'g':
pathInBionanoGAP = optarg;
break;
case 'o':
pcPathOverlapsIn = optarg;
break;
case 'G':
tctx.minBionanoGapLen = atoi(optarg);
break;
case 'T':
tctx.maxTrimLength = atoi(optarg);
break;
case 'L':
tmp = atoi(optarg);
if (tmp < 0 || tmp > 100)
{
fprintf(stderr, "[ERROR] Invalid range for tandem repeat fraction %d. Must be in [0,100]\n", tmp);
exit(1);
}
tctx.maxLowCompTrimPerc = tmp;
break;
case 'O':
tctx.trimOffset = atoi(optarg);
break;
case 'F':
tctx.maxFuzzyBases = atoi(optarg);
break;
case 'w':
tctx.lineWidth = atoi(optarg);
break;
case 'p':
tctx.purgeOpt = atoi(optarg);
break;
default:
fprintf(stderr, "unknown option %c\n", optopt);
usage();
exit(1);
}
}
if (argc - optind != 2)
{
usage();
exit(1);
}
pcPathReadsIn = argv[optind++];
tctx.fileOutPattern = argv[optind++];
if (pcPathOverlapsIn)
{
if ((fileOvlIn = fopen(pcPathOverlapsIn, "r")) == NULL)
{
fprintf(stderr, "[ERROR] - could not open %s\n", pcPathOverlapsIn);
exit(1);
}
}
if (Open_DB(pcPathReadsIn, &db))
{
fprintf(stderr, "[ERROR] - could not open %s\n", pcPathReadsIn);
exit(1);
}
if (pcTrackDust)
{
tctx.trackDust = track_load(&db, pcTrackDust);
if (!tctx.trackDust)
{
fprintf(stderr, "[ERROR] - could not load track %s\n", pcTrackDust);
exit(1);
}
}
if (pcTrackTan)
{
tctx.trackTan = track_load(&db, pcTrackTan);
if (!tctx.trackTan)
{
fprintf(stderr, "[ERROR] - could not load track %s\n", pcTrackTan);
exit(1);
}
}
// check if purge options are valid
if (tctx.purgeOpt == 0)
{
if (pathInBionanoAGP == NULL)
{
fprintf(stderr, "[ERROR] - trim option -p 0: requires a bionano.agp file\n");
exit(1);
}
}
else if (tctx.purgeOpt == 1 || tctx.purgeOpt == 2)
{
if (pathInBionanoAGP == NULL || pathInBionanoGAP == NULL)
{
fprintf(stderr, "[ERROR] - trim option -p 1 and -p 2: requires a bionano.agp and bionano.gap file\n");
exit(1);
}
}
else if (tctx.purgeOpt == 3 || tctx.purgeOpt == 4)
{
if (fileOvlIn == NULL)
{
fprintf(stderr, "[ERROR] - trim option -p 3 and -p 4: requires a chain filtered LAS file\n");
exit(1);
}
if (tctx.purgeOpt == 4 && tctx.trackTan == NULL)
{
fprintf(stderr, "[ERROR] - trim option -p 4: requires a chain filtered LAS file and a tandem repeat file!\n");
exit(1);
}
}
else if (tctx.purgeOpt == 5 || tctx.purgeOpt == 6)
{
if (fileOvlIn == NULL || pathInBionanoAGP == NULL || pathInBionanoGAP == NULL)
{
fprintf(stderr, "[ERROR] - trim option -p 5 and -p 6: requires a chain filtered LAS file and a bionano.agp and a bionano.gap file\n");
exit(1);
}
}
else
{
fprintf(stderr, "[ERROR] - unknown trim option -p %d\n", tctx.purgeOpt);
usage();
exit(1);
}
if (fileOvlIn)
{
// passes
pctx = pass_init(fileOvlIn, NULL);
pctx->split_b = 1;
pctx->load_trace = 1;
pctx->unpack_trace = 1;
pctx->data = &tctx;
pctx->write_overlaps = 0;
pctx->purge_discarded = 0;
}
trim_pre(pctx, &tctx);
getDBFastaHeader(&tctx, pcPathReadsIn);
if (pathInBionanoAGP)
{
parseBionanoAGPfile(&tctx, pathInBionanoAGP);
printf("------ OUTPUT CUT COORDINATES\n");
int i,j;
for (i=0; i<DB_NREADS(&db);i++)
{
printf("CONTIG %4d initial length [%10d]", i, DB_READ_LEN(&db,i));
for(j=0;j<tctx.trimCoord[i].numCoordPairs; j++)
printf(" [%d, %d, %d]", tctx.trimCoord[i].coord[j*3], tctx.trimCoord[i].coord[j*3+1], tctx.trimCoord[i].coord[j*3+2]);
printf("\n");
printf("sort coordinates\n");
qsort(tctx.trimCoord[i].coord, tctx.trimCoord[i].numCoordPairs, sizeof(int)*3, TrimCoordinates_cmp);
printf("CONTIG %4d initial length [%10d]", i, DB_READ_LEN(&db,i));
for(j=0;j<tctx.trimCoord[i].numCoordPairs; j++)
printf(" [%d, %d, %d]", tctx.trimCoord[i].coord[j*3], tctx.trimCoord[i].coord[j*3+1], tctx.trimCoord[i].coord[j*3+2]);
printf("\n");
printf("sort coordinates\n");
}
}
if (pathInBionanoGAP)
{
parseBionanoGAPfile(&tctx, pathInBionanoGAP);
}
if (fileOvlIn)
{
pass(pctx, trim_handler);
}
trim_contigs(&tctx);
trim_post(&tctx);
if (fileOvlIn)
{
pass_free(pctx);
fclose(fileOvlIn);
}
Close_DB(&db);
int i;
for (i = 0; i < tctx.nfiles; i++)
{
free(tctx.flist[i]);
free(tctx.hlist[i]);
}
for (i = 0; i < tctx.numTrimEvidence; i++)
{
if (tctx.trimEvid->nLASchains)
free(tctx.trimEvid[i].chains);
if (tctx.trimEvid->nBioNanoGaps)
free(tctx.trimEvid[i].gaps);
}
free(tctx.trimEvid);
free(tctx.flist);
free(tctx.hlist);
free(tctx.findx - 1);
for (i = 0; i < DB_NREADS(tctx.db); i++)
{
free(tctx.trimCoord[i].coord);
}
free(tctx.trimCoord);
return 0;
}
|
MartinPippel/DAmar
|
db/DBstats.c
|
<reponame>MartinPippel/DAmar
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "DB.h"
#include "lib/utils.h"
#define DEF_ARG_B 1000
extern char* optarg;
extern int optind, opterr, optopt;
static void usage()
{
fprintf( stderr, "usage: [-nr] [-bg <int>] <name:db|dam>\n" );
fprintf( stderr, "options: -b ... bucket size of histogram length (%d)\n", DEF_ARG_B );
fprintf( stderr, " -g ... genome size\n" );
fprintf( stderr, " -r ... raw output\n" );
}
int main( int argc, char* argv[] )
{
HITS_DB _db, *db = &_db;
int dam;
int nbin, *hist;
int64* bsum;
int BIN = DEF_ARG_B;
int64 GSIZE = -1;
int raw = 0;
// parse arguments
int c;
opterr = 0;
while ( ( c = getopt( argc, argv, "rb:g:" ) ) != -1 )
{
switch ( c )
{
case 'r':
raw = 1;
break;
case 'g':
GSIZE = bp_parse( optarg );
if ( GSIZE <= 0 )
{
fprintf( stderr, "Invalid genome size of %lld\n", GSIZE );
exit( 1 );
}
break;
case 'b':
BIN = atoi( optarg );
if ( BIN <= 0 )
{
fprintf( stderr, "Invalid histogram bucket size of %d\n", BIN );
exit( 1 );
}
break;
default:
fprintf( stderr, "Unsupported argument: %s\n", argv[ optind ] );
usage();
exit( 1 );
}
}
if ( optind + 1 > argc )
{
fprintf( stderr, "[ERROR]: Database is required\n" );
usage();
exit( 1 );
}
int i, status;
// Open .db or .dam
status = Open_DB( argv[ optind ], db );
if ( status < 0 )
{
exit( 1 );
}
dam = status;
if ( raw && dam )
{
fprintf(stderr, "raw output currently not supported for .dam\n");
raw = 0;
}
int64 totlen;
int nreads, maxlen;
int64 ave, dev;
HITS_READ* reads;
int64* cum;
int64* btot;
nreads = db->nreads;
totlen = db->totlen;
maxlen = db->maxlen;
reads = db->reads;
nbin = maxlen / BIN + 1;
hist = (int*)Malloc( sizeof( int ) * nbin, "Allocating histograms" );
bsum = (int64*)Malloc( sizeof( int64 ) * nbin, "Allocating histograms" );
btot = malloc( sizeof( int64 ) * nbin );
cum = malloc( sizeof( int64 ) * nbin );
if ( !hist || !bsum || !btot || !cum )
{
exit( 1 );
}
bzero( hist, sizeof( int ) * nbin );
bzero( bsum, sizeof( uint64 ) * nbin );
bzero( cum, sizeof( uint64 ) * nbin );
bzero( btot, sizeof( uint64 ) * nbin );
for ( i = 0; i < nreads; i++ )
{
int rlen = reads[ i ].rlen;
hist[ rlen / BIN ] += 1;
bsum[ rlen / BIN ] += rlen;
}
nbin = ( maxlen - 1 ) / BIN + 1;
ave = totlen / nreads;
dev = 0;
for ( i = 0; i < nreads; i++ )
{
int rlen = reads[ i ].rlen;
dev += ( rlen - ave ) * ( rlen - ave );
}
dev = (int64)sqrt( ( 1. * dev ) / nreads );
int64 _cum = 0;
int64 _btot = 0;
for ( i = nbin - 1; i >= 0; i-- )
{
_cum += hist[ i ];
_btot += bsum[ i ];
cum[ i ] = _cum;
btot[ i ] = _btot;
}
if ( dam )
{
printf( "%d contigs %lld average contig length\n", nreads, ave );
}
else if ( raw )
{
printf( "%d %lld %lld %lld\n", nreads, totlen, ave, dev );
}
else
{
printf( "%d reads %s base pairs\n", nreads, bp_format(totlen, 1) );
printf( "%lld average read length with %lld standard deviation\n", ave, dev );
}
if (raw)
{
printf( "A %.3f C %.3f G %.3f T %.3f\n", db->freq[ 0 ], db->freq[ 1 ], db->freq[ 2 ], db->freq[ 3 ] );
}
else
{
printf( "Base composition: %.3f(A) %.3f(C) %.3f(G) %.3f(T)\n", db->freq[ 0 ], db->freq[ 1 ], db->freq[ 2 ], db->freq[ 3 ] );
printf( "\nDistribution of Read Lengths (Bin size = %d)\n\n", BIN );
printf( "%11s %11s %7s %7s %9s", "Bin", "Count", "% Reads", "% Bases", "Average" );
if ( GSIZE > 0 )
{
printf( " %11s", "Coverage" );
}
printf( "\n" );
}
int skip = dam ? 0 : -1;
for ( i = nbin - 1; i >= 0; i-- )
{
if ( hist[ i ] != skip && ( hist[ i ] > 0 ) )
{
if (raw)
{
printf( "%d %d %.1f %.1f %lld",
( i * BIN ),
hist[ i ],
( 100. * cum[ i ] ) / nreads,
( 100. * btot[ i ] ) / totlen,
btot[ i ] / cum[ i ] );
if ( GSIZE > 0 )
{
printf( " %.2f", btot[ i ] * 1.0 / GSIZE );
}
printf( "\n" );
}
else
{
printf( "%11d %11d %7.1f %7.1f %9lld",
( i * BIN ),
hist[ i ],
( 100. * cum[ i ] ) / nreads,
( 100. * btot[ i ] ) / totlen,
btot[ i ] / cum[ i ] );
if ( GSIZE > 0 )
{
printf( " %11.2f", btot[ i ] * 1.0 / GSIZE );
}
printf( "\n" );
}
}
if ( cum[ i ] == nreads )
{
break;
}
}
free( hist );
free( bsum );
free(btot);
free(cum);
Close_DB( db );
exit( 0 );
}
|
MartinPippel/DAmar
|
dalign/HPCdaligner.c
|
<filename>dalign/HPCdaligner.c
/************************************************************************************\
* *
* Copyright (c) 2014, Dr. <NAME> (EWM). 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. *
* *
* - The name of EWM may not be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY EWM "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 EWM 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. *
* *
* For any issues regarding this software and its use, contact EWM at: *
* *
* <NAME>r. *
* Bautzner Str. 122e *
* 01099 Dresden *
* GERMANY *
* Email: <EMAIL> *
* *
\************************************************************************************/
/*********************************************************************************************\
*
* Produce a script to compute overlaps for all block pairs of a DB, and then sort and merge
* them into as many .las files as their are blocks.
*x
* Author: <NAME>
* Date : June 1, 2014
*
*********************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <getopt.h>
#include "db/DB.h"
#include "filter.h"
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
static char *Usage =
{ " [-vbAIKSXT] [-k<int(14)>] [-w<int(6)>] [-h<int(35)>] [-t<int>] [-H<int>]\n"
" [-M<int>] [-e<double(.70)] [-l<int(1000)>] [-r<int>] [-s<int(100)>]\n"
" [--dal<int(4)>] [--dalDiag<int(1)>] [--mrg<int(8)>] [-D host[:port]]\n"
" [-o fileSuffix] [-j<int(4)>] [-mtrack]+ <path:db> [<block:int>[-<range:int>]" };
static void printUsage(char* prog, FILE *out)
{
fprintf(out, "\nUsage:\t%s\t%s\n\n", prog, Usage);
fprintf(out, " -h prints this usage info\n");
fprintf(out, " -o ARG specify a file suffix, if set the daligner plan is written to planDalignARG and the merge plan is written\n"
" to planMergeARG (default: not set, i.e. everything goes to stdout)\n");
fprintf(out, " -v enable verbose mode for daligner and LAmerge\n");
fprintf(out, " path database\n");
fprintf(out, " bID[-bID] specify a block or a range of blocks\n");
fprintf(out, " daligner options: \n");
fprintf(out, " -j number of daligner threads, (Must be a power of 2, default=4).\n");
fprintf(out, " -A asymmetric, for block X and Y the symmetric alignments for Y vs X are suppressed.\n");
fprintf(out, " -I identity, overlaps of the same read will found and reported\n");
fprintf(out, " -b bias genome (AT content is greater then 70%% or lower then 30%%)\n");
fprintf(out, " -k ARG kmer length (default: 14)\n");
fprintf(out, " -w ARG diagonal band width (default: 6)\n");
fprintf(out, " -h ARG number of kmer hits (default: 35)\n");
fprintf(out, " -t ARG suppresses the use of any k-mer that occurs more than t times in either the subject or target block (default: not set)\n");
fprintf(out, " -H ARG report only overlaps where the a-read is over N base-pairs long (default: 0)\n");
fprintf(out, " -M ARG memory usage limit in Gb (default: unlimited)\n");
fprintf(out, " -e ARG average correlation rate (default: 0.5). Must be in [.5,1.)\n");
fprintf(out, " -l ARG minimum length for local alignments (default: 1000)\n");
fprintf(out, " -r ARG run identifier (default: 1). That means all overlap files of Block X a written to a subdirectory: dRUN-IDENTIFIER_X\n");
fprintf(out, " -s ARG record trace point of the alignment, every -s ARG base pairs (default: 100)\n");
fprintf(out, " --dal ARG number of block comparisons per call to daligner (default: 4)\n");
fprintf(out, " --dalDiag ARG number of block comparisons per call to daligner for jobs including the diagonal element (default: 1 if ddust is set, otherwise 4)\n");
fprintf(out, " -D host:port specify host and port where the dynamic dust server is running (default: not set)\n");
fprintf(out, " -m specify an interval track that is to be softmasked\n");
fprintf(out, " -X change daligner job order into: block.1 vs block.1 .. block.n, block.2 vs block.2 .. block.n, ... \n");
fprintf(out, " -T do not report trace points in overlaps\n");
fprintf(out, " LAmerge options: \n");
fprintf(out, " -K keep intermediate merge results (default: 0)\n");
fprintf(out, " -S sort inital overlaps before merging phase (default: 0)\n");
fprintf(out, " --mrg ARG gives the maximum number of files that will be merged in a single LAmerge command (default: 8)\n");
}
typedef struct
{
int DAL_JOBS, DAL_DIAG_JOBS;
int VERBOSE, BIAS;
int WINT, TINT, HGAP, HINT, KINT, SINT, LINT;
double EREL, MREL;
int RUN_ID, MEM;
int ASYMMETRY, IDENTITY, IGNORE;
int NTHREADS;
int SORT;
int CONSECUTIVE;
int NO_TRACE_POINTS;
int fblock, lblock;
char *db; // full name dir + name + .db
char *dbDir;
char *dbName;
int dbBlocks;
char* host;
int port;
FILE *dalignOut;
FILE *mergeOut;
// track info
int MMAX, MTOP;
char **MASK;
// parameter for LAmerge
int KEEP;
int MERGE_JOBS;
} HPC_OPT;
HPC_OPT* parseOptions(int argc, char* argv[])
{
HPC_OPT *hopt = (HPC_OPT*) malloc(sizeof(HPC_OPT));
// set default values
hopt->VERBOSE = 0;
hopt->BIAS = 0;
hopt->KEEP = 0;
hopt->NTHREADS = 4;
hopt->DAL_JOBS = 4;
hopt->DAL_DIAG_JOBS = 0;
hopt->MERGE_JOBS = 8;
hopt->KINT = 14;
hopt->WINT = 6;
hopt->HINT = 35;
hopt->TINT = 0;
hopt->HGAP = 0;
hopt->EREL = 0.;
hopt->MREL = 0.;
hopt->SINT = 100;
hopt->LINT = 1000;
hopt->RUN_ID = 1;
hopt->MEM = 0;
hopt->ASYMMETRY = 0;
hopt->IDENTITY = 0;
hopt->IGNORE = 0;
hopt->SORT = 0;
hopt->CONSECUTIVE = 0;
hopt->NO_TRACE_POINTS = 0;
hopt->MTOP = 0;
hopt->MMAX = 10;
hopt->MASK = (char **) Malloc(hopt->MMAX * sizeof(char *), "Allocating mask track array");
if (hopt->MASK == NULL)
exit(1);
hopt->host = NULL;
hopt->port = -1;
hopt->dbBlocks = 0;
hopt->dalignOut = stdout;
hopt->mergeOut = stdout;
int c;
while (1)
{
static struct option long_options[] =
{
{ "help", no_argument, 0, 'h' },
{ "verbose", no_argument, 0, 'v' },
{ "bias", no_argument, 0, 'b' },
{ "keep", no_argument, 0, 'K' },
{ "check", no_argument, 0, 'C' },
{ "asymm", no_argument, 0, 'A' },
{ "identity", no_argument, 0, 'I' },
{ "ignore", no_argument, 0, 'i' },
{ "kmer", required_argument, 0, 'k' },
{ "bwidth", required_argument, 0, 'w' },
{ "hits", required_argument, 0, 'h' },
{ "htimes", required_argument, 0, 't' },
{ "rlen", required_argument, 0, 'H' },
{ "mem", required_argument, 0, 'M' },
{ "cor", required_argument, 0, 'e' },
{ "alen", required_argument, 0, 'l' },
{ "rid", required_argument, 0, 'r' },
{ "trace", required_argument, 0, 's' },
{ "dal", required_argument, 0, 'n' },
{ "dalDiag", required_argument, 0, 'N' },
{ "mrg", required_argument, 0, 'c' },
{ "dServer", required_argument, 0, 'D' },
{ "out", required_argument, 0, 'o' },
{ "nthreads", required_argument, 0, 'j' },
{ "track", required_argument, 0, 'm' },
{ "sort", required_argument, 0, 'S' },
{ "jobOrder", no_argument, 0, 'X' },
{ "noTrace", no_argument, 0, 'T' }};
/* getopt_long stores the option index here. */
int option_index = 0;
c = getopt_long(argc, argv, "?vbKXTSAIk:w:h:t:H:M:e:l:r:s:n:N:c:D:o:m:j:", long_options, &option_index);
/* Detect the end of the options. */
if (c == -1)
break;
switch (c)
{
case 0:
/* If this option set a flag, do nothing else now. */
if (long_options[option_index].flag != 0)
break;
break;
case '?':
printUsage(argv[0], stderr);
exit(1);
case 'v':
hopt->VERBOSE++;
break;
case 'A':
hopt->ASYMMETRY = 1;
break;
case 'I':
hopt->IDENTITY = 1;
break;
case 'b':
hopt->BIAS = 1;
break;
case 'K':
hopt->KEEP = 1;
break;
case 'S':
hopt->SORT = 1;
break;
case 'X':
hopt->CONSECUTIVE = 1;
break;
case 'T':
hopt->NO_TRACE_POINTS = 1;
break;
case 'j':
{
int tmp = atoi(optarg);
int test;
test = 1;
while (test < tmp)
test *= 2;
if (test == tmp)
{
hopt->NTHREADS = tmp;
}
else
{
fprintf(stderr, "invalid number of threads: %d. Must be a power of 2.\n", tmp);
exit(1);
}
}
break;
case 'k':
hopt->KINT = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument from kmer length (-k ARG)! Must be an integer in [4, 31]\n");
exit(1);
}
if (hopt->KINT < 4 || hopt->KINT > 31)
{
fprintf(stderr, "Kmer length not accepted! Must be in [4, 31]\n");
exit(1);
}
break;
case 'w':
hopt->WINT = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument from diagonal band width (-w ARG)! \n");
exit(1);
}
break;
case 'h':
hopt->HINT = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument from option -h/--hits! \n");
exit(1);
}
break;
case 't':
hopt->TINT = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument from option -t/--htimes! \n");
exit(1);
}
break;
case 'H':
hopt->HGAP = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument from option -H/--rlen! \n");
exit(1);
}
break;
case 'M':
hopt->MEM = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument from option -M/--mem! \n");
exit(1);
}
break;
case 'e':
hopt->EREL = strtod(optarg, NULL);
if (errno)
{
fprintf(stderr, "Cannot parse argument from option -e/--cor! \n");
exit(1);
}
if (hopt->EREL < .5 || hopt->EREL >= 1)
{
fprintf(stderr, "Average correlation not accepted! Must be in [.5, 1)\n");
exit(1);
}
break;
case 'l':
hopt->LINT = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument from option -l/--alen! \n");
exit(1);
}
break;
case 'r':
hopt->RUN_ID = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument from option -r/--rid! \n");
exit(1);
}
if (hopt->RUN_ID < 0 || hopt->RUN_ID > 999)
{
fprintf(stderr, "Run id not accepted! Must be in [0, 999]\n");
exit(1);
}
break;
case 's':
hopt->SINT = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument from option -s/--trace! \n");
exit(1);
}
break;
case 'n':
hopt->DAL_JOBS = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument from option -c/--dal! \n");
exit(1);
}
if (hopt->DAL_JOBS < 1)
{
fprintf(stderr, "Number of block comparisons per call to daligner not accepted! Must be in > 0! \n");
exit(1);
}
break;
case 'N':
hopt->DAL_DIAG_JOBS = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument from option -c/--dal! \n");
exit(1);
}
if (hopt->DAL_DIAG_JOBS < 1)
{
fprintf(stderr, "Number of block comparisons per call to daligner not accepted! Must be in > 0! \n");
exit(1);
}
break;
case 'c':
hopt->MERGE_JOBS = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument from option -c/--mrg! \n");
exit(1);
}
if (hopt->MERGE_JOBS < 3)
{
fprintf(stderr, "Maximum number of files that will be merged in a single LAmerge command not accepted! Must be in > 3! \n");
exit(1);
}
break;
case 'D':
{
char *ptr;
int ch = ':';
ptr = strchr(optarg, ch);
if (ptr)
{
hopt->port = (int) strtol(ptr + 1, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument port number from option -D/--dServer! \n");
exit(1);
}
hopt->host = (char*) malloc(strlen(optarg) + 10);
strcpy(hopt->host, optarg);
hopt->host[ptr - optarg] = '\0';
}
else
{
hopt->host = (char*) malloc(strlen(optarg) + 10);
strcpy(hopt->host, optarg);
}
}
break;
case 'o':
{
char *out;
out = (char*) malloc(strlen(optarg) + 20);
sprintf(out, "planDalign%s", optarg);
if ((hopt->dalignOut = fopen(out, "w")) == NULL)
{
fprintf(stderr, "ERROR - Cannot open file %s for writing\n", out);
exit(1);
}
sprintf(out, "planMerge%s", optarg);
if ((hopt->mergeOut = fopen(out, "w")) == NULL)
{
fprintf(stderr, "ERROR - Cannot open file %s for writing\n", out);
exit(1);
}
free(out);
}
break;
case 'm':
if (hopt->MTOP >= hopt->MMAX)
{
hopt->MMAX = 1.2 * hopt->MTOP + 10;
hopt->MASK = (char **) Realloc(hopt->MASK, hopt->MMAX * sizeof(char *), "Reallocating mask track array");
if (hopt->MASK == NULL)
exit(1);
}
hopt->MASK[hopt->MTOP] = optarg;
hopt->MTOP++;
break;
default:
fprintf(stderr, "[ERROR] Unsupported argument: %s\n", argv[optind]);
printUsage(argv[0], stderr);
exit(1);
}
}
if (optind + 1 > argc)
{
fprintf(stderr, "Required arument: <Database>\n");
printUsage(argv[0], stderr);
exit(1);
}
// database name
{
int len = strlen(argv[optind]);
hopt->db = (char*) malloc(len + 10);
strcpy(hopt->db, argv[optind]);
if (strcasecmp(hopt->db + (len - 3), ".db") != 0)
{
strcpy(hopt->db + len, ".db");
}
hopt->dbName = Root(hopt->db, ".db");
hopt->dbDir = PathTo(hopt->db);
// check if db file is available and parse number blocks
{
int nblocks = DB_Blocks(hopt->db);
if (nblocks < 0)
exit(1);
hopt->dbBlocks = nblocks;
hopt->fblock = 1;
hopt->lblock = nblocks;
}
optind++;
}
// parse blocks
if (optind < argc)
{
char * ptr;
int ch = '-';
int fblock;
int lblock;
ptr = strchr(argv[optind], ch);
if (ptr)
{
lblock = (int) strtol(ptr + 1, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse end block id! \n");
exit(1);
}
*ptr = '\0';
fblock = (int) strtol(argv[optind], NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse start block id! \n");
exit(1);
}
*ptr = '-';
}
else
{
fblock = (int) strtol(argv[optind], NULL, 10);
lblock = fblock;
if (errno)
{
fprintf(stderr, "Cannot parse block id! \n");
exit(1);
}
}
if (fblock < 1 || fblock > hopt->lblock)
{
fprintf(stderr, "Ivalid first block id %d! \n", fblock);
exit(1);
}
if (lblock < 1 || lblock < fblock || lblock > hopt->lblock)
{
fprintf(stderr, "Ivalid last block id %d! \n", lblock);
exit(1);
}
hopt->fblock = fblock;
hopt->lblock = lblock;
}
return hopt;
}
int main(int argc, char *argv[])
{
{
int njobs;
int i, j, k;
HPC_OPT *hopt = parseOptions(argc, argv);
if (hopt->DAL_DIAG_JOBS == 0)
{
if (hopt->host == NULL)
hopt->DAL_DIAG_JOBS = hopt->DAL_JOBS;
else
hopt->DAL_DIAG_JOBS = 1;
}
njobs = 0;
if (hopt->CONSECUTIVE)
{
for (i = hopt->fblock; i <= hopt->lblock; i++)
{
int low, hgh;
if (hopt->ASYMMETRY)
low = hopt->fblock;
else
low = i;
hgh = hopt->lblock;
int count;
while (low < hgh)
{
count = 0;
while (low <= hgh && count < hopt->DAL_JOBS)
{
count++;
low++;
}
njobs++;
}
}
}
else
{
for (i = hopt->fblock; i <= hopt->lblock; i++)
{
njobs += 1 + (int) ceil(1. * MAX(i - hopt->fblock + 1 - hopt->DAL_DIAG_JOBS, 0) / hopt->DAL_JOBS);
// printf("%d --> %d (%d)\n", i, 1 + (int)ceil(1.*MAX(i-hopt->fblock+1-hopt->DAL_DIAG_JOBS, 0) / hopt->DAL_JOBS), njobs);
}
}
int cur = 0;
int blockCmps = (hopt->lblock - hopt->fblock + 1) * (hopt->lblock - hopt->fblock + 2) / 2;
int test = 0;
if (hopt->dalignOut == stdout)
fprintf(hopt->dalignOut, "# Daligner jobs (%d)\n", njobs);
int first = 1;
// if ddust server is not used, then report daligner jobs linewise i.e. block.1 vs block 1...n, block.2 vs block 1...n, ... block.n vs block 1...n
if (hopt->CONSECUTIVE)
{
for (i = hopt->fblock; i <= hopt->lblock; i++)
{
int low, hgh;
if (hopt->ASYMMETRY)
low = hopt->fblock;
else
low = i;
hgh = hopt->lblock;
int count;
while (low <= hgh)
{
count = 0;
fprintf(hopt->dalignOut, "daligner");
if (hopt->VERBOSE)
fprintf(hopt->dalignOut, " -v");
if (hopt->BIAS)
fprintf(hopt->dalignOut, " -b");
if (hopt->ASYMMETRY)
fprintf(hopt->dalignOut, " -A");
if (hopt->IDENTITY)
fprintf(hopt->dalignOut, " -I");
if (hopt->IGNORE)
fprintf(hopt->dalignOut, " -i");
if (hopt->KINT != 14)
fprintf(hopt->dalignOut, " -k%d", hopt->KINT);
if (hopt->WINT != 6)
fprintf(hopt->dalignOut, " -w%d", hopt->WINT);
if (hopt->HINT != 35)
fprintf(hopt->dalignOut, " -h%d", hopt->HINT);
if (hopt->TINT > 0)
fprintf(hopt->dalignOut, " -t%d", hopt->TINT);
if (hopt->HGAP > 0)
fprintf(hopt->dalignOut, " -H%d", hopt->HGAP);
if (hopt->EREL > .1)
fprintf(hopt->dalignOut, " -e%g", hopt->EREL);
if (hopt->MREL > .1)
fprintf(hopt->dalignOut, " -m%g", hopt->MREL);
if (hopt->LINT != 1000)
fprintf(hopt->dalignOut, " -l%d", hopt->LINT);
if (hopt->SINT != 100)
fprintf(hopt->dalignOut, " -s%d", hopt->SINT);
if (hopt->MEM > 0)
fprintf(hopt->dalignOut, " -s%d", hopt->MEM);
if (hopt->NO_TRACE_POINTS > 0)
fprintf(hopt->dalignOut, " -T");
if (hopt->host)
fprintf(hopt->dalignOut, " -D%s", hopt->host);
if (hopt->port > 0)
fprintf(hopt->dalignOut, ":%d", hopt->port);
fprintf(hopt->dalignOut, " -r%d", hopt->RUN_ID);
fprintf(hopt->dalignOut, " -j%d", hopt->NTHREADS);
for (k = 0; k < hopt->MTOP; k++)
fprintf(hopt->dalignOut, " -m%s", hopt->MASK[k]);
if (strlen(hopt->dbDir) > 1)
fprintf(hopt->dalignOut, " %s%s.%d", hopt->dbDir, hopt->dbName, i);
else
fprintf(hopt->dalignOut, " %s.%d", hopt->dbName, i);
while (low <= hgh && count < hopt->DAL_JOBS)
{
if (strlen(hopt->dbDir) > 1)
fprintf(hopt->dalignOut, " %s%s.%d", hopt->dbDir, hopt->dbName, low);
else
fprintf(hopt->dalignOut, " %s.%d", hopt->dbName, low);
count++;
low++;
}
fprintf(hopt->dalignOut, "\n");
}
}
}
else
{
int low, hgh;
while (cur < blockCmps)
{
for (i = hopt->fblock; i <= hopt->lblock; i++)
{
if (first)
{
hgh = i - test * hopt->DAL_DIAG_JOBS;
low = MAX(hopt->fblock, hgh - hopt->DAL_DIAG_JOBS + 1);
}
else
{
hgh = i - (hopt->DAL_DIAG_JOBS + (test - 1) * hopt->DAL_JOBS);
low = MAX(hopt->fblock, hgh - hopt->DAL_JOBS + 1);
}
if (hgh >= low)
{
fprintf(hopt->dalignOut, "daligner");
if (hopt->VERBOSE)
fprintf(hopt->dalignOut, " -v");
if (hopt->BIAS)
fprintf(hopt->dalignOut, " -b");
if (hopt->ASYMMETRY)
fprintf(hopt->dalignOut, " -A");
if (hopt->IDENTITY)
fprintf(hopt->dalignOut, " -I");
if (hopt->IGNORE)
fprintf(hopt->dalignOut, " -i");
if (hopt->KINT != 14)
fprintf(hopt->dalignOut, " -k%d", hopt->KINT);
if (hopt->WINT != 6)
fprintf(hopt->dalignOut, " -w%d", hopt->WINT);
if (hopt->HINT != 35)
fprintf(hopt->dalignOut, " -h%d", hopt->HINT);
if (hopt->TINT > 0)
fprintf(hopt->dalignOut, " -t%d", hopt->TINT);
if (hopt->HGAP > 0)
fprintf(hopt->dalignOut, " -H%d", hopt->HGAP);
if (hopt->EREL > .1)
fprintf(hopt->dalignOut, " -e%g", hopt->EREL);
if (hopt->MREL > .1)
fprintf(hopt->dalignOut, " -m%g", hopt->MREL);
if (hopt->LINT != 1000)
fprintf(hopt->dalignOut, " -l%d", hopt->LINT);
if (hopt->SINT != 100)
fprintf(hopt->dalignOut, " -s%d", hopt->SINT);
if (hopt->NO_TRACE_POINTS > 0)
fprintf(hopt->dalignOut, " -T");
if (hopt->MEM > 0)
fprintf(hopt->dalignOut, " -s%d", hopt->MEM);
if (hopt->host)
fprintf(hopt->dalignOut, " -D%s", hopt->host);
if (hopt->port > 0)
fprintf(hopt->dalignOut, ":%d", hopt->port);
fprintf(hopt->dalignOut, " -r%d", hopt->RUN_ID);
fprintf(hopt->dalignOut, " -j%d", hopt->NTHREADS);
for (j = 0; j < hopt->MTOP; j++)
fprintf(hopt->dalignOut, " -m%s", hopt->MASK[j]);
if (strlen(hopt->dbDir) > 1)
fprintf(hopt->dalignOut, " %s%s.%d", hopt->dbDir, hopt->dbName, i);
else
fprintf(hopt->dalignOut, " %s.%d", hopt->dbName, i);
for (j = hgh; j >= low; j--)
{
cur++;
if (strlen(hopt->dbDir) > 1)
fprintf(hopt->dalignOut, " %s%s.%d", hopt->dbDir, hopt->dbName, j);
else
fprintf(hopt->dalignOut, " %s.%d", hopt->dbName, j);
}
fprintf(hopt->dalignOut, "\n");
}
}
if (first && hopt->dalignOut == stdout && hopt->host != NULL)
fprintf(hopt->dalignOut, "# end of diagonal\n");
first = 0;
test++;
}
}
if (hopt->dalignOut == stdout)
fprintf(hopt->mergeOut, "# merge jobs(%d)\n", hopt->lblock - hopt->fblock + 1);
char *dir;
for (i = hopt->fblock; i <= hopt->lblock; i++)
{
dir = getDir(hopt->RUN_ID, i);
fprintf(hopt->mergeOut, "LAmerge");
if (hopt->VERBOSE)
{
fprintf(hopt->mergeOut, " -");
int v;
for (v = 0; v < hopt->VERBOSE; v++)
fprintf(hopt->mergeOut, "v");
}
if (hopt->KEEP)
fprintf(hopt->mergeOut, " -k");
if (hopt->SORT)
fprintf(hopt->mergeOut, " -s");
fprintf(hopt->mergeOut, " -n %d", hopt->MERGE_JOBS);
fprintf(hopt->mergeOut, " %s %s.%d.las %s \n", hopt->db, hopt->dbName, i, dir);
}
}
exit(0);
}
|
MartinPippel/DAmar
|
lib/stats.c
|
<reponame>MartinPippel/DAmar
#include <math.h>
#include "stats.h"
#define SQR(a) ((a)*(a))
static double inverfc(double p)
{
double x, err, t, pp;
if (p >= 2.) return -100.;
if (p <= 0.0) return 100.;
pp=(p < 1.0)? p:2.-p;
t=sqrt(-2.*log(pp/2));
x= -0.70711*((2.30753+t*0.27061)/(1+t*(0.99229+t*0.04481))-t);
int j;
for (j=0;j<2;j++)
{
err=erfc(x)-pp;
x += err/(1.12837916709551257*exp(-x*x)-x*err);
}
return (p<1.0 ? x:-x);
}
double ln_invcdf(double p, double mu, double sig)
{
return exp(-1.41421356237309505*sig*inverfc(2.*p)+mu);
}
double ln_p(double x, double mu, double sig)
{
return (0.398942280401432678 / (sig*x)) * exp( -0.5*SQR((log(x)-mu)/sig) );
}
void ln_estimate(int* data, int n, double* mu, double* sig)
{
double _mu = 0.0;
double _sig = 0.0;
int i;
for (i = 0; i < n; i++)
{
_mu += log(data[i]);
}
_mu = _mu / n;
for (i = 0; i < n; i++)
{
_sig += SQR(log(data[i]) - _mu);
}
_sig = sqrt( _sig / n );
*mu = _mu;
*sig = _sig;
}
void n_estimate(int* data, int n, double* mu, double* sig)
{
double _mu = 0.0;
double _sig = 0.0;
int i;
for (i = 0; i < n; i++)
{
_mu += data[i];
}
_mu = _mu / n;
for (i = 0; i < n; i++)
{
_sig += SQR(data[i] - _mu);
}
_sig = sqrt( _sig / n );
*mu = _mu;
*sig = _sig;
}
void n_estimate_double(double* data, int n, double* mu, double* sig)
{
double _mu = 0.0;
double _sig = 0.0;
int i;
for (i = 0; i < n; i++)
{
_mu += data[i];
}
_mu = _mu / n;
for (i = 0; i < n; i++)
{
_sig += SQR(data[i] - _mu);
}
_sig = sqrt( _sig / n );
*mu = _mu;
*sig = _sig;
}
|
MartinPippel/DAmar
|
scrub/LAfix.c
|
<reponame>MartinPippel/DAmar<gh_stars>10-100
/*
repairs gaps and weak regions based on a read's overlaps
and produces a new set of sequences
Author: <NAME>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <sys/param.h>
#include "lib/colors.h"
#include "lib/tracks.h"
#include "lib/pass.h"
#include "lib/oflags.h"
#include "lib/utils.h"
#include "lib.ext/types.h"
#include "lib.ext/bitarr.h"
#include "db/DB.h"
#include "dalign/align.h"
// defaults
#define DEF_ARG_X 1000
#define DEF_ARG_G 500 // don't patch gaps above a certain size
#define DEF_ARG_Q 28 // low quality cutoff
#define DEF_ARG_B 7 // border coverage
#define DEF_ARG_C 8000 // maximum chimer length
#define DEF_ARG_F 0 // allow fuzzy LAS chain begin/end
#define DEF_ARG_R 70
// settings
#define FASTA_WIDTH 60 // wrapping for result fasta files
#define MIN_INT_LEN 5 // min length of an adjusted track interval
#define MIN_SPAN 400 // only alignments with at least MIN_SPAN bases left and right of a segment are considering as support
#define MIN_SPAN_REPEAT 800 // in repeats: only alignments with at least MIN_SPAN_REPEAT bases left and right of a segment are considering as support
// toggles
#undef DEBUG
#undef DEBUG_INTERVAL_ADJUSTMENT
#define DEBUG_FLIP
#undef DEBUG_CHAIN
#undef DEBUG_CHIMER
#define VERBOSE
// for getopt()
extern char* optarg;
extern int optind, opterr, optopt;
// context
typedef struct
{
Overlap **ovls;
int novl;
int maxOvl;
} Chain;
typedef struct
{
HITS_DB* db;
int twidth;
FILE* fileFastaOut;
FILE* fileQvOut;
FILE* fileTrimOut;
// arguments
int minlen;
int lowq;
int maxgap;
int trim;
int maxspanners;
int minsupport;
int fixChimers;
int maxChimerLen;
int minChimerBorderCov;
int fuzzyChain;
int repeatPerc;
char *qName;
HITS_TRACK* qtrack;
char *trimName;
HITS_TRACK* trimtrack;
char *repeatName;
HITS_TRACK* repeattrack;
HITS_TRACK** convertTracks;
int curctracks;
int maxctracks;
uint64_t stats_bases_before; // bases before patching
uint64_t stats_bases_after; // bases after patching
int discardChimericReads;
// stats
int num_flips;
int num_gaps;
int num_chimers;
char* reada;
char* readb;
char* read_patched;
char** qva;
char** qvb;
char** qv_patched;
int* apatches;
Chain *ovlChains;
int curChains;
int maxChains;
} FixContext;
// information on a gap/weak region
typedef struct
{
int ab; // a begin
int ae; // a end
int bb; // b begin
int be; // b end
int diff; // quality
int b; // b read id
int support; // how many reads support the gap
// int span; // reads spanning the gap
int comp; // complement sequence when writing
} Gap;
static void fix_pre(PassContext* pctx, FixContext* fctx)
{
#ifdef VERBOSE
printf(ANSI_COLOR_GREEN "PASS fix" ANSI_COLOR_RESET "\n");
#endif
fctx->twidth = pctx->twidth;
if (!(fctx->qtrack = track_load(fctx->db, fctx->qName)))
{
fprintf(stderr, "failed to open track %s\n", fctx->qName);
exit(1);
}
if (fctx->trimName)
{
if (!(fctx->trimtrack = track_load(fctx->db, fctx->trimName)))
{
fprintf(stderr, "failed to open track %s\n", fctx->trimName);
exit(1);
}
}
else
{
fctx->trimtrack = NULL;
}
if (fctx->repeatName)
{
if (!(fctx->repeattrack = track_load(fctx->db, fctx->repeatName)))
{
fprintf(stderr, "failed to open track %s\n", fctx->repeatName);
exit(1);
}
}
else
{
fctx->repeattrack = NULL;
}
int maxlen = fctx->db->maxlen;
fctx->reada = New_Read_Buffer(fctx->db);
fctx->readb = New_Read_Buffer(fctx->db);
fctx->read_patched = malloc(maxlen * 2 + 4);
if (fctx->fileQvOut)
{
fctx->qva = New_QV_Buffer(fctx->db);
fctx->qvb = New_QV_Buffer(fctx->db);
fctx->qv_patched = malloc(sizeof(char*) * NUM_QV_STREAMS);
char* qvs = malloc(maxlen * 2 * NUM_QV_STREAMS);
int i;
for (i = 0; i < NUM_QV_STREAMS; i++)
{
fctx->qv_patched[i] = qvs + i * maxlen * 2;
}
}
fctx->apatches = malloc((maxlen / pctx->twidth + 1) * 3 * sizeof(int));
fctx->curChains = 0;
fctx->maxChains = 5;
fctx->ovlChains = (Chain*) malloc(sizeof(Chain) * fctx->maxChains);
bzero(fctx->ovlChains, sizeof(Chain) * fctx->maxChains);
}
static void fix_post(PassContext* pctx, FixContext* fctx)
{
#ifdef VERBOSE
printf("gaps: %5d\n", fctx->num_gaps);
printf("flips: %5d\n", fctx->num_flips);
printf("chimers: %5d\n", fctx->num_chimers);
printf("replaced %'" PRIu64 " with %'" PRIu64 " bases\n", fctx->stats_bases_before, fctx->stats_bases_after);
#endif
UNUSED(pctx);
free(fctx->reada - 1);
free(fctx->readb - 1);
free(fctx->read_patched);
if (fctx->fileQvOut)
{
Free_QV_Buffer(fctx->qva);
Free_QV_Buffer(fctx->qvb);
Free_QV_Buffer(fctx->qv_patched);
}
free(fctx->apatches);
int i;
for (i = 0; i < fctx->maxChains; i++)
{
Chain *chain = fctx->ovlChains + i;
if (chain)
free(chain->ovls);
else
break;
}
free(fctx->ovlChains);
}
static int cmp_gaps(const void* x, const void* y)
{
Gap* a = (Gap*) x;
Gap* b = (Gap*) y;
int cmp = a->ab - b->ab;
if (cmp == 0)
{
cmp = a->ae - b->ae;
}
if (cmp == 0)
{
cmp = a->diff - b->diff;
}
return cmp;
}
#ifdef DEBUG_CHAIN
static void printChain(Chain *chain)
{
printf("CHAIN: nvols %d, %7d vs %7d %s\n", chain->novl, chain->ovls[0]->aread, chain->ovls[0]->bread, (chain->ovls[0]->flags & OVL_COMP) ? "COMP" : "NORM");
int i;
for (i = 0; i < chain->novl; ++i)
{
printf("%3d in A [%8d,%8d] in B [%8d,%8d] %5.2f\n", i, chain->ovls[i]->path.abpos, chain->ovls[i]->path.aepos, chain->ovls[i]->path.bbpos,
chain->ovls[i]->path.bepos, chain->ovls[i]->path.diffs * 100.0 / (chain->ovls[i]->path.aepos - chain->ovls[i]->path.abpos));
}
}
#endif
static int getRepeatCount(FixContext* ctx, int readID, int beg, int end)
{
if (ctx->repeattrack == NULL)
return 0;
track_anno* rep_anno = ctx->repeattrack->anno;
track_data* rep_data = ctx->repeattrack->data;
track_anno rb, re;
int repBases = 0;
int rBeg, rEnd;
if (readID < 0 || readID >= DB_NREADS(ctx->db))
{
fprintf(stderr, "[ERROR] - isInRepeat readID: %d out of bounds [0, %d]\n", readID, DB_NREADS(ctx->db) - 1);
fflush(stderr);
exit(1);
}
// repeat bases in a-read
rb = rep_anno[readID] / sizeof(track_data);
re = rep_anno[readID + 1] / sizeof(track_data);
while (rb < re)
{
rBeg = rep_data[rb];
rEnd = rep_data[rb + 1];
repBases += intersect(beg, end, rBeg, rEnd);
rb += 2;
}
return repBases;
}
static int contained(int ab, int ae, int bb, int be)
{
if (ab >= bb && ae <= be)
{
return 1;
}
return 0;
}
static int cmp_ovls_abeg(const void* a, const void* b)
{
Overlap* o1 = *(Overlap**) a;
Overlap* o2 = *(Overlap**) b;
int cmp = o1->path.abpos - o2->path.abpos;
if (!cmp)
{
cmp = (o1->path.aepos - o1->path.abpos) - (o2->path.aepos - o2->path.abpos);
}
return cmp;
}
static int cmp_chain_len(const void *a, const void *b)
{
Chain* c1 = (Chain *) a;
Chain* c2 = (Chain *) b;
int i;
int olen1 = c1->ovls[0]->path.aepos - c1->ovls[0]->path.abpos;
for (i = 1; i < c1->novl; i++)
{
olen1 += c1->ovls[i]->path.aepos - c1->ovls[i]->path.abpos;
if (c1->ovls[i - 1]->path.aepos > c1->ovls[i]->path.abpos)
olen1 -= c1->ovls[i - 1]->path.aepos > c1->ovls[i]->path.abpos;
}
int olen2 = c2->ovls[0]->path.aepos - c2->ovls[0]->path.abpos;
for (i = 1; i < c2->novl; i++)
{
olen2 += c2->ovls[i]->path.aepos - c2->ovls[i]->path.abpos;
if (c2->ovls[i - 1]->path.aepos > c2->ovls[i]->path.abpos)
olen2 -= c2->ovls[i - 1]->path.aepos > c2->ovls[i]->path.abpos;
}
return (olen2 - olen1);
}
static int getRepeatBases(FixContext *ctx, Overlap *ovl, int read)
{
if (ctx->repeattrack == NULL)
{
return 0;
}
assert(ovl->aread == read || ovl->bread == read);
int bLen = ovl->path.bepos - ovl->path.bbpos;
// get repeats track
track_anno* rep_anno = ctx->repeattrack->anno;
track_data* rep_data = ctx->repeattrack->data;
track_anno rb, re;
int nrep = 0;
rb = rep_anno[read] / sizeof(track_data);
re = rep_anno[read + 1] / sizeof(track_data);
// loop through all repeats in a
int rBeg, rEnd;
while (rb < re)
{
rBeg = rep_data[rb];
rEnd = rep_data[rb + 1];
if (ovl->aread == read)
{
nrep += intersect(ovl->path.abpos, ovl->path.aepos, rBeg, rEnd);
}
else
{
if (ovl->flags & OVL_COMP)
{
nrep += intersect(bLen - ovl->path.bepos, bLen - ovl->path.bbpos, rBeg, rEnd);
}
else
{
nrep += intersect(ovl->path.bbpos, ovl->path.bepos, rBeg, rEnd);
}
}
rb += 2;
}
return nrep;
}
static int spanningChain(FixContext*ctx, Overlap *ovls, int n, int chimerBeg, int chimerEnd, int trim_ab, int trim_ae)
{
/// TODO hard coded
int MIN_OVL_LOOKAHEAD = 2000;
int MAX_OVL_LOOKAHEAD = 10000;
int STRIDE_OVL_LOOKAHEAD = 2000;
int MIN_ANCHOR = 800;
int MIN_CHAIN_LEN = 3000;
int FUZZY = ctx->fuzzyChain;
if (n < 2)
{
if (!(ovls->flags & OVL_DISCARD) && ovls->path.abpos + MIN_ANCHOR < chimerBeg && ovls->path.aepos - MIN_ANCHOR > chimerEnd && ovls->path.aepos - ovls->path.abpos > MIN_CHAIN_LEN)
{
#ifdef DEBUG_CHAIN
printf("found spnning chain %d vs %d\n", ovls->aread, ovls->bread);
#endif
return 1;
}
return 0;
}
#ifdef DEBUG_CHAIN
printf("chain(%d,%d,%d) CHAIN: n%d m%d\n", ovls->aread, ovls->bread, n, ctx->curChains, ctx->maxChains);
#endif
int aread, bread;
int alen, blen;
int i;
aread = ovls->aread;
bread = ovls->bread;
alen = DB_READ_LEN(ctx->db, aread);
blen = DB_READ_LEN(ctx->db, bread);
int nremain = n;
#ifdef DEBUG_CHAIN
printf("find detect already excluded overlaps\n");
#endif
{
for (i = 0; i < n; i++)
{
Overlap *ovl_i = ovls + i;
if (ovl_i->flags & (OVL_CONT | OVL_DISCARD))
{
nremain--;
}
}
}
#ifdef DEBUG_CHAIN
printf("nremain %d\n", nremain);
#endif
if (nremain == 0)
return 0;
// mark contained overlaps
#ifdef DEBUG_CHAIN
printf("mark contained overlaps\n");
#endif
{
int j;
for (i = 0; i < n; i++)
{
Overlap *ovl_i = ovls + i;
if (ovl_i->flags & (OVL_CONT | OVL_DISCARD))
continue;
for (j = i + 1; j < n; j++)
{
Overlap *ovl_j = ovls + j;
if (ovl_j->flags & (OVL_CONT | OVL_DISCARD))
continue;
if (contained(ovl_j->path.abpos, ovl_j->path.aepos, ovl_i->path.abpos, ovl_i->path.aepos) && contained(ovl_j->path.bbpos, ovl_j->path.bepos, ovl_i->path.bbpos, ovl_i->path.bepos))
{
nremain--;
ovl_j->flags |= (OVL_CONT | OVL_DISCARD);
}
}
}
}
#ifdef DEBUG_CHAIN
printf("nremain %d\n", nremain);
#endif
assert(nremain >= 1);
while (nremain > 0)
{
int longestUniqOvlBases = -1;
int longestUniqOvlIdx = -1;
int longestOvlBases = -1;
int longestOvlIdx = -1;
// find longest overlap based on number of unique bases
for (i = 0; i < n; i++)
{
Overlap *ovl = ovls + i;
if (ovl->flags & (OVL_CONT | OVL_DISCARD | OVL_TEMP))
{
continue;
}
int aLen = ovl->path.aepos - ovl->path.abpos;
int bLen = ovl->path.bepos - ovl->path.bbpos;
int aRep = getRepeatBases(ctx, ovl, ovl->aread);
int bRep = getRepeatBases(ctx, ovl, ovl->bread);
#ifdef DEBUG_CHAIN
printf("%d - %d [%d, %d] [%d, %d], aR %d/%d, bR %d/%d\n", aread, bread, ovl->path.abpos, ovl->path.aepos, ovl->path.bbpos, ovl->path.bepos, aLen, aRep,
bLen, bRep);
#endif
int tmpBases = MAX(aLen - aRep, bLen - bRep);
if (tmpBases > longestUniqOvlBases)
{
longestUniqOvlBases = tmpBases;
longestUniqOvlIdx = i;
}
tmpBases = MAX(aLen, bLen);
if (tmpBases > longestOvlBases)
{
longestOvlBases = tmpBases;
longestOvlIdx = i;
}
}
assert(longestOvlIdx >= 0);
if (longestUniqOvlBases < ctx->twidth && longestOvlBases > longestUniqOvlBases)
{
#ifdef DEBUG_CHAIN
printf("Number of unique bases to low. Use longest overlap.\n");
#endif
longestUniqOvlBases = longestOvlBases;
longestUniqOvlIdx = longestOvlIdx;
}
#ifdef DEBUG_CHAIN
printf("longest overlap:\n");
printf("idx: %d --> uB %d, %d - %d [%d, %d] [%d, %d]\n", longestUniqOvlIdx, longestUniqOvlBases, ovls[longestUniqOvlIdx].aread,
ovls[longestUniqOvlIdx].bread, ovls[longestUniqOvlIdx].path.abpos, ovls[longestUniqOvlIdx].path.aepos, ovls[longestUniqOvlIdx].path.bbpos,
ovls[longestUniqOvlIdx].path.bepos);
#endif
// try to "elongate" longest overlap
// 1st on the right
// 2nd on the left side
if (ctx->curChains == ctx->maxChains)
{
ctx->maxChains = ctx->maxChains * 1.2 + 5;
ctx->ovlChains = (Chain*) realloc(ctx->ovlChains, sizeof(Chain) * ctx->maxChains);
bzero(ctx->ovlChains + ctx->curChains, sizeof(Chain) * (ctx->maxChains - ctx->curChains));
}
Chain *chain = ctx->ovlChains + ctx->curChains;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d, nremain: %d\n", chain->novl, chain->maxOvl, nremain);
#endif
if (chain->ovls == NULL)
{
chain->novl = 0;
chain->maxOvl = 10;
chain->ovls = (Overlap**) malloc(sizeof(Overlap*) * chain->maxOvl);
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d\n", chain->novl, chain->maxOvl);
#endif
}
chain->ovls[0] = ovls + longestUniqOvlIdx;
chain->ovls[0]->flags |= OVL_TEMP;
chain->novl++;
nremain--;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d, nremain %d\n", chain->novl, chain->maxOvl, nremain);
#endif
int ab1, ae1;
int bb1, be1;
int ab2, ae2;
int bb2, be2;
if (nremain && longestUniqOvlIdx + 1 < n)
{
ab1 = ovls[longestUniqOvlIdx].path.abpos;
ae1 = ovls[longestUniqOvlIdx].path.aepos;
bb1 = ovls[longestUniqOvlIdx].path.bbpos;
be1 = ovls[longestUniqOvlIdx].path.bepos;
#ifdef DEBUG_CHAIN
printf("extend longest overlap in right direction\n");
#endif
// 1st right
int cont = 1;
int curBestUniqOffset = 1;
int curBestUniqBases = -1;
int curBestBases = -1;
int curBestOffset = 1;
int curBestIntersection = MAX(alen, blen);
while (cont)
{
int stepSize;
for (stepSize = MIN_OVL_LOOKAHEAD; stepSize <= MAX_OVL_LOOKAHEAD && curBestUniqBases == -1; stepSize += STRIDE_OVL_LOOKAHEAD)
{
#ifdef DEBUG_CHAIN
printf("FOR LOOP stepsize %d\n", stepSize);
#endif
for (i = longestUniqOvlIdx + curBestUniqOffset; i < n; i++)
{
Overlap * ovl = ovls + i;
ab2 = ovl->path.abpos;
ae2 = ovl->path.aepos;
bb2 = ovl->path.bbpos;
be2 = ovl->path.bepos;
if ((ovl->flags & OVL_COMP) != (ovls[longestUniqOvlIdx].flags & OVL_COMP))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> different orientations\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_CONT)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> really contained repeat\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_TEMP)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> is part of another chain\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_DISCARD)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> discarded\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
// todo mark those as discard ????
if (contained(ab2, ae2, ab1, ae1))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> contained repeat in A-interval\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
// todo mark those as discard ????
if (contained(bb2, be2, bb1, be1))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> contained repeat in B-interval\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ae2 < ae1 || be2 < be1) // also overlap must follow right direction
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> improper right extension direction (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2,
bb2, be2, stepSize);
#endif
continue;
}
if (MAX(ab2 - ae1, bb2 - be1) > stepSize)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> gap size too large (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
continue;
}
if (ae1 - ab2 > ae2 - ae1 || be1 - bb2 > be2 - be1) // at least 50% overhang
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> overhang too short (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
continue;
}
// check if current overlap is better (longer/more unique bases ?) then curBest
int curUniqBasesInAIvl = (ae2 - ab2) - getRepeatBases(ctx, ovl, aread);
int curUniqBasesInBIvl = (be2 - bb2) - getRepeatBases(ctx, ovl, bread);
if (curBestIntersection > MAX(intersect(ab1, ae1, ab2, ae2), intersect(bb1, be1, bb2, be2)) && curBestBases < MIN(ae2 - ab2, be2 - bb2))
{
curBestBases = MIN(ae2 - ab2, be2 - bb2);
curBestOffset = i - longestUniqOvlIdx;
curBestIntersection = MAX(intersect(ab1, ae1, ab2, ae2), intersect(bb1, be1, bb2, be2));
}
if (curBestUniqBases < MIN(curUniqBasesInAIvl, curUniqBasesInBIvl))
{
#ifdef DEBUG_CHAIN
printf("found right current best overlap %d %d %d: [%d, %d] [%d, %d] right side\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
curBestUniqOffset = i - longestUniqOvlIdx;
curBestUniqBases = MIN(curUniqBasesInAIvl, curUniqBasesInBIvl);
}
else if (curBestUniqBases == -1 && stepSize + STRIDE_OVL_LOOKAHEAD > MAX_OVL_LOOKAHEAD) // for repetitive genomes
{
Overlap *tmpOvl = ovls + (longestUniqOvlIdx + curBestOffset);
if ((intersect(ab1, ae1, tmpOvl->path.abpos, tmpOvl->path.aepos) < ae1 - tmpOvl->path.abpos) && (intersect(bb1, be1, tmpOvl->path.bbpos, tmpOvl->path.bepos) < be1 - tmpOvl->path.bbpos))
{
curBestUniqOffset = curBestOffset;
curBestUniqBases = 1;
}
}
else
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> cannot be anchored (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
}
}
}
// check if left best overlap can be used to extend overlap group on the right side
if (curBestUniqBases < 0) // i.e. there was no good overlap at right side
{
#ifdef DEBUG_CHAIN
printf("could not extend ovlgroup on right side with proper overlap (with stepSize %d)\n", stepSize - STRIDE_OVL_LOOKAHEAD);
#endif
break;
}
/// todo further sanity check necessary ???
ab2 = ovls[longestUniqOvlIdx + curBestUniqOffset].path.abpos;
ae2 = ovls[longestUniqOvlIdx + curBestUniqOffset].path.aepos;
bb2 = ovls[longestUniqOvlIdx + curBestUniqOffset].path.bbpos;
be2 = ovls[longestUniqOvlIdx + curBestUniqOffset].path.bepos;
#ifdef DEBUG_CHAIN
printf("extend ovlgroup with (right): %d %d %d: [%d, %d] [%d, %d] stepSize %d\n", longestUniqOvlIdx + curBestUniqOffset,
ovls[longestUniqOvlIdx + curBestUniqOffset].aread, ovls[longestUniqOvlIdx + curBestUniqOffset].bread, ab1, ae1, ab2, ae2,
stepSize - STRIDE_OVL_LOOKAHEAD);
#endif
if (chain->novl == chain->maxOvl)
{
chain->maxOvl = chain->maxOvl * 1.2 + 5;
chain->ovls = (Overlap**) realloc(chain->ovls, sizeof(Overlap*) * chain->maxOvl);
}
// append left side overlaps at the end of chain, i.e. chain must be sorted afterwards by abpos
chain->ovls[chain->novl] = ovls + (longestUniqOvlIdx + curBestUniqOffset);
chain->ovls[chain->novl]->flags |= OVL_TEMP;
chain->novl++;
nremain--;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d nremain %d\n", chain->novl, chain->maxOvl, nremain);
#endif
ab1 = ab2;
ae1 = ae2;
bb1 = bb2;
be1 = be2;
curBestUniqOffset++;
curBestOffset = curBestUniqOffset;
curBestUniqBases = -1;
curBestBases = -1;
curBestIntersection = MAX(alen, blen);
if (longestUniqOvlIdx + curBestUniqOffset >= n)
{
cont = 0;
}
}
}
if (nremain && longestUniqOvlIdx > 0)
{
ab1 = ovls[longestUniqOvlIdx].path.abpos;
ae1 = ovls[longestUniqOvlIdx].path.aepos;
bb1 = ovls[longestUniqOvlIdx].path.bbpos;
be1 = ovls[longestUniqOvlIdx].path.bepos;
#ifdef DEBUG_CHAIN
printf("extend longest overlap in left direction\n");
#endif
// 2nd left side
int cont = 1;
int curBestUniqOffset = 1;
int curBestUniqBases = -1;
int curBestBases = -1;
int curBestOffset = 1;
int curBestIntersection = MAX(alen, blen);
while (cont)
{
int stepSize;
for (stepSize = MIN_OVL_LOOKAHEAD; stepSize <= MAX_OVL_LOOKAHEAD && curBestUniqBases == -1; stepSize += STRIDE_OVL_LOOKAHEAD)
{
#ifdef DEBUG_CHAIN
printf("FOR LOOP stepsize %d\n", stepSize);
#endif
// try to find next best overlap with lookahead of stepSize bases
for (i = longestUniqOvlIdx - curBestUniqOffset; i >= 0; --i)
{
Overlap * ovl = ovls + i;
#ifdef DEBUG_CHAIN
printf("LEFT: Check ovl: a[%d, %d] b[%d,%d]\n", ovl->path.abpos, ovl->path.aepos, ovl->path.bbpos, ovl->path.bepos);
#endif
ab2 = ovl->path.abpos;
ae2 = ovl->path.aepos;
bb2 = ovl->path.bbpos;
be2 = ovl->path.bepos;
if ((ovl->flags & OVL_COMP) != (ovls[longestUniqOvlIdx].flags & OVL_COMP))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> different orientations\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_CONT)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> really contained repeat\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_TEMP)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> is part of another chain\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_DISCARD)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> discarded\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
// todo mark those as discard ????
if (contained(ab2, ae2, ab1, ae1))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> contained repeat in A-interval\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
// todo mark those as discard ????
if (contained(bb2, be2, bb1, be1))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> contained repeat in B-interval\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ab2 > ab1 || bb2 > bb1) // also overlap must follow left direction
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> improper left extension direction (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2,
bb2, be2, stepSize);
#endif
continue;
}
if (MAX(ab1 - ae2, bb1 - be2) > stepSize)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> gap size too large (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
continue;
}
if (ae2 - ab1 > ab1 - ab2 || be2 - bb1 > bb1 - bb2) // at least 50% overhang
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> overhang too short (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
continue;
}
// check if current overlap is better (longer/more unique bases ?) then curLeftBest
int curUniqBasesInAIvl = (ae2 - ab2) - getRepeatBases(ctx, ovl, aread);
int curUniqBasesInBIvl = (be2 - bb2) - getRepeatBases(ctx, ovl, bread);
if (curBestIntersection > MAX(intersect(ab2, ae2, ab1, ae1), intersect(bb2, be2, bb1, be1)) && curBestBases < MIN(ae2 - ab2, be2 - bb2))
{
curBestBases = MIN(ae2 - ab2, be2 - bb2);
curBestOffset = longestUniqOvlIdx - i;
curBestIntersection = MAX(intersect(ab2, ae2, ab1, ae1), intersect(bb2, be2, bb1, be1));
}
if (curBestUniqBases < MIN(curUniqBasesInAIvl, curUniqBasesInBIvl))
{
#ifdef DEBUG_CHAIN
printf("found left current best overlap %d %d %d: [ab2 %d, ae2 %d] [bb2 %d, be2 %d] left side\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
curBestUniqOffset = longestUniqOvlIdx - i;
curBestUniqBases = curUniqBasesInAIvl + curUniqBasesInBIvl;
}
else if (curBestUniqBases == -1 && stepSize + STRIDE_OVL_LOOKAHEAD > MAX_OVL_LOOKAHEAD) // for repetitive genomes
{
Overlap *tmpOvl = ovls + (longestUniqOvlIdx - curBestOffset);
if ((intersect(tmpOvl->path.abpos, tmpOvl->path.aepos, ab1, ae1) < ae1 - tmpOvl->path.abpos) && (intersect(tmpOvl->path.bbpos, tmpOvl->path.bepos, bb1, be1) < be1 - tmpOvl->path.bbpos))
{
curBestUniqOffset = curBestOffset;
curBestUniqBases = 1;
}
}
else
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> cannot be anchored (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
}
}
}
// check if left best overlap can be used to extend overlap group on the left side
if (curBestUniqBases < 0) // i.e. there was no good overlap at left side
{
#ifdef DEBUG_CHAIN
printf("could not extend ovlgroup on left side with proper overlap (stepSize %d)\n", stepSize - STRIDE_OVL_LOOKAHEAD);
#endif
break;
}
/// todo further sanity check necessary ???
ab2 = ovls[longestUniqOvlIdx - curBestUniqOffset].path.abpos;
ae2 = ovls[longestUniqOvlIdx - curBestUniqOffset].path.aepos;
bb2 = ovls[longestUniqOvlIdx - curBestUniqOffset].path.bbpos;
be2 = ovls[longestUniqOvlIdx - curBestUniqOffset].path.bepos;
#ifdef DEBUG_CHAIN
printf("extend ovlgroup with (left): %d %d %d: [%d, %d] [%d, %d] with stepSize %d\n", longestUniqOvlIdx - curBestUniqOffset,
ovls[longestUniqOvlIdx - curBestUniqOffset].aread, ovls[longestUniqOvlIdx - curBestUniqOffset].bread, ab1, ae1, ab2, ae2,
stepSize - STRIDE_OVL_LOOKAHEAD);
#endif
if (ctx->curChains == ctx->maxChains)
{
ctx->maxChains = ctx->maxChains * 1.2 + 5;
ctx->ovlChains = (Chain*) realloc(ctx->ovlChains, sizeof(Chain) * ctx->maxChains);
bzero(ctx->ovlChains + ctx->curChains, sizeof(Chain) * (ctx->maxChains - ctx->curChains));
}
if (chain->novl == chain->maxOvl)
{
chain->maxOvl = chain->maxOvl * 1.2 + 5;
chain->ovls = (Overlap**) realloc(chain->ovls, sizeof(Overlap*) * chain->maxOvl);
}
// append left side overlaps at the end of chain, i.e. chain must be sorted afterwards by abpos
chain->ovls[chain->novl] = ovls + (longestUniqOvlIdx - curBestUniqOffset);
chain->ovls[chain->novl]->flags |= OVL_TEMP;
chain->novl++;
nremain--;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d nremain %d\n", chain->novl, chain->maxOvl, nremain);
#endif
ab1 = ab2;
ae1 = ae2;
bb1 = bb2;
be1 = be2;
curBestUniqOffset++;
curBestOffset = curBestUniqOffset;
curBestUniqBases = -1;
curBestBases = -1;
curBestIntersection = MAX(alen, blen);
if (longestUniqOvlIdx - curBestUniqOffset < 0)
{
cont = 0;
}
}
if (chain->novl > 1)
{ // sort chain
qsort(chain->ovls, chain->novl, sizeof(Overlap*), cmp_ovls_abeg);
}
}
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d nremain: %d\n", chain->novl, chain->maxOvl, nremain);
#endif
// find possible ovls that could be added to chain (i.e. fill gaps)
if (chain->novl > 1 && nremain > 0)
{
#ifdef DEBUG_CHAIN
printf("find possible ovls that could be added to chain (i.e. fill gaps)\n");
#endif
int chainIdx = 0;
int chainLastIdx = chain->novl - 1;
int j;
for (i = 0; i < n; i++)
{
Overlap *ovl = ovls + i;
if ((ovl->flags & (OVL_TEMP | OVL_CONT | OVL_DISCARD)) || ((ovl->flags & OVL_COMP) != (chain->ovls[chainIdx]->flags & OVL_COMP)))
continue;
if (ovl->path.abpos < chain->ovls[chainIdx]->path.abpos)
continue;
if (ovl->path.abpos > chain->ovls[chainLastIdx]->path.abpos)
break;
for (j = chainIdx; j < chainLastIdx; j++)
{
if (chain->ovls[j]->path.aepos <= ovl->path.abpos && chain->ovls[j + 1]->path.abpos >= ovl->path.aepos && chain->ovls[j]->path.bepos <= ovl->path.bbpos && chain->ovls[j + 1]->path.bbpos >= ovl->path.bepos)
{
Overlap *lastAddedOvl = chain->ovls[chain->novl - 1];
if (intersect(ovl->path.abpos, ovl->path.aepos, lastAddedOvl->path.abpos, lastAddedOvl->path.aepos) || intersect(ovl->path.bbpos, ovl->path.bepos, lastAddedOvl->path.bbpos, lastAddedOvl->path.bepos))
break;
if (chain->novl == chain->maxOvl)
{
chain->maxOvl = chain->maxOvl * 1.2 + 5;
chain->ovls = (Overlap**) realloc(chain->ovls, sizeof(Overlap*) * chain->maxOvl);
}
// append left side overlaps at the end of chain, i.e. chain must be sorted afterwards by abpos
ovl->flags |= OVL_TEMP;
chain->ovls[chain->novl] = ovl;
chain->novl++;
nremain--;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d nremain %d\n", chain->novl, chain->maxOvl, nremain);
#endif
}
if (ovl->path.abpos > chain->ovls[j + 1]->path.abpos)
chainIdx++;
}
}
if (chainLastIdx < chain->novl - 1)
{
qsort(chain->ovls, chain->novl, sizeof(Overlap*), cmp_ovls_abeg);
}
}
if (nremain)
{
// mark remaining ovls as DISC if the overlap with a chain overlap !!
#ifdef DEBUG_CHAIN
printf("// mark remaining ovls as DISC if they overlap with a chain overlap !!\n");
#endif
int chainIdx = 0;
int chainLastIdx = chain->novl - 1;
int j;
for (i = 0; i < n; i++)
{
Overlap *ovl = ovls + i;
if ((ovl->flags & (OVL_TEMP | OVL_CONT | OVL_DISCARD)) || ((ovl->flags & OVL_COMP) != (chain->ovls[chainIdx]->flags & OVL_COMP)))
continue;
for (j = chainIdx; j <= chainLastIdx; j++)
{
if (intersect(chain->ovls[j]->path.abpos, chain->ovls[j]->path.aepos, ovl->path.abpos, ovl->path.aepos) || intersect(chain->ovls[j]->path.bbpos, chain->ovls[j]->path.bepos, ovl->path.bbpos, ovl->path.bepos))
{
ovl->flags |= OVL_DISCARD;
nremain--;
#ifdef DEBUG_CHAIN
printf("DISCARD [%d, %d] [%d, %d] nremain %d\n", ovl->path.abpos, ovl->path.aepos, ovl->path.bbpos, ovl->path.bepos, nremain);
#endif
}
if (j + 1 < chain->novl && ovl->path.abpos > chain->ovls[j + 1]->path.abpos)
chainIdx++;
}
}
}
#ifdef DEBUG_CHAIN
printChain(chain);
#endif
// sanity check // there should be no intersection with other chains (with same orientation) possible
int valid = 1;
if (ctx->curChains)
{
#ifdef DEBUG_CHAIN
printf("DO SANITY CHECK\n");
#endif
int j;
for (i = 0; i < ctx->curChains && valid; i++)
{
if ((chain->ovls[0]->flags & OVL_COMP) == (ctx->ovlChains[i].ovls[0]->flags && OVL_COMP))
{
for (j = 0; j < chain->novl; j++)
{
if ((chain->ovls[j]->path.abpos > ctx->ovlChains[i].ovls[0]->path.abpos && chain->ovls[j]->path.aepos < ctx->ovlChains[i].ovls[ctx->ovlChains[i].novl - 1]->path.aepos)
|| (chain->ovls[j]->path.bbpos > ctx->ovlChains[i].ovls[0]->path.bbpos && chain->ovls[j]->path.bepos < ctx->ovlChains[i].ovls[ctx->ovlChains[i].novl - 1]->path.bepos))
{
#ifdef DEBUG_CHAIN
printf("CHAIN is invalid - DISCARD\n");
#endif
valid = 0;
break;
}
}
}
}
}
if (valid)
ctx->curChains++;
else
{
int j;
for (j = 0; j < chain->novl; j++)
{
chain->ovls[j]->flags |= OVL_DISCARD;
}
chain->novl = 0;
}
#ifdef DEBUG_CHAIN
printf("curChain: %d, remain unchained OVls: %d\n", ctx->curChains, nremain);
#endif
}
#ifdef DEBUG_CHAIN
printf("FINAL CHAINS: %d %7d vs %7d\n", ctx->curChains, ctx->ovlChains[0].ovls[0]->aread, ctx->ovlChains[0].ovls[0]->bread);
for (i = 0; i < ctx->curChains; i++)
{
printf(" CHAIN %d/%d: #novl %d\n", i + 1, ctx->curChains, ctx->ovlChains[0].novl);
int j;
for (j = 0; j < ctx->ovlChains[i].novl; j++)
{
printf(" OVL %d/%d: a[%7d, %7d] b[%7d, %7d] %s\n", j + 1, ctx->ovlChains[i].novl, ctx->ovlChains[i].ovls[j]->path.abpos,
ctx->ovlChains[i].ovls[j]->path.aepos, ctx->ovlChains[i].ovls[j]->path.bbpos, ctx->ovlChains[i].ovls[j]->path.bepos,
(ctx->ovlChains[i].ovls[j]->flags & OVL_COMP) ? "COMP" : "NORM");
}
}
#endif
// sort chains according to alignment lengths
if (ctx->curChains > 1)
{
#ifdef DEBUG_CHAIN
printf("SORT CHAINS (longest first):\n");
#endif
qsort(ctx->ovlChains, ctx->curChains, sizeof(Chain), cmp_chain_len);
#ifdef DEBUG_CHAIN
printf("FINAL CHAINS: %d %7d vs %7d\n", ctx->curChains, ctx->ovlChains[0].ovls[0]->aread, ctx->ovlChains[0].ovls[0]->bread);
for (i = 0; i < ctx->curChains; i++)
{
printf(" CHAIN %d/%d: #novl %d\n", i + 1, ctx->curChains, ctx->ovlChains[0].novl);
int j;
for (j = 0; j < ctx->ovlChains[i].novl; j++)
{
printf(" OVL %d/%d: a[%7d, %7d] b[%7d, %7d] %s\n", j + 1, ctx->ovlChains[i].novl, ctx->ovlChains[i].ovls[j]->path.abpos,
ctx->ovlChains[i].ovls[j]->path.aepos, ctx->ovlChains[i].ovls[j]->path.bbpos, ctx->ovlChains[i].ovls[j]->path.bepos,
(ctx->ovlChains[i].ovls[j]->flags & OVL_COMP) ? "COMP" : "NORM");
}
}
#endif
}
// cleanup all flags
for (i = 0; i < n; i++)
{
ovls[i].flags &= ~(OVL_DISCARD | OVL_TEMP | OVL_CONT);
}
// check if chain spans putative chimer
Chain* bestChain = ctx->ovlChains;
int trim_bb, trim_be;
if (ctx->trimtrack)
{
get_trim(ctx->db, ctx->trimtrack, ovls->bread, &trim_bb, &trim_be);
}
else
{
trim_bb = 0;
trim_be = DB_READ_LEN(ctx->db, ovls->bread);
}
if (bestChain->ovls[0]->path.abpos + MIN_ANCHOR > chimerBeg)
return 0;
if (bestChain->ovls[bestChain->novl - 1]->path.aepos - MIN_ANCHOR < chimerEnd)
return 0;
int chainLen = 0;
for (i = 0; i < bestChain->novl; i++)
chainLen += bestChain->ovls[i]->path.aepos - bestChain->ovls[i]->path.abpos;
if (chainLen < MIN_CHAIN_LEN)
return 0;
// chain must be proper
// todo
// 1. allow not fully proper chain? i.e. that start/end near the tips of the trim intervals????
// 2. set a minimum overlaps length to avoid 'sparse chains' (only induced by repeats) ??
// 3. set a minimum of non-repeat bases for a chain ??? --> DONE
if (bestChain->ovls[0]->flags & OVL_COMP)
{
// if(bestChain->ovls[0]->aread == 29 && bestChain->ovls[0]->bread == 29372)
// {
// printf(" READ 29 29372 ab: %d < %d bb: %d < %d ae: %d < %d be: %d < %d\n", bestChain->ovls[0]->path.abpos - FUZZY, trim_ab, (blen - bestChain->ovls[0]->path.bepos) - FUZZY, trim_bb,
// bestChain->ovls[bestChain->novl-1]->path.aepos + FUZZY, trim_ae, (blen - bestChain->ovls[bestChain->novl-1]->path.bbpos) + FUZZY, trim_be);
// }
if (((bestChain->ovls[0]->path.abpos - FUZZY <= trim_ab) || ((blen - bestChain->ovls[0]->path.bepos) - FUZZY <= trim_bb)) && ((bestChain->ovls[bestChain->novl - 1]->path.aepos + FUZZY >= trim_ae) || ((blen - bestChain->ovls[bestChain->novl - 1]->path.bbpos) + FUZZY >= trim_be)))
{
#ifdef DEBUG_CHAIN
printf("found spanning chain %d vs %d\n", ovls->aread, ovls->bread);
#endif
return 1;
}
}
else
{
if (((bestChain->ovls[0]->path.abpos - FUZZY <= trim_ab) || (bestChain->ovls[0]->path.bbpos - FUZZY <= trim_bb)) && ((bestChain->ovls[bestChain->novl - 1]->path.aepos + FUZZY >= trim_ae) || (bestChain->ovls[bestChain->novl - 1]->path.bepos + FUZZY >= trim_be)))
{
#ifdef DEBUG_CHAIN
printf("found spanning chain %d vs %d\n", ovls->aread, ovls->bread);
#endif
return 1;
}
}
return 0;
}
static int oChainIntervalIntersection(FixContext *fctx, Overlap* ovls, int novl, int b, int e, int trim_ab, int trim_ae)
{
int spanningChains = 0;
int j, k;
j = k = 0;
while (j < novl)
{
while (k < novl - 1 && ovls[j].bread == ovls[k + 1].bread)
{
k++;
}
spanningChains += spanningChain(fctx, ovls + j, k - j + 1, b, e, trim_ab, trim_ae);
{
// reset chain and ovl counter
int i;
for (i = 0; i < fctx->curChains; i++)
fctx->ovlChains[i].novl = 0;
fctx->curChains = 0;
}
if (spanningChains)
return spanningChains;
j = k + 1;
}
return spanningChains;
}
static int bReadIntersectionInterval(FixContext *fctx, Overlap* ovls, int novl, int b, int e)
{
bit* visited = ba_new(DB_NREADS(fctx->db));
int NON_REP_BASES = 10;
int i;
int pre = 0;
int post = 0;
for (i = 0; i < novl; i++)
{
Overlap* ovl = ovls + i;
if (ovl->path.abpos + MIN(b / 2, 1000) < b && ((ovl->path.aepos - ovl->path.abpos) - getRepeatCount(fctx, ovl->aread, ovl->path.abpos, ovl->path.aepos) >= NON_REP_BASES))
{
ba_assign(visited, ovl->bread, TRUE);
++pre;
}
}
int intersection = 0;
for (i = 0; i < novl; i++)
{
Overlap* ovl = ovls + i;
if (ovl->path.aepos - MIN((DB_READ_LEN(fctx->db, ovl->aread) - e) / 2, 1000) > e && ((ovl->path.aepos - ovl->path.abpos) - getRepeatCount(fctx, ovl->aread, ovl->path.abpos, ovl->path.aepos) >= NON_REP_BASES))
{
if (ba_value(visited, ovl->bread))
{
ba_assign(visited, ovl->bread, FALSE);
intersection++;
}
++post;
}
}
free(visited);
// if there are almost no overlaps before or after chimer, then chimer detection is not reliable!
// if(pre <= 3 || post <= 3)
// return 99;
return intersection;
}
static int spanners_interval(FixContext *fctx, Overlap* ovls, int novl, int b, int e)
{
int span = 0;
int minSpan = (e - b - getRepeatCount(fctx, ovls->aread, b, e) < 100) ? MIN_SPAN_REPEAT : MIN_SPAN;
int trim_ab, trim_ae;
if (fctx->trimtrack)
{
get_trim(fctx->db, fctx->trimtrack, ovls->aread, &trim_ab, &trim_ae);
}
else
{
trim_ab = 0;
trim_ae = DB_READ_LEN(fctx->db, ovls->aread);
}
int i;
for (i = 0; i < novl; i++)
{
Overlap* ovl = ovls + i;
if (ovl->path.abpos <= MAX(trim_ab, b - minSpan) && ovl->path.aepos >= MIN(trim_ae, e + minSpan))
{
span++;
}
}
#ifdef DEBUG
if (ovls->aread == 344566)
printf("spanners_interval %d minspan %d [%d ,%d] #span: %d\n", ovls->aread, minSpan, b, e, span);
#endif
return span;
}
static int spanners_point(FixContext *fctx, Overlap* ovls, int novl, int p, int max)
{
int span = 0;
int minSpan = getRepeatCount(fctx, ovls->aread, p, p + 1) ? MIN_SPAN_REPEAT : MIN_SPAN;
int i;
for (i = 0; i < novl; i++)
{
Overlap* ovl = ovls + i;
if (ovl->path.abpos < p - minSpan && ovl->path.aepos > p + minSpan)
{
span++;
if (span > max)
{
break;
}
}
}
#ifdef DEBUG
if (ovls->aread == 218393)
printf("spanners_point %d minspan %d point %d #span: %d max %d\n", ovls->aread, minSpan, p, span, max);
#endif
return (span > max);
}
static int filter_chimers(FixContext* fctx, Overlap* ovls, int novl, int* trim_b, int* trim_e)
{
int *alnBeg = (int *) malloc((DB_READ_MAXLEN(fctx->db) / fctx->twidth + 1) * sizeof(int));
memset(alnBeg, 0, (DB_READ_MAXLEN(fctx->db) / fctx->twidth + 1) * sizeof(int));
int *alnEnd = (int *) malloc((DB_READ_MAXLEN(fctx->db) / fctx->twidth + 1) * sizeof(int));
memset(alnEnd, 0, (DB_READ_MAXLEN(fctx->db) / fctx->twidth + 1) * sizeof(int));
#ifdef DEBUG_CHIMER
printf("filter_chimers aread %d #ovls %d trim [%d, %d]\n", ovls->aread, novl, *trim_b, *trim_e);
#endif
int i;
for (i = 1; i < novl - 1; i++)
{
Overlap *opre = ovls + i - 1;
Overlap *ocur = ovls + i;
Overlap *opas = ovls + i + 1;
int prematEnd = (ocur->path.bepos + 1000 < DB_READ_LEN(fctx->db, ocur->bread)) && (ocur->path.aepos + 1000 < *trim_e) && (ocur->path.aepos - 100 > *trim_b);
int prematBeg = (ocur->path.bbpos > 1000) && (ocur->path.abpos > *trim_b + 1000) && (ocur->path.abpos + 100 < *trim_e);
// // check weird case first
if (prematBeg && prematEnd && (opre->bread != ocur->bread) && (ocur->bread != opas->bread)) // most probably a repeat
continue;
if ((ocur->bread != opas->bread) && prematEnd)
{
alnEnd[(ocur->path.aepos / fctx->twidth)] += 1;
#ifdef DEBUG_CHIMER
printf("found end %d vs %d a[%d, %d] b[%d, %d] ends[%d]=%d\n", ocur->aread, ocur->bread, ocur->path.abpos, ocur->path.aepos, ocur->path.bbpos,
ocur->path.bepos, (ocur->path.aepos / fctx->twidth), alnEnd[(ocur->path.aepos / fctx->twidth)]);
#endif
}
else if ((opre->bread != ocur->bread) && prematBeg)
{
alnBeg[(ocur->path.abpos / fctx->twidth)] += 1;
#ifdef DEBUG_CHIMER
printf("found beg %d vs %d a[%d, %d] b[%d, %d] beg[%d]=%d\n", ocur->aread, ocur->bread, ocur->path.abpos, ocur->path.aepos, ocur->path.bbpos,
ocur->path.bepos, (ocur->path.abpos / fctx->twidth), alnBeg[(ocur->path.abpos / fctx->twidth)]);
#endif
}
}
int chimBeg = -1;
int chimEnd = -1;
int numChim = 0;
int remainBeg = *trim_b;
int remainEnd = *trim_e;
int j;
i = j = 0;
for (i = remainBeg / fctx->twidth; i <= remainEnd / fctx->twidth; i++)
{
if (alnEnd[i] >= fctx->minChimerBorderCov)
{
chimBeg = i;
}
else if (alnEnd[i] + alnEnd[i + 1] >= fctx->minChimerBorderCov)
{
chimBeg = ++i;
}
if (chimBeg < 0)
continue;
for (j = remainBeg / fctx->twidth; j <= remainEnd / fctx->twidth; j++)
{
if (alnBeg[j] >= fctx->minChimerBorderCov)
{
chimEnd = j;
}
else if (alnBeg[j] + alnBeg[j + 1] >= fctx->minChimerBorderCov)
{
chimEnd = ++j;
}
if (chimEnd < 0)
continue;
#ifdef DEBUG_CHIMER
printf("check putative chimer indexes [%d, %d]\n", chimBeg, chimEnd);
#endif
chimBeg = i * fctx->twidth;
chimEnd *= fctx->twidth;
if (chimBeg > chimEnd)
{
int tmp = chimBeg;
chimBeg = chimEnd;
chimEnd = tmp;
}
#ifdef DEBUG_CHIMER
printf("check putative chimer interval [%d, %d]\n", chimBeg, chimEnd);
#endif
if ((chimEnd - chimBeg) > fctx->maxChimerLen)
{
#ifdef DEBUG_CHIMER
printf("chimer interval too large [%d, %d] len %d-- IGNORED\n", chimBeg, chimEnd, (chimEnd - chimBeg));
#endif
chimEnd = -1;
continue;
}
int tmpRep = getRepeatCount(fctx, ovls->aread, chimBeg, chimEnd);
#ifdef DEBUG_CHIMER
printf("getRepeatCount %d %d %d: %d\n", ovls->aread, chimBeg, chimEnd, tmpRep);
#endif
if ((chimEnd - chimBeg) > 1000 && tmpRep * 100.0 / (chimEnd - chimBeg) < fctx->repeatPerc)
{
#ifdef DEBUG_CHIMER
printf("chimer interval too large [%d, %d] len %d but not repetitive %.2f%%-- IGNORED\n", chimBeg, chimEnd, (chimEnd - chimBeg),
tmpRep * 1.0 / (chimEnd - chimBeg));
#endif
chimEnd = -1;
continue;
}
int crossingChains = oChainIntervalIntersection(fctx, ovls, novl, chimBeg, chimEnd, remainBeg, remainEnd);
#ifdef DEBUG_CHIMER
printf("intersectBreads %d\n", crossingChains);
#endif
if (crossingChains < 1)
{
#ifdef DEBUG_CHIMER
printf("check putative chimer (spanner < 1 true) interval [%d, %d]\n", chimBeg, chimEnd);
#endif
if (numChim == 0)
{
if (chimBeg - *trim_b > *trim_e - chimEnd)
{
remainEnd = chimBeg;
}
else
{
remainBeg = chimEnd;
}
}
else if (chimBeg < remainEnd)
{
if (chimBeg - remainBeg > remainEnd - chimEnd)
{
remainEnd = chimBeg;
}
else
{
remainBeg = chimEnd;
}
}
++numChim;
#ifdef DEBUG_CHIMER
printf("AREAD %d FOUND %d. CHIMER [%d, %d] best remaining part [%d, %d]\n", ovls->aread, numChim, chimBeg, chimEnd, remainBeg, remainEnd);
#endif
chimEnd = -1;
break;
}
chimEnd = -1;
j += 2; // don't check neighboring walls
}
chimBeg = -1;
i += 2; // don't check neighboring walls
}
if (numChim)
{
*trim_b = remainBeg;
*trim_e = remainEnd;
if (fctx->discardChimericReads)
{
int tmp = *trim_b;
*trim_b = *trim_e;
*trim_e = tmp;
}
#ifdef DEBUG_FLIP
printf("FINALCHIMER %d [%d, %d] remaining part [%d, %d]\n", ovls->aread, chimBeg, chimEnd, *trim_b, *trim_e);
#endif
}
free(alnBeg);
free(alnEnd);
return numChim;
}
static int filter_flips(FixContext* fctx, Overlap* ovls, int novl, int* trim_b, int* trim_e)
{
int self_n = 0;
int self_c = 0;
int aread = ovls->aread;
int trimmed = 0;
int b = -1;
int e = -1;
int i;
for (i = 0; i < novl; i++)
{
Overlap* ovl = ovls + i;
int bread = ovl->bread;
if (aread < bread)
{
if (b != -1)
{
e = i;
}
break;
}
else if (aread == bread)
{
if (b == -1)
{
b = i;
}
if (ovl->flags & OVL_COMP)
{
self_c++;
}
else
{
self_n++;
}
}
}
if (self_c == 0)
{
return trimmed;
}
#ifdef DEBUG
printf("%7d %3d %3d [%4d..%4d]\n", aread, self_c, self_n, b, e);
#endif
int alen = DB_READ_LEN(fctx->db, aread);
for (i = b; i < e; i++)
{
Overlap* ovl = ovls + i;
if (ovl->flags & OVL_COMP)
{
int ab = ovl->path.abpos;
int ae = ovl->path.aepos;
int ab_c = alen - ovl->path.bepos;
int ae_c = alen - ovl->path.bbpos;
if (intersect(ab, ae, ab_c, ae_c))
{
#ifdef DEBUG
printf(" -> crosses diagonal %5d..%5d x %5d..%5d\n", ab, ae, ab_c, ae_c);
#endif
ovl_trace* trace = ovl->path.trace;
int sab = ovl->path.abpos;
int sae = (sab / fctx->twidth + 1) * fctx->twidth;
int sbb = ovl->path.bbpos;
int sbe = sbb + trace[1];
#ifdef DEBUG
printf(" -> sab %d sae %d sbb %d sbe %d\n", sab, sae, sbb, sbe);
#endif
int j;
for (j = 2; j < ovl->path.tlen - 2; j += 2)
{
//if (intersect(sab, sae, alen - sbe, alen - sbb)) // && spanners(ovls, novl, sab, sae) <= 1 )
if (intersect(sab, sae + 1, alen - sbe, alen - sbb - 1) && spanners_interval(fctx, ovls, novl, sab, sae) <= 1 ) // modified 25.06.18 change interval from [ ) to [ ]
{
#ifdef DEBUG_FLIP
printf("%8d CROSS @ %5d..%5d x %5d..%5d\n", aread, sab, sae, alen - sbe, alen - sbb);
#endif
trimmed = 1;
if (*trim_b < sab && sae < *trim_e)
{
if (sab - *trim_b < *trim_e - sae)
{
*trim_b = sae;
}
else
{
*trim_e = sab;
}
}
}
sab = sae;
sae += fctx->twidth;
sbb = sbe;
sbe += trace[j + 1];
}
sae = ovl->path.aepos;
sbe = ovl->path.bepos;
}
}
}
i = b;
while (i < e - 1)
{
Overlap* ovl = ovls + i;
Overlap* ovl2 = ovls + i + 1;
if ((ovl->flags & OVL_COMP) && (ovl2->flags & OVL_COMP))
{
int ab = ovl->path.aepos;
int ae = ovl2->path.abpos;
int ab_c = alen - ovl2->path.bbpos;
int ae_c = alen - ovl->path.bepos;
if (intersect(ab, ae, ab_c, ae_c) && spanners_interval(fctx, ovls, novl, ab, ae) <= 1)
{
#ifdef DEBUG_FLIP
printf("%8d GAP @ %5d..%5d x %5d..%5d\n", aread, ab, ae, ab_c, ae_c);
#endif
trimmed = 1;
int mid = (ab + ae) / 2;
if (*trim_b < mid && mid < *trim_e)
{
if (mid - *trim_b < *trim_e - mid)
{
*trim_b = mid;
}
else
{
*trim_e = mid;
}
}
}
}
i += 1;
}
return trimmed;
}
static int fix_process(void* _ctx, Overlap* ovl, int novl)
{
// #warning "REMOVE ME"
// if ( ovl->aread != 166815 ) return 1;
FixContext* fctx = (FixContext*) _ctx;
// #warning "REMOVE ME"
// if ( DB_READ_LEN(fctx->db, ovl->aread) < 20000 ) return 1;
int maxgap = fctx->maxgap;
int lowq = fctx->lowq;
int twidth = fctx->twidth;
int maxspanners = fctx->maxspanners;
int minsupport = fctx->minsupport;
int dcur = 0;
int dmax = 1000;
Gap* data = malloc(sizeof(Gap) * dmax);
track_anno* qanno = fctx->qtrack->anno;
track_data* qdata = fctx->qtrack->data;
track_data* qa = qdata + (qanno[ovl->aread] / sizeof(track_data));
// get trim offsets and skip reads that get trimmed away
int trim_ab, trim_ae;
if (fctx->trimtrack)
{
get_trim(fctx->db, fctx->trimtrack, ovl->aread, &trim_ab, &trim_ae);
}
else
{
trim_ab = 0;
trim_ae = DB_READ_LEN(fctx->db, ovl->aread);
}
if (trim_ab >= trim_ae)
{
free(data);
return 1;
}
// locate missed adapters
int flips_trim_b = trim_ab;
int flips_trim_e = trim_ae;
if (filter_flips(fctx, ovl, novl, &flips_trim_b, &flips_trim_e))
{
fctx->num_flips += 1;
}
trim_ab = MAX(flips_trim_b, trim_ab);
trim_ae = MIN(flips_trim_e, trim_ae);
if (trim_ae - trim_ab < fctx->minlen)
{
printf("skip read %d len %d < min Len %d due to missed adapter\n", ovl->aread, trim_ae - trim_ab, fctx->minlen);
free(data);
return 1;
}
// locate chimers
if (fctx->fixChimers)
{
int chimer_trim_b = trim_ab;
int chimer_trim_e = trim_ae;
if (filter_chimers(fctx, ovl, novl, &chimer_trim_b, &chimer_trim_e))
{
fctx->num_chimers += 1;
}
trim_ab = MAX(chimer_trim_b, trim_ab);
trim_ae = MIN(chimer_trim_e, trim_ae);
if (trim_ae - trim_ab < fctx->minlen)
{
printf("skip read %d len %d < min Len %d due to chimer \n", ovl->aread, trim_ae - trim_ab, fctx->minlen);
free(data);
return 1;
}
}
if (fctx->fileTrimOut)
fprintf(fctx->fileTrimOut, "%d %d %d\n", ovl->aread, trim_ab, trim_ae);
// sanity check tracks
int alen = DB_READ_LEN(fctx->db, ovl->aread);
int nsegments = (alen + fctx->twidth - 1) / twidth;
int ob = qanno[ovl->aread] / sizeof(track_data);
int oe = qanno[ovl->aread + 1] / sizeof(track_data);
if (oe - ob != nsegments)
{
fprintf(stderr, "read %d expected %d Q track entries, found %d\n", ovl->aread, nsegments, oe - ob);
exit(1);
}
if (trim_ab < 0 || trim_ab > alen || trim_ab > trim_ae || trim_ae > alen)
{
fprintf(stderr, "trim interval %d..%d outside read length %d\n", trim_ab, trim_ae, alen);
exit(1);
}
// locate breaks in A and move outwards to the next segment boundary
int i;
Overlap* ocur = ovl + 0;
Overlap* oprev = NULL;
for (i = 1; i < novl; i++)
{
oprev = ocur;
ocur = ovl + i;
if (oprev->bread == ocur->bread && oprev->path.aepos < ocur->path.abpos && (oprev->flags & OVL_COMP) == (ocur->flags & OVL_COMP))
{
if (dcur >= dmax)
{
dmax = dmax * 1.2 + 1000;
data = realloc(data, sizeof(Gap) * dmax);
}
ovl_trace* trace_left = ovl[i - 1].path.trace;
ovl_trace* trace_right = ovl[i].path.trace;
int ab = (ovl[i - 1].path.aepos - 1) / twidth;
int ae = ovl[i].path.abpos / twidth + 1;
int j = ovl[i - 1].path.tlen - 1;
int bb = ovl[i - 1].path.bepos - trace_left[j];
int be = ovl[i].path.bbpos + trace_right[1];
/*
while (qa[ab-1] > lowq)
{
j -= 2;
ab--;
bb -= trace_left[j];
}
j = 1;
while (qa[ae+1] > lowq)
{
j += 2;
ae++;
be += trace_right[j];
}
*/
if (bb >= be)
{
continue;
}
if (ovl[i].flags & OVL_COMP)
{
int t = bb;
int blen = DB_READ_LEN(fctx->db, ovl[i].bread);
bb = blen - be;
be = blen - t;
}
int weak_b = 0;
track_data* qb = qdata + (qanno[ovl[i].bread] / sizeof(track_data));
int beg = bb / twidth;
int end = be / twidth + 1;
int q = 0;
j = beg;
while (j < end)
{
if (qb[j] == 0)
{
weak_b = 1;
}
q += qb[j];
j++;
}
if (weak_b)
{
continue;
}
if (spanners_point(fctx, ovl, novl, ab * twidth, maxspanners) && spanners_point(fctx, ovl, novl, ae * twidth, maxspanners))
{
continue;
}
int q_total = 0;
int q_zero = 0;
for (j = ab + 1; j < ae - 1; j++)
{
q_total += 1;
if (qa[j] == 0)
{
q_zero += 1;
}
}
if (q_total - q_zero > 1) // TODO --- hardcoded
{
continue;
}
if ((ae - ab) * twidth * 10 < (be - bb)) // TODO --- hardcoded
{
continue;
}
#ifdef DEBUG
printf("A %7d %5d..%5d %5d..%5d -> ", ovl->aread, ovl[i - 1].path.abpos, ovl[i - 1].path.aepos, ovl[i].path.abpos, ovl[i].path.aepos);
printf("B %7d %5d..%5d %5d..%5d | ", ovl[i].bread, ovl[i - 1].path.bbpos, ovl[i - 1].path.bepos, ovl[i].path.bbpos, ovl[i].path.bepos);
printf("%d %d %d %d %d %d %d\n", ab, ae, q, beg, end, bb, be);
#endif
// gap due to potential weak region in A
data[dcur].ab = ab * twidth;
data[dcur].ae = ae * twidth;
data[dcur].b = ovl[i].bread;
data[dcur].bb = bb;
data[dcur].be = be;
data[dcur].support = 1;
data[dcur].diff = fctx->twidth * 1.0 * q / (be - bb);
data[dcur].comp = (ovl[i].flags & OVL_COMP);
#ifdef DEBUG
printf("OVL %d..%d -> %d..%d\n", ovl[i - 1].path.abpos, ovl[i - 1].path.aepos, ovl[i].path.abpos, ovl[i].path.aepos);
#endif
dcur++;
}
}
qsort(data, dcur, sizeof(Gap), cmp_gaps);
int j = 0;
// merge breaks located at the same position in A
for (i = 0; i < dcur; i++)
{
if (data[i].support == -1)
{
continue;
}
if (maxgap != -1 && (data[i].ae - data[i].ab >= maxgap || abs(data[i].be - data[i].bb) >= maxgap))
{
data[i].support = -1;
continue;
}
for (j = i + 1; j < dcur && data[i].ab == data[j].ab && data[i].ae == data[j].ae; j++)
{
if (data[j].support == -1)
{
continue;
}
if (abs((data[j].be - data[j].bb) - (data[i].be - data[i].bb)) < 50)
{
data[i].support += 1;
data[j].support = -1;
}
}
}
// merge overlapping breaks
for (i = 0; i < dcur; i++)
{
if (data[i].support == -1)
{
continue;
}
for (j = i + 1; j < dcur && data[i].ae > data[j].ab && data[i].ab < data[j].ae; j++)
{
if (data[j].support == -1)
{
continue;
}
// if ( data[i].ae - data[i].ab > data[j].ae - data[j].ab )
if (data[i].support > data[j].support)
{
data[i].support += data[j].support;
data[j].support = -1;
}
else
{
data[j].support += data[i].support;
data[i].support = -1;
break;
}
}
}
// filter breaks with not enough support (# B reads) or no accompanying Q drop in A
/*
for (j = 0; j < dcur; j++)
{
if ( data[j].support != -1 && spanners_point(ovl, novl, data[j].ab) > maxspanners
&& spanners_point(ovl, novl, data[j].ae) > maxspanners )
{
data[j].support = -1;
}
}
*/
j = 0;
for (i = 0; i < dcur; i++)
{
if (data[i].support < minsupport)
{
continue;
}
int bad_q = 0;
int k;
for (k = data[i].ab / twidth; k < data[i].ae / twidth; k++)
{
if (qa[k] == 0 || qa[k] >= lowq)
{
bad_q = 1;
break;
}
}
if (!bad_q)
{
continue;
}
data[j] = data[i];
j++;
}
dcur = j;
// scan for bad regions ~1k from both ends
int seg_first = trim_ab / twidth;
int seg_last = trim_ae / twidth;
while (qa[seg_first] == 0)
{
seg_first++;
}
while (qa[seg_last - 1] == 0)
{
seg_last--;
}
for (i = seg_first; i < seg_last; i++)
{
// TODO ---------
// if (i == seg_first + BEND_SEGMENTS)
// {
// i = MAX(i, seg_last - BEND_SEGMENTS - 1);
// }
if (qa[i] != 0 && qa[i] < lowq)
{
continue;
}
int ab = i * twidth;
int ae = (i + 1) * twidth;
// already covered by a break interval
int contained = 0;
for (j = 0; j < dcur; j++)
{
if (data[j].support != -1 && data[j].ab <= ab && data[j].ae >= ae)
{
contained = 1;
break;
}
}
if (contained)
{
#ifdef DEBUG
printf("%d @ %d contained\n", i, qa[i]);
#endif
continue;
}
// spanners & reads starting/stopping
int span = 0;
int border = 0;
float q_min = 0;
int ovl_q_min = -1;
int bb_q_min, be_q_min;
for (j = 0; j < novl; j++)
{
// if (ovl[j].flags & OVL_COMP) continue;
if (ovl[j].path.abpos + fctx->twidth <= ab && ovl[j].path.aepos - fctx->twidth >= ae) // TODO --- hardcoded
{
if (dcur >= dmax)
{
dmax = dmax * 1.2 + 1000;
data = realloc(data, sizeof(Gap) * dmax);
}
// locate replacement segment(s) in B
int bb, be;
bb = -1;
be = ovl[j].path.bbpos;
ovl_trace* tracerep = ovl[j].path.trace;
int apos = ovl[j].path.abpos;
int k = 0;
while (apos <= ab)
{
apos = (apos / twidth + 1) * twidth;
bb = be;
be += tracerep[k + 1];
k += 2;
}
assert(bb != -1);
if (ovl[j].flags & OVL_COMP)
{
int t = bb;
int blen = DB_READ_LEN(fctx->db, ovl[j].bread);
bb = blen - be;
be = blen - t;
}
// get Q in B read
track_data* qb = qdata + (qanno[ovl[j].bread] / sizeof(track_data));
int beg = bb / twidth;
int end = be / twidth;
int q = 0;
k = beg;
while (k < end)
{
if (qb[k] == 0)
{
q = 0;
break;
}
q += qb[k];
k++;
}
if (q == 0)
{
continue;
}
// printf("%d..%d %d..%d\n", bb, be, beg, end);
float q_new = 1.0 * q / (end - beg);
if (ovl_q_min == -1 || q_new < q_min)
{
bb_q_min = bb;
be_q_min = be;
q_min = q_new;
ovl_q_min = j;
}
#ifdef DEBUG
printf("%c %8d %5d..%5d %3d..%3d %5.2f\n", ovl_q_min == j ? '*' : ' ', ovl[j].bread, bb, be, beg, end, q_new);
#endif
span++;
}
if ((ovl[j].path.abpos >= ab && ovl[j].path.abpos <= ae) || (ovl[j].path.aepos >= ab && ovl[j].path.aepos <= ae))
{
border++;
}
}
// nothing spans the bad region or nothing starts/stops there
if (ovl_q_min == -1) // || border == 0)
{
continue;
}
// locate replacement segment in B
Overlap* ovlrep = ovl + ovl_q_min;
#ifdef DEBUG
printf("in %d bad Q %d @ %d..%d SPAN %d BORDER %d\n", ovl->aread, qa[i], ab, ae, span, border);
printf(" -> using B %d..%d x %d..%d @ %.2f\n", ovlrep->path.abpos, ovlrep->path.aepos, ovlrep->path.bbpos, ovlrep->path.bepos, q_min);
#endif
data[dcur].bb = bb_q_min;
data[dcur].be = be_q_min;
data[dcur].b = ovlrep->bread;
// data[dcur].span = span;
data[dcur].support = border;
data[dcur].ab = ab;
data[dcur].ae = ae;
data[dcur].diff = q_min;
data[dcur].comp = (ovlrep->flags & OVL_COMP);
dcur++;
}
// no problems in read
if (dcur == 0)
{
Load_Read(fctx->db, ovl->aread, fctx->reada, 1);
if (trim_ae - trim_ab >= fctx->minlen)
{
fprintf(fctx->fileFastaOut, ">trimmed_%d source=%d", ovl->aread, ovl->aread);
for (i = 0; i < fctx->curctracks; i++)
{
track_anno* anno = fctx->convertTracks[i]->anno;
track_data* data = fctx->convertTracks[i]->data;
track_anno ob = anno[ovl->aread] / sizeof(track_data);
track_anno oe = anno[ovl->aread + 1] / sizeof(track_data);
char* track = fctx->convertTracks[i]->name;
int first = 1;
int beg, end;
for (; ob < oe; ob += 2)
{
beg = data[ob] - trim_ab;
end = data[ob + 1] - trim_ab;
// check trim begin
if (end < 0)
{
continue;
}
if (beg < 0)
{
beg = 0;
}
// check trim end
if (beg > trim_ae - trim_ab)
{
break;
}
if (end > trim_ae - trim_ab)
{
end = (trim_ae - trim_ab);
}
if (first)
{
fprintf(fctx->fileFastaOut, " %s=", track);
}
else
{
fprintf(fctx->fileFastaOut, ",");
}
fprintf(fctx->fileFastaOut, "%d,%d", beg, end);
first = 0;
}
}
fprintf(fctx->fileFastaOut, "\n");
wrap_write(fctx->fileFastaOut, fctx->reada + trim_ab, trim_ae - trim_ab, FASTA_WIDTH);
if (fctx->fileQvOut)
{
Load_QVentry(fctx->db, ovl->aread, fctx->qva, 1);
fprintf(fctx->fileQvOut, "@fixed/%d_%d source=%d\n", 0, trim_ae - trim_ab, ovl->aread);
for (i = 0; i < NUM_QV_STREAMS; i++)
{
fprintf(fctx->fileQvOut, "%.*s\n", trim_ae - trim_ab, fctx->qva[i] + trim_ab);
}
}
}
// cleanup
free(data);
return 1;
}
qsort(data, dcur, sizeof(Gap), cmp_gaps);
// count reads that span the break
/*
for (i = 0; i < novl; i++)
{
for (j = 0; j < dcur; j++)
{
if (ovl[i].path.abpos + 100 < data[j].ab && ovl[i].path.aepos - 100 > data[j].ae) // TODO --- hardcoded
{
data[j].span += 1;
}
}
}
*/
// calculate new read length and patch segments
Load_Read(fctx->db, ovl->aread, fctx->reada, 1);
if (fctx->fileQvOut)
{
Load_QVentry(fctx->db, ovl->aread, fctx->qva, 1);
}
char* read = fctx->read_patched;
char** qv = fctx->qv_patched;
int rlen = 0;
int ab = trim_ab;
int ae;
#ifdef DEBUG
printf("A %7d TRIM %5d..%5d\n", ovl->aread, trim_ab, trim_ae);
#endif
int* apatches = fctx->apatches;
int napatches = 0;
for (i = 0; i < dcur; i++)
{
if (trim_ab > data[i].ab)
{
ab = data[i].ae;
continue;
}
if (trim_ae < data[i].ae)
{
// ae = data[i].ae;
break;
}
ae = data[i].ab;
if (trim_ab < ae && trim_ab > ab)
{
ab = trim_ab;
}
// A[ab..ae]
assert(ab <= ae);
if (ab < ae)
{
#ifdef DEBUG
printf("A %7d %5d..%5d\n", ovl->aread, ab, ae);
#endif
apatches[napatches] = ab;
apatches[napatches + 1] = ae;
apatches[napatches + 2] = rlen;
napatches += 3;
if (fctx->fileQvOut)
{
for (j = 0; j < NUM_QV_STREAMS; j++)
{
memcpy(qv[j] + rlen, fctx->qva[j] + ab, ae - ab);
}
}
memcpy(read + rlen, fctx->reada + ab, ae - ab);
rlen += ae - ab;
}
ab = data[i].ae;
// B[bb..be]
fctx->num_gaps += 1;
int bb = data[i].bb;
int be = data[i].be;
fctx->stats_bases_before += data[i].ae - data[i].ab;
fctx->stats_bases_after += data[i].be - data[i].bb;
if (fctx->fileQvOut)
{
Load_QVentry(fctx->db, data[i].b, fctx->qvb, 1);
for (j = 0; j < NUM_QV_STREAMS; j++)
{
if (data[i].comp)
{
rev(fctx->qvb[j] + bb, be - bb);
}
memcpy(qv[j] + rlen, fctx->qvb[j] + bb, be - bb);
}
}
Load_Read(fctx->db, data[i].b, fctx->readb, 1);
if (data[i].comp)
{
revcomp(fctx->readb + bb, be - bb);
}
memcpy(read + rlen, fctx->readb + bb, be - bb);
rlen += be - bb;
#ifdef DEBUG
printf("B %7d %5d..%5d (%6d) @ DIFF %3d SUPPORT %3d", data[i].b, bb, be, be - bb, data[i].diff, data[i].support);
printf(" Q");
for (j = data[i].ab / twidth; j < data[i].ae / twidth; j++)
{
printf(" %2d", qa[j]);
}
printf("\n");
#endif
}
ae = trim_ae;
if (ab < ae)
{
apatches[napatches] = ab;
apatches[napatches + 1] = ae;
apatches[napatches + 2] = rlen;
napatches += 3;
if (fctx->fileQvOut)
{
for (j = 0; j < NUM_QV_STREAMS; j++)
{
memcpy(qv[j] + rlen, fctx->qva[j] + ab, ae - ab);
}
}
memcpy(read + rlen, fctx->reada + ab, ae - ab);
rlen += ae - ab;
#ifdef DEBUG
printf("A %7d %5d..%5d\n", ovl->aread, ab, ae);
#endif
}
#ifdef DEBUG
printf("A %7d RLEN %5d -> %5d\n", ovl->aread, DB_READ_LEN(fctx->db, ovl->aread), rlen);
#endif
// write patched sequence
if (rlen >= fctx->minlen)
{
fprintf(fctx->fileFastaOut, ">fixed_%d source=%d", ovl->aread, ovl->aread);
#ifdef DEBUG_INTERVAL_ADJUSTMENT
printf("\n\n");
for (i = 0; i < napatches; i += 3)
{
printf("A-PATCH %5d..%5d -> %5d\n", apatches[i], apatches[i + 1], apatches[i + 2]);
}
#endif
// for each track
for (i = 0; i < fctx->curctracks; i++)
{
track_anno* anno = fctx->convertTracks[i]->anno;
track_data* data = fctx->convertTracks[i]->data;
track_anno ob = anno[ovl->aread] / sizeof(track_data);
track_anno oe = anno[ovl->aread + 1] / sizeof(track_data);
char* track = fctx->convertTracks[i]->name;
// adjust intervals if present
if (ob < oe)
{
int first = 1;
while (ob < oe)
{
int ib = data[ob];
int ie = data[ob + 1];
int ib_adj = -1;
int ie_adj = -1;
if (ie < apatches[0] || ib > apatches[napatches - 2])
{
#ifdef DEBUG_INTERVAL_ADJUSTMENT
printf("INTRVL %5d..%5d -> OUTSIDE\n", ib, ie);
#endif
ob += 2;
continue;
}
for (j = 0; j < napatches; j += 3)
{
if (ib_adj == -1)
{
if (ib < apatches[j + 1])
{
ib_adj = MAX(ib, apatches[j]);
ib_adj = apatches[j + 2] + (ib_adj - apatches[j]);
}
}
if (ie_adj == -1)
{
if (ie <= apatches[j + 1])
{
if (ie < apatches[j] && j > 0)
{
ie_adj = apatches[j - 2];
ie_adj = apatches[j - 1] + (ie_adj - apatches[j - 3]);
break;
}
else if (ie > apatches[j])
{
ie_adj = ie;
ie_adj = apatches[j + 2] + (ie_adj - apatches[j]);
break;
}
}
}
}
if (ie_adj - ib_adj > MIN_INT_LEN)
{
#ifdef DEBUG_INTERVAL_ADJUSTMENT
printf("INTRVL %5d..%5d -> %5d..%5d\n", ib, ie, ib_adj, ie_adj);
#endif
if (!first)
{
fprintf(fctx->fileFastaOut, ",");
}
else
{
fprintf(fctx->fileFastaOut, " %s=", track);
}
// sanity check
if (ib_adj < 0 || ib_adj > rlen || ib_adj > ie_adj || ie_adj > rlen)
{
fprintf(stderr, "adjust interval %d..%d outside read length %d\n", ib_adj, ie_adj, rlen);
exit(1);
}
fprintf(fctx->fileFastaOut, "%d,%d", ib_adj, ie_adj);
first = 0;
}
else
{
#ifdef DEBUG_INTERVAL_ADJUSTMENT
printf("INTRVL %5d..%5d -> SKIP\n", ib, ie);
#endif
}
ob += 2;
}
}
}
fprintf(fctx->fileFastaOut, "\n");
wrap_write(fctx->fileFastaOut, read, rlen, FASTA_WIDTH);
if (fctx->fileQvOut)
{
fprintf(fctx->fileQvOut, "@fixed/%d_%d source=%d\n", 0, rlen, ovl->aread);
for (j = 0; j < NUM_QV_STREAMS; j++)
{
fprintf(fctx->fileQvOut, "%.*s\n", rlen, qv[j]);
}
}
}
// cleanup
free(data);
return 1;
}
static void usage()
{
printf("usage: [-ladX] [-bCxQgFR <int>] [-ctqr <track>] [-f <patched.quiva>] [-T <file>] <db> <in.las> <patched.fasta>\n");
printf(" -c ... convert track intervals (multiple -c possible)\n");
printf(" -f ... patch quality streams\n");
printf(" -x ... min length for fixed sequences (%d)\n", DEF_ARG_X);
printf(" -Q ... segment quality threshold (%d)\n", DEF_ARG_Q);
printf(" -g ... max gap length for patching (%d)\n", DEF_ARG_G);
printf(" -t ... trim reads based on a track\n");
printf(" -q ... quality track (default: %s)\n", TRACK_Q);
printf(" -l ... low coverage mode\n");
printf("EXPERIMENTAL OPTIONS\n");
printf(" -X ... fix chimeric reads in repeat regions\n");
printf(" -r ... repeat track\n");
printf(" -d ... discard all chimeric reads, (default: 0, i.e. keep longest part of chimeric reads)\n");
printf(" -b ... minimum border coverage to start a chimer detection (default: %d)\n", DEF_ARG_B);
printf(" -C ... maximum chimer length (default: %d)\n", DEF_ARG_C);
printf(" -T ... write trim interval after gap-, cross-, and chimer-detection into a file.\n");
printf(" -F ... allow LAS chain to have a fuzzy begin and end overlap. LAS chains are used to find spanners over putative chimeric break intervals. (default: %d)\n", DEF_ARG_F);
printf(" -R ... Fix chimers only in regions that are at least -R <int repetitive. (default: %d)\n", DEF_ARG_R);
}
int main(int argc, char* argv[])
{
HITS_DB db;
PassContext* pctx;
FixContext fctx;
FILE* fileOvlIn;
bzero(&fctx, sizeof(FixContext));
fctx.db = &db;
fctx.minlen = DEF_ARG_X;
fctx.lowq = DEF_ARG_Q;
fctx.maxgap = DEF_ARG_G;
fctx.trimName = NULL;
fctx.repeatName = NULL;
fctx.qName = TRACK_Q;
fctx.discardChimericReads = 0;
fctx.maxChimerLen = DEF_ARG_C;
fctx.minChimerBorderCov = DEF_ARG_B;
fctx.fuzzyChain = DEF_ARG_F;
fctx.repeatPerc = DEF_ARG_R;
// process arguments
char* pathQvOut = NULL;
char* pathTrimOut = NULL;
int c;
int lowc = 0;
opterr = 0;
while ((c = getopt(argc, argv, "dlXx:f:c:Q:g:t:q:r:b:C:T:F:R:")) != -1)
{
switch (c)
{
case 'l':
lowc = 1;
break;
case 'X':
fctx.fixChimers = 1;
break;
case 'd':
fctx.discardChimericReads = 1;
break;
case 'Q':
fctx.lowq = atoi(optarg);
break;
case 'R':
fctx.repeatPerc = atoi(optarg);
break;
case 'F':
fctx.fuzzyChain = atoi(optarg);
break;
case 'b':
fctx.minChimerBorderCov = atoi(optarg);
break;
case 'C':
fctx.maxChimerLen = atoi(optarg);
break;
case 'g':
fctx.maxgap = atoi(optarg);
break;
case 'x':
fctx.minlen = atoi(optarg);
break;
case 'f':
pathQvOut = optarg;
break;
case 'T':
pathTrimOut = optarg;
break;
case 'q':
fctx.qName = optarg;
break;
case 't':
fctx.trimName = optarg;
break;
case 'r':
fctx.repeatName = optarg;
break;
case 'c':
if (fctx.curctracks >= fctx.maxctracks)
{
fctx.maxctracks += 10;
fctx.convertTracks = realloc(fctx.convertTracks, sizeof(HITS_TRACK*) * fctx.maxctracks);
}
// use the HITS_TRACK* array as temporary storage of the track names
fctx.convertTracks[fctx.curctracks] = (HITS_TRACK*) optarg;
fctx.curctracks++;
break;
default:
usage();
exit(1);
}
}
if (opterr || argc - optind != 3)
{
usage();
exit(1);
}
char* pcPathReadsIn = argv[optind++];
char* pcPathOverlapsIn = argv[optind++];
char* pcPathFastaOut = argv[optind++];
if ((fileOvlIn = fopen(pcPathOverlapsIn, "r")) == NULL)
{
fprintf(stderr, "could not open '%s'\n", pcPathOverlapsIn);
exit(1);
}
if ((fctx.fileFastaOut = fopen(pcPathFastaOut, "w")) == NULL)
{
fprintf(stderr, "could not open '%s'\n", pcPathFastaOut);
exit(1);
}
if (pathQvOut)
{
if ((fctx.fileQvOut = fopen(pathQvOut, "w")) == NULL)
{
fprintf(stderr, "error: could not open '%s'\n", pathQvOut);
exit(1);
}
}
if (pathTrimOut)
{
if ((fctx.fileTrimOut = fopen(pathTrimOut, "w")) == NULL)
{
fprintf(stderr, "error: could not open '%s'\n", pathTrimOut);
exit(1);
}
}
if (Open_DB(pcPathReadsIn, &db))
{
fprintf(stderr, "could not open database '%s'\n", pcPathReadsIn);
exit(1);
}
if (fctx.repeatPerc < 0 || fctx.repeatPerc > 100)
{
fprintf(stderr, "invalid chimer repeat percentage %d. Must be within [0, 100]\n", fctx.repeatPerc);
exit(1);
}
int i;
for (i = 0; i < fctx.curctracks; i++)
{
char* track = (char*) fctx.convertTracks[i];
fctx.convertTracks[i] = track_load(&db, track);
if (fctx.convertTracks[i] == NULL)
{
fprintf(stderr, "could not open track '%s'\n", track);
exit(1);
}
}
if (lowc)
{
fctx.maxspanners = 3;
fctx.minsupport = 2;
}
else
{
fctx.maxspanners = 7; // 10
fctx.minsupport = 4; // 5
}
// pass
if (fctx.fileQvOut)
{
if (Load_QVs(&db) != 0)
{
fprintf(stderr, "error: failed to load QVs\n");
exit(1);
}
}
pctx = pass_init(fileOvlIn, NULL);
pctx->split_b = 0;
pctx->load_trace = 1;
pctx->unpack_trace = 1;
pctx->data = &fctx;
fix_pre(pctx, &fctx);
pass(pctx, fix_process);
fix_post(pctx, &fctx);
pass_free(pctx);
// cleanup
if (fctx.fileQvOut)
{
Close_QVs(&db);
fclose(fctx.fileQvOut);
}
if (fctx.fileTrimOut)
fclose(fctx.fileTrimOut);
Close_DB(&db);
fclose(fileOvlIn);
fclose(fctx.fileFastaOut);
if (fctx.curctracks)
free(fctx.convertTracks);
return 0;
}
|
MartinPippel/DAmar
|
db/DB.c
|
<reponame>MartinPippel/DAmar
/************************************************************************************\
* *
* Copyright (c) 2014, Dr. <NAME> (EWM). 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. *
* *
* · The name of EWM may not be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY EWM ”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 EWM 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. *
* *
* For any issues regarding this software and its use, contact EWM at: *
* *
* <NAME>r. *
* Bautzner Str. 122e *
* 01099 Dresden *
* GERMANY *
* Email: <EMAIL> *
* *
\************************************************************************************/
/*******************************************************************************************
*
* Compressed data base module. Auxiliary routines to open and manipulate a data base for
* which the sequence and read information are separated into two separate files, and the
* sequence is compressed into 2-bits for each base. Support for tracks of additional
* information, and trimming according to the current partition. Eventually will also
* support compressed quality information.
*
* Author : <NAME>
* Date : July 2013
* Revised: April 2014
*
********************************************************************************************/
#include <ctype.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/param.h>
#include "DB.h"
#ifdef HIDE_FILES
#define PATHSEP "/."
#else
#define PATHSEP "/"
#endif
/*******************************************************************************************
*
* GENERAL UTILITIES
*
********************************************************************************************/
char* Prog_Name;
#ifdef INTERACTIVE
char Ebuffer[ 1000 ];
#endif
int Count_Args(char *var)
{
int cnt, lev;
char *s;
cnt = 1;
lev = 0;
for (s = var; *s != '\0'; s++)
if (*s == ',')
{
if (lev == 0)
cnt += 1;
}
else if (*s == '(')
lev += 1;
else if (*s == ')')
lev -= 1;
return (cnt);
}
void *Malloc(int64 size, char *mesg)
{
void *p;
if ((p = malloc(size)) == NULL)
{
if (mesg == NULL)
EPRINTF(EPLACE, "%s: Out of memory (size: %lld)\n", Prog_Name, size);
else
EPRINTF(EPLACE, "%s: Out of memory (size: %lld) (%s)\n", Prog_Name, size, mesg);
}
return (p);
}
void *Realloc(void *p, int64 size, char *mesg)
{
if (size <= 0)
size = 1;
if ((p = realloc(p, size)) == NULL)
{
if (mesg == NULL)
EPRINTF(EPLACE, "%s: Out of memory (size: %lld)\n", Prog_Name, size);
else
EPRINTF(EPLACE, "%s: Out of memory (size: %lld) (%s)\n", Prog_Name, size, mesg);
}
return (p);
}
char *Strdup(char *name, char *mesg)
{
char *s;
if (name == NULL)
return (NULL);
if ((s = strdup(name)) == NULL)
{
if (mesg == NULL)
EPRINTF(EPLACE, "%s: Out of memory\n", Prog_Name);
else
EPRINTF(EPLACE, "%s: Out of memory (%s)\n", Prog_Name, mesg);
}
return (s);
}
FILE *Fopen(char *name, char *mode)
{
FILE *f;
if (name == NULL || mode == NULL)
return (NULL);
if ((f = fopen(name, mode)) == NULL)
EPRINTF(EPLACE, "%s: Cannot open %s for '%s'\n", Prog_Name, name, mode);
return (f);
}
char *PathTo(char *name)
{
char *path, *find;
if (name == NULL)
return (NULL);
if ((find = rindex(name, '/')) != NULL)
{
*find = '\0';
path = Strdup(name, "Extracting path from");
*find = '/';
}
else
path = Strdup(".", "Allocating default path");
return (path);
}
char *Root(char *name, char *suffix)
{
char *path, *find, *dot;
int epos;
if (name == NULL)
return (NULL);
find = rindex(name, '/');
if (find == NULL)
find = name;
else
find += 1;
if (suffix == NULL)
{
dot = strchr(find, '.');
if (dot != NULL)
*dot = '\0';
path = Strdup(find, "Extracting root from");
if (dot != NULL)
*dot = '.';
}
else
{
epos = strlen(find);
epos -= strlen(suffix);
if (epos > 0 && strcasecmp(find + epos, suffix) == 0)
{
find[epos] = '\0';
path = Strdup(find, "Extracting root from");
find[epos] = suffix[0];
}
else
path = Strdup(find, "Allocating root");
}
return (path);
}
char *Catenate(char *path, char *sep, char *root, char *suffix)
{
static char *cat = NULL;
static int max = -1;
int len;
if (path == NULL || root == NULL || sep == NULL || suffix == NULL)
return (NULL);
len = strlen(path);
len += strlen(sep);
len += strlen(root);
len += strlen(suffix);
if (len > max)
{
max = ((int) (1.2 * len)) + 100;
if ((cat = (char *) realloc(cat, max + 1)) == NULL)
{
EPRINTF(EPLACE, "%s: Out of memory (Making path name for %s)\n", Prog_Name, root);
return (NULL);
}
}
sprintf(cat, "%s%s%s%s", path, sep, root, suffix);
return (cat);
}
char *Numbered_Suffix(char *left, int num, char *right)
{
static char *suffix = NULL;
static int max = -1;
int len;
if (left == NULL || right == NULL)
return (NULL);
len = strlen(left);
len += strlen(right) + 40;
if (len > max)
{
max = ((int) (1.2 * len)) + 100;
if ((suffix = (char *) realloc(suffix, max + 1)) == NULL)
{
EPRINTF(EPLACE, "%s: Out of memory (Making number suffix for %d)\n", Prog_Name, num);
return (NULL);
}
}
sprintf(suffix, "%s%d%s", left, num, right);
return (suffix);
}
#define COMMA ','
// Print big integers with commas/periods for better readability
void Print_Number(int64 num, int width, FILE* out)
{
if (width == 0)
{
if (num < 1000ll)
fprintf(out, "%lld", num);
else if (num < 1000000ll)
fprintf(out, "%lld%c%03lld", num / 1000ll, COMMA, num % 1000ll);
else if (num < 1000000000ll)
fprintf(out, "%lld%c%03lld%c%03lld", num / 1000000ll,
COMMA, (num % 1000000ll) / 1000ll, COMMA, num % 1000ll);
else
fprintf(out, "%lld%c%03lld%c%03lld%c%03lld", num / 1000000000ll,
COMMA, (num % 1000000000ll) / 1000000ll,
COMMA, (num % 1000000ll) / 1000ll, COMMA, num % 1000ll);
}
else
{
if (num < 1000ll)
fprintf(out, "%*lld", width, num);
else if (num < 1000000ll)
{
if (width <= 4)
fprintf(out, "%lld%c%03lld", num / 1000ll, COMMA, num % 1000ll);
else
fprintf(out, "%*lld%c%03lld", width - 4, num / 1000ll, COMMA, num % 1000ll);
}
else if (num < 1000000000ll)
{
if (width <= 8)
fprintf(out, "%lld%c%03lld%c%03lld", num / 1000000ll, COMMA, (num % 1000000ll) / 1000ll,
COMMA, num % 1000ll);
else
fprintf(out, "%*lld%c%03lld%c%03lld", width - 8, num / 1000000ll, COMMA, (num % 1000000ll) / 1000ll,
COMMA, num % 1000ll);
}
else
{
if (width <= 12)
fprintf(out, "%lld%c%03lld%c%03lld%c%03lld", num / 1000000000ll, COMMA, (num % 1000000000ll) / 1000000ll, COMMA, (num % 1000000ll) / 1000ll,
COMMA, num % 1000ll);
else
fprintf(out, "%*lld%c%03lld%c%03lld%c%03lld", width - 12, num / 1000000000ll, COMMA, (num % 1000000000ll) / 1000000ll, COMMA,
(num % 1000000ll) / 1000ll, COMMA, num % 1000ll);
}
}
}
// Return the number of digits, base 10, of num
int Number_Digits(int64 num)
{
int digit;
digit = 0;
while (num >= 1)
{
num /= 10;
digit += 1;
}
return (digit);
}
/*******************************************************************************************
*
* READ COMPRESSION/DECOMPRESSION UTILITIES
*
********************************************************************************************/
// Compress read into 2-bits per base (from [0-3] per byte representation
void Compress_Read(int len, char* s)
{
int i;
char c, d;
char *s0, *s1, *s2, *s3;
s0 = s;
s1 = s0 + 1;
s2 = s1 + 1;
s3 = s2 + 1;
c = s1[len];
d = s2[len];
s0[len] = s1[len] = s2[len] = 0;
for (i = 0; i < len; i += 4)
*s++ = (char) ((s0[i] << 6) | (s1[i] << 4) | (s2[i] << 2) | s3[i]);
s1[len] = c;
s2[len] = d;
}
// Uncompress read form 2-bits per base into [0-3] per byte representation
void Uncompress_Read(int len, char* s)
{
int i, tlen, byte;
char *s0, *s1, *s2, *s3;
char* t;
s0 = s;
s1 = s0 + 1;
s2 = s1 + 1;
s3 = s2 + 1;
tlen = (len - 1) / 4;
t = s + tlen;
for (i = tlen * 4; i >= 0; i -= 4)
{
byte = *t--;
s0[i] = (char) ((byte >> 6) & 0x3);
s1[i] = (char) ((byte >> 4) & 0x3);
s2[i] = (char) ((byte >> 2) & 0x3);
s3[i] = (char) (byte & 0x3);
}
s[len] = 4;
}
// Convert read in [0-3] representation to ascii representation (end with '\n')
void Lower_Read(char* s)
{
static char letter[4] =
{ 'a', 'c', 'g', 't' };
for (; *s != 4; s++)
*s = letter[(int) *s];
*s = '\0';
}
void Upper_Read(char* s)
{
static char letter[4] =
{ 'A', 'C', 'G', 'T' };
for (; *s != 4; s++)
*s = letter[(int) *s];
*s = '\0';
}
// Convert read in ascii representation to [0-3] representation (end with 4)
void Number_Read(char* s)
{
static char number[128] =
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
for (; *s != '\0'; s++)
*s = number[(int) *s];
*s = 4;
}
void Number_Arrow(char *s)
{ static char arrow[128] =
{ 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3,
3, 0, 1, 2, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 2,
3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3,
};
for ( ; *s != '\0'; s++)
*s = arrow[(int) *s];
*s = 4;
}
/*******************************************************************************************
*
* DB OPEN, TRIM & CLOSE ROUTINES
*
********************************************************************************************/
// Open the given database or dam, "path" into the supplied HITS_DB record "db". If the name has
// a part # in it then just the part is opened. The index array is allocated (for all or
// just the part) and read in.
// Return status of routine:
// -1: The DB could not be opened for a reason reported by the routine to EPLACE
// 0: Open of DB proceeded without mishap
// 1: Open of DAM proceeded without mishap
int Open_DB(char* path, HITS_DB* db)
{
return Open_DB_Block(path, db, -1);
}
int Open_DB_Block(char* path, HITS_DB* db, int part)
{
HITS_DB dbcopy;
char *root, *pwd, *bptr, *fptr, *cat;
int nreads;
FILE *index, *dbvis;
int status, plen, isdam;
int ufirst, ulast;
status = -1;
dbcopy = *db;
plen = strlen(path);
if (strcmp(path + (plen - 4), ".dam") == 0)
root = Root(path, ".dam");
else
root = Root(path, ".db");
pwd = PathTo(path);
bptr = rindex(root, '.');
if (part == -1)
{
if (bptr != NULL && bptr[1] != '\0' && bptr[1] != '-')
{
part = strtol(bptr + 1, &fptr, 10);
if (*fptr != '\0' || part == 0)
part = 0;
else
*bptr = '\0';
}
else
part = 0;
}
else
{
if (bptr != NULL && bptr[1] != '\0' && bptr[1] != '-')
{
*bptr = '\0';
}
}
isdam = 0;
cat = Catenate(pwd, "/", root, ".db");
if (cat == NULL)
return (-1);
if ((dbvis = fopen(cat, "r")) == NULL)
{
cat = Catenate(pwd, "/", root, ".dam");
if (cat == NULL)
return (-1);
if ((dbvis = fopen(cat, "r")) == NULL)
{
EPRINTF( EPLACE, "%s: Could not open database %s\n", Prog_Name, path);
goto error;
}
isdam = 1;
}
if ((index = Fopen(Catenate(pwd, PATHSEP, root, ".idx"), "r")) == NULL)
goto error1;
if (fread(db, sizeof(HITS_DB), 1, index) != 1)
{
EPRINTF( EPLACE, "%s: Index file (.idx) of %s is junk\n", Prog_Name, root);
goto error2;
}
// sanity check, freq must add up to 1
float sum = db->freq[0] + db->freq[1] + db->freq[2] + db->freq[3];
if (sum < 0.99 || sum > 1.01)
{
EPRINTF( EPLACE, "%s: Index file frequencies sum to %.2f. File corrupt.\n", Prog_Name, sum);
goto error2;
}
// sanity check, make sure filesize and HITS_READ record count match
struct stat st;
stat(Catenate(pwd, PATHSEP, root, ".idx"), &st);
if ((unsigned int) db->ureads != (st.st_size - sizeof(HITS_DB)) / sizeof(HITS_READ))
{
EPRINTF( EPLACE, "%s: Index file size and record count mismatch %u expected %zu present\n", Prog_Name, db->ureads,
(size_t) (st.st_size - sizeof(HITS_DB)) / sizeof(HITS_READ));
goto error2;
}
{
int p, nblocks, nfiles;
int64 size;
char fname[MAX_NAME], prolog[MAX_NAME];
nblocks = 0;
if (fscanf(dbvis, DB_NFILE, &nfiles) != 1)
{
EPRINTF( EPLACE, "%s: Stub file (.db) of %s is junk\n", Prog_Name, root);
goto error2;
}
for (p = 0; p < nfiles; p++)
if (fscanf(dbvis, DB_FDATA, &ulast, fname, prolog) != 3)
{
EPRINTF( EPLACE, "%s: Stub file (.db) of %s is junk\n", Prog_Name, root);
goto error2;
}
if (fscanf(dbvis, DB_NBLOCK, &nblocks) != 1)
{
if (part != 0)
{
EPRINTF( EPLACE, "%s: DB %s has not yet been partitioned, cannot request a block !\n", Prog_Name, root);
goto error2;
}
}
else
{
if (fscanf(dbvis, DB_PARAMS, &size) != 1)
{
EPRINTF( EPLACE, "%s: Stub file (.db) of %s is junk\n", Prog_Name, root);
goto error2;
}
if (part > nblocks)
{
EPRINTF( EPLACE, "%s: DB %s has only %d blocks\n", Prog_Name, root, nblocks);
goto error2;
}
}
if (part > 0)
{
for (p = 1; p <= part; p++)
if (fscanf(dbvis, DB_BDATA, &ufirst) != 1)
{
EPRINTF( EPLACE, "%s: Stub file (.db) of %s is junk\n", Prog_Name, root);
goto error2;
}
if (fscanf(dbvis, DB_BDATA, &ulast) != 1)
{
EPRINTF( EPLACE, "%s: Stub file (.db) of %s is junk\n", Prog_Name, root);
goto error2;
}
}
else
{
ufirst = 0;
ulast = db->ureads;
}
}
db->tracks = NULL;
db->part = part;
db->ufirst = ufirst;
nreads = ulast - ufirst;
if (part <= 0)
{
db->reads = (HITS_READ*) Malloc(sizeof(HITS_READ) * (nreads + 2), "Allocating Open_DB index");
db->reads += 1;
if (fread(db->reads, sizeof(HITS_READ), nreads, index) != (size_t) nreads)
{
EPRINTF( EPLACE, "%s: Index file (.idx) of %s is junk\n", Prog_Name, root);
free(db->reads);
goto error2;
}
}
else
{
HITS_READ* reads;
int i, r, maxlen;
int64 totlen;
reads = (HITS_READ*) Malloc(sizeof(HITS_READ) * (nreads + 2), "Allocating Open_DB index");
reads += 1;
fseeko(index, sizeof(HITS_READ) * ufirst, SEEK_CUR);
if (fread(reads, sizeof(HITS_READ), nreads, index) != (size_t) nreads)
{
EPRINTF( EPLACE, "%s: Index file (.idx) of %s is junk\n", Prog_Name, root);
free(reads);
goto error2;
}
totlen = 0;
maxlen = 0;
for (i = 0; i < nreads; i++)
{
r = reads[i].rlen;
totlen += r;
if (r > maxlen)
maxlen = r;
}
db->maxlen = maxlen;
db->totlen = totlen;
db->reads = reads;
}
((int*) (db->reads))[-1] = ulast - ufirst; // Kludge, need these for DB part
db->nreads = nreads;
db->path = Strdup(Catenate(pwd, PATHSEP, root, ""), "Allocating Open_DB path");
if (db->path == NULL)
goto error2;
db->bases = NULL;
db->loaded = 0;
status = isdam;
error2: fclose(index);
error1: fclose(dbvis);
error: if (bptr != NULL)
*bptr = '.';
free(pwd);
free(root);
if (status < 0)
*db = dbcopy;
return (status);
}
// Shut down an open 'db' by freeing all associated space, including tracks and QV structures,
// and any open file pointers. The record pointed at by db however remains (the user
// supplied it and so should free it).
void Close_DB(HITS_DB* db)
{
HITS_TRACK *t, *p;
if (db->loaded)
{
free(((char*) (db->bases)) - 1);
db->bases = NULL;
}
else if (db->bases != NULL)
{
fclose((FILE*) db->bases);
db->bases = NULL;
}
if (db->reads != NULL)
{
free(db->reads - 1);
db->reads = NULL;
}
free(db->path);
db->path = NULL;
Close_QVs(db);
for (t = db->tracks; t != NULL; t = p)
{
p = t->next;
free(t->anno);
free(t->data);
free(t->name);
free(t);
}
db->tracks = NULL;
}
// Return the size in bytes of the memory occupied by a given DB
int64 sizeof_DB(HITS_DB *db)
{ int64 s;
HITS_TRACK *t;
s = sizeof(HITS_DB)
+ sizeof(HITS_READ)*(db->nreads+2)
+ strlen(db->path)+1
+ (db->totlen+db->nreads+4);
t = db->tracks;
if (t != NULL && strcmp(t->name,".@qvs") == 0)
{ HITS_QV *q = (HITS_QV *) t;
s += sizeof(HITS_QV)
+ sizeof(uint16) * db->nreads
+ q->ncodes * sizeof(QVcoding)
+ 6;
t = t->next;
}
for (; t != NULL; t = t->next)
{ s += sizeof(HITS_TRACK)
+ strlen(t->name)+1
+ t->size * (db->nreads+1);
if (t->data != NULL)
{ if (t->size == 8)
s += sizeof(int)*((int64 *) t->anno)[db->nreads];
else // t->size == 4
s += sizeof(int)*((int *) t->anno)[db->nreads];
}
}
return (s);
}
/*******************************************************************************************
*
* QV LOAD & CLOSE ROUTINES
*
********************************************************************************************/
HITS_DB* Active_DB = NULL; // Last db/qv used by "Load_QVentry"
HITS_QV* Active_QV; // Becomes invalid after closing
int Load_QVs(HITS_DB* db)
{
FILE *quiva, *istub, *indx;
char* root;
uint16* table;
HITS_QV* qvtrk;
QVcoding *coding, *nx;
int ncodes;
if (db->tracks != NULL && strcmp(db->tracks->name, ".@qvs") == 0)
return (0);
if (db->reads[db->nreads - 1].coff < 0)
{
EPRINTF( EPLACE, "%s: The requested QVs have not been added to the DB!\n", Prog_Name);
EXIT(1);
}
// Open .qvs, .idx, and .db files
quiva = Fopen(Catenate(db->path, "", "", ".qvs"), "r");
if (quiva == NULL)
return (-1);
istub = NULL;
indx = NULL;
table = NULL;
coding = NULL;
qvtrk = NULL;
root = rindex(db->path, '/') + 2;
istub = Fopen(Catenate(PathTo(db->path), "/", root, ".db"), "r");
if (istub == NULL)
goto error;
{
int first, last, nfiles;
char prolog[MAX_NAME], fname[MAX_NAME];
int i, j;
if (fscanf(istub, DB_NFILE, &nfiles) != 1)
{
EPRINTF( EPLACE, "%s: Stub file (.db) of %s is junk\n", Prog_Name, root);
goto error;
}
if (db->part > 0)
{
int pfirst, plast;
int fbeg, fend;
int n, k;
FILE* indx;
// Determine first how many and which files span the block (fbeg to fend)
pfirst = db->ufirst;
plast = pfirst + db->nreads;
first = 0;
for (fbeg = 0; fbeg < nfiles; fbeg++)
{
if (fscanf(istub, DB_FDATA, &last, fname, prolog) != 3)
{
EPRINTF( EPLACE, "%s: Stub file (.db) of %s is junk\n", Prog_Name, root);
goto error;
}
if (last > pfirst)
break;
first = last;
}
for (fend = fbeg + 1; fend <= nfiles; fend++)
{
if (last >= plast)
break;
if (fscanf(istub, DB_FDATA, &last, fname, prolog) != 3)
{
EPRINTF( EPLACE, "%s: Stub file (.db) of %s is junk\n", Prog_Name, root);
goto error;
}
first = last;
}
indx = Fopen(Catenate(db->path, "", "", ".idx"), "r");
ncodes = fend - fbeg;
coding = (QVcoding*) Malloc(sizeof(QVcoding) * ncodes, "Allocating coding schemes");
table = (uint16*) Malloc(sizeof(uint16) * db->nreads, "Allocating QV table indices");
if (indx == NULL || coding == NULL || table == NULL)
{
ncodes = 0;
goto error;
}
// Carefully get the first coding scheme (its offset is most likely in a HITS_RECORD
// in .idx that is *not* in memory). Get all the other coding schemes normally and
// assign the tables # for each read in the block in "tables".
rewind(istub);
if (fscanf(istub, DB_NFILE, &nfiles) != DB_NFILE_FIELDS)
{
EPRINTF( EPLACE, "%s: Index file (.idx) of %s is junk\n", Prog_Name, root);
ncodes = 0;
goto error;
}
first = 0;
for (n = 0; n < fbeg; n++)
{
if (fscanf(istub, DB_FDATA, &last, fname, prolog) != DB_FDATA_FIELDS)
{
EPRINTF( EPLACE, "%s: Index file (.idx) of %s is junk\n", Prog_Name, root);
ncodes = 0;
goto error;
}
first = last;
}
for (n = fbeg; n < fend; n++)
{
if (fscanf(istub, DB_FDATA, &last, fname, prolog) != DB_FDATA_FIELDS)
{
EPRINTF( EPLACE, "%s: Index file (.idx) of %s is junk\n", Prog_Name, root);
ncodes = 0;
goto error;
}
i = n - fbeg;
if (first < pfirst)
{
HITS_READ read;
fseeko(indx, sizeof(HITS_DB) + sizeof(HITS_READ) * first, SEEK_SET);
if (fread(&read, sizeof(HITS_READ), 1, indx) != 1)
{
EPRINTF( EPLACE, "%s: Index file (.idx) of %s is junk\n", Prog_Name, root);
ncodes = i;
goto error;
}
fseeko(quiva, read.coff, SEEK_SET);
nx = Read_QVcoding(quiva);
if (nx == NULL)
{
ncodes = i;
goto error;
}
coding[i] = *nx;
}
else
{
fseeko(quiva, db->reads[first - pfirst].coff, SEEK_SET);
nx = Read_QVcoding(quiva);
if (nx == NULL)
{
ncodes = i;
goto error;
}
coding[i] = *nx;
db->reads[first - pfirst].coff = ftello(quiva);
}
j = first - pfirst;
if (j < 0)
j = 0;
k = last - pfirst;
if (k > db->nreads)
k = db->nreads;
while (j < k)
table[j++] = (uint16) i;
first = last;
}
fclose(indx);
indx = NULL;
}
else
{ // Load in coding scheme for each file, adjust .coff of first read in the file, and
// record which table each read uses
ncodes = nfiles;
coding = (QVcoding*) Malloc(sizeof(QVcoding) * nfiles, "Allocating coding schemes");
table = (uint16*) Malloc(sizeof(uint16) * db->nreads, "Allocating QV table indices");
if (coding == NULL || table == NULL)
goto error;
first = 0;
for (i = 0; i < nfiles; i++)
{
if (fscanf(istub, DB_FDATA, &last, fname, prolog) != 3)
{
EPRINTF( EPLACE, "%s: Stub file (.db) of %s is junk\n", Prog_Name, root);
goto error;
}
fseeko(quiva, db->reads[first].coff, SEEK_SET);
nx = Read_QVcoding(quiva);
if (nx == NULL)
{
ncodes = i;
goto error;
}
coding[i] = *nx;
db->reads[first].coff = ftello(quiva);
for (j = first; j < last; j++)
table[j] = (uint16) i;
first = last;
}
}
// Allocate and fill in the HITS_QV record and add it to the front of the
// track list
qvtrk = (HITS_QV*) Malloc(sizeof(HITS_QV), "Allocating QV pseudo-track");
if (qvtrk == NULL)
goto error;
qvtrk->name = Strdup(".@qvs", "Allocating QV pseudo-track name");
if (qvtrk->name == NULL)
goto error;
qvtrk->next = db->tracks;
db->tracks = (HITS_TRACK*) qvtrk;
qvtrk->ncodes = ncodes;
qvtrk->table = table;
qvtrk->coding = coding;
qvtrk->quiva = quiva;
}
fclose(istub);
return (0);
error: if (qvtrk != NULL)
free(qvtrk);
if (table != NULL)
free(table);
if (coding != NULL)
{
int i;
for (i = 0; i < ncodes; i++)
Free_QVcoding(coding + i);
free(coding);
}
if (indx != NULL)
fclose(indx);
if (istub != NULL)
fclose(istub);
fclose(quiva);
EXIT(1);
}
// Close the QV stream, free the QV pseudo track and all associated memory
void Close_QVs(HITS_DB* db)
{
HITS_TRACK* track;
HITS_QV* qvtrk;
int i;
Active_DB = NULL;
track = db->tracks;
if (track != NULL && strcmp(track->name, ".@qvs") == 0)
{
qvtrk = (HITS_QV*) track;
for (i = 0; i < qvtrk->ncodes; i++)
Free_QVcoding(qvtrk->coding + i);
free(qvtrk->coding);
free(qvtrk->table);
fclose(qvtrk->quiva);
db->tracks = track->next;
free(track);
}
return;
}
/*******************************************************************************************
*
* TRACK LOAD & CLOSE ROUTINES
*
********************************************************************************************/
// Return status of track:
// 0: Track is for DB
// -1: Track is not the right size of DB
// -2: Could not find the track
int Check_Track(HITS_DB* db, char* track)
{
FILE* afile;
int tracklen, size, ispart;
int ureads;
int newTrack = 0;
afile = NULL;
if (db->part > 0)
{
afile = fopen(Catenate(db->path, Numbered_Suffix(".", db->part, "."), track, ".anno"), "r");
ispart = 1;
}
if (afile == NULL)
{
afile = fopen(Catenate(db->path, Numbered_Suffix(".", db->part, "."), track, ".a2"), "r");
ispart = 1;
newTrack = 1;
}
if (afile == NULL)
{
afile = fopen(Catenate(db->path, ".", track, ".anno"), "r");
ispart = 0;
}
if (afile == NULL)
{
afile = fopen(Catenate(db->path, ".", track, ".a2"), "r");
ispart = 0;
newTrack = 1;
}
if (afile == NULL)
return (-2);
if (fread(&tracklen, sizeof(int), 1, afile) != 1)
return (-1);
if (fread(&size, sizeof(int), 1, afile) != 1)
return (-1);
fclose(afile);
if (ispart && !newTrack)
ureads = ((int*) (db->reads))[-1];
else
ureads = db->ureads;
if (tracklen == ureads)
return (0);
else
return (-1);
}
// If track is not already in the db's track list, then allocate all the storage for it,
// read it in from the appropriate file, add it to the track list, and return a pointer
// to the newly created HITS_TRACK record. If the track does not exist or cannot be
// opened for some reason, then NULL is returned.
HITS_TRACK* Load_Track(HITS_DB* db, char* track)
{
FILE *afile, *dfile;
int tracklen, size;
int nreads, ispart;
int ureads;
void* anno;
void* data;
char* name;
HITS_TRACK* record;
if (track[0] == '.')
{
EPRINTF( EPLACE, "%s: Track name, '%s', cannot begin with a .\n", Prog_Name, track);
EXIT(NULL);
}
for (record = db->tracks; record != NULL; record = record->next)
if (strcmp(record->name, track) == 0)
return (record);
afile = NULL;
if (db->part)
{
afile = fopen(Catenate(db->path, Numbered_Suffix(".", db->part, "."), track, ".anno"), "r");
ispart = 1;
}
if (afile == NULL)
{
afile = fopen(Catenate(db->path, ".", track, ".anno"), "r");
ispart = 0;
}
if (afile == NULL)
{
EPRINTF( EPLACE, "%s: Track '%s' does not exist\n", Prog_Name, track);
return ( NULL);
}
dfile = NULL;
anno = NULL;
data = NULL;
record = NULL;
if (ispart)
name = Catenate(db->path, Numbered_Suffix(".", db->part, "."), track, ".data");
else
name = Catenate(db->path, ".", track, ".data");
if (name == NULL)
goto error;
dfile = fopen(name, "r");
if (fread(&tracklen, sizeof(int), 1, afile) != 1)
{
EPRINTF( EPLACE, "%s: Track '%s' annotation file is junk\n", Prog_Name, track);
goto error;
}
if (fread(&size, sizeof(int), 1, afile) != 1)
{
EPRINTF( EPLACE, "%s: Track '%s' annotation file is junk\n", Prog_Name, track);
goto error;
}
if (size <= 0)
{
EPRINTF( EPLACE, "%s: Track '%s' annotation file is junk\n", Prog_Name, track);
goto error;
}
if (ispart)
ureads = ((int*) (db->reads))[-1];
else
ureads = db->ureads;
if (tracklen != ureads)
{
EPRINTF( EPLACE, "%s: Track '%s' not same size as database (track: %d, db: %d)!\n", Prog_Name, track, tracklen, ureads);
goto error;
}
if (!ispart && db->part > 0)
fseeko(afile, size * db->ufirst, SEEK_CUR);
nreads = db->nreads;
anno = (void*) Malloc(size * (nreads + 1), "Allocating Track Anno Vector");
if (anno == NULL)
goto error;
if (dfile != NULL)
{
int64 *anno8, off8, dlen;
int *anno4, off4;
int i;
if (fread(anno, size, nreads + 1, afile) != (size_t) (nreads + 1))
{
EPRINTF( EPLACE, "%s: Track '%s' annotation file is junk\n", Prog_Name, track);
goto error;
}
if (size == 4)
{
anno4 = (int*) anno;
off4 = anno4[0];
if (off4 != 0)
{
for (i = 0; i <= nreads; i++)
anno4[i] -= off4;
fseeko(dfile, off4, SEEK_SET);
}
dlen = anno4[nreads];
data = (void*) Malloc(dlen, "Allocating Track Data Vector");
}
else
{
anno8 = (int64*) anno;
off8 = anno8[0];
if (off8 != 0)
{
for (i = 0; i <= nreads; i++)
anno8[i] -= off8;
fseeko(dfile, off8, SEEK_SET);
}
dlen = anno8[nreads];
data = (void*) Malloc(dlen, "Allocating Track Data Vector");
}
if (data == NULL)
goto error;
if (dlen > 0)
{
if (fread(data, dlen, 1, dfile) != 1)
{
EPRINTF( EPLACE, "%s: Track '%s' data file size mismatch. Expected %lld\n", Prog_Name, track, dlen);
goto error;
}
}
fclose(dfile);
dfile = NULL;
}
else
{
if (fread(anno, size, nreads, afile) != (size_t) nreads)
{
EPRINTF( EPLACE, "%s: Track '%s' annotation file is junk\n", Prog_Name, track);
goto error;
}
data = NULL;
}
fclose(afile);
record = (HITS_TRACK*) Malloc(sizeof(HITS_TRACK), "Allocating Track Record");
if (record == NULL)
goto error;
record->name = Strdup(track, "Allocating Track Name");
if (record->name == NULL)
goto error;
record->data = data;
record->anno = anno;
record->size = size;
if (db->tracks != NULL && strcmp(db->tracks->name, ".@qvs") == 0)
{
record->next = db->tracks->next;
db->tracks->next = record;
}
else
{
record->next = db->tracks;
db->tracks = record;
}
return (record);
error: if (record == NULL)
free(record);
if (data != NULL)
free(data);
if (anno != NULL)
free(anno);
if (dfile != NULL)
fclose(dfile);
fclose(afile);
EXIT(NULL);
}
void Close_Track(HITS_DB* db, char* track)
{
HITS_TRACK *record, *prev;
prev = NULL;
for (record = db->tracks; record != NULL; record = record->next)
{
if (strcmp(record->name, track) == 0)
{
free(record->anno);
free(record->data);
free(record->name);
if (prev == NULL)
db->tracks = record->next;
else
prev->next = record->next;
free(record);
return;
}
prev = record;
}
return;
}
/*******************************************************************************************
*
* READ BUFFER ALLOCATION AND READ ACCESS
*
********************************************************************************************/
// Allocate and return a buffer big enough for the largest read in 'db', leaving room
// for an initial delimiter character
char* New_Read_Buffer(HITS_DB* db)
{
char* read;
read = (char*) Malloc(db->maxlen + 4, "Allocating New Read Buffer");
if (read == NULL)
EXIT(NULL);
return (read + 1);
}
// Load into 'read' the i'th read in 'db'. As an upper case ASCII string if ascii is 2, as a
// lower-case ASCII string is ascii is 1, and as a numeric string over 0(A), 1(C), 2(G), and
// 3(T) otherwise.
//
// **NB**, the byte before read will be set to a delimiter character!
int Load_Read(HITS_DB* db, int i, char* read, int ascii)
{
FILE* bases = (FILE*) db->bases;
int64 off;
int len, clen;
HITS_READ* r = db->reads;
if (i >= db->nreads)
{
EPRINTF( EPLACE, "%s: Index out of bounds (Load_Read)\n", Prog_Name);
EXIT(1);
}
if (bases == NULL)
{
bases = Fopen(Catenate(db->path, "", "", ".bps"), "r");
if (bases == NULL)
EXIT(1);
db->bases = (void*) bases;
}
off = r[i].boff;
len = r[i].rlen;
if (ftello(bases) != off)
fseeko(bases, off, SEEK_SET);
clen = COMPRESSED_LEN(len);
if (clen > 0)
{
if (fread(read, clen, 1, bases) != 1)
{
EPRINTF( EPLACE, "%s: Failed read of .bps file (Load_Read)\n", Prog_Name);
EXIT(1);
}
}
Uncompress_Read(len, read);
if (ascii == 1)
{
Lower_Read(read);
read[-1] = '\0';
}
else if (ascii == 2)
{
Upper_Read(read);
read[-1] = '\0';
}
else
read[-1] = 4;
return (0);
}
char* Load_Subread(HITS_DB* db, int i, int beg, int end, char* read, int ascii)
{
FILE* bases = (FILE*) db->bases;
int64 off;
int len, clen;
int bbeg, bend;
HITS_READ* r = db->reads;
if (i >= db->nreads)
{
EPRINTF( EPLACE, "%s: Index out of bounds (Load_Read)\n", Prog_Name);
EXIT(NULL);
}
if (bases == NULL)
{
bases = Fopen(Catenate(db->path, "", "", ".bps"), "r");
if (bases == NULL)
EXIT(NULL);
db->bases = (void*) bases;
}
bbeg = beg / 4;
bend = (end - 1) / 4 + 1;
off = r[i].boff + bbeg;
len = end - beg;
if (ftello(bases) != off)
fseeko(bases, off, SEEK_SET);
clen = bend - bbeg;
if (clen > 0)
{
if (fread(read, clen, 1, bases) != 1)
{
EPRINTF( EPLACE, "%s: Failed read of .bps file (Load_Read)\n", Prog_Name);
EXIT(NULL);
}
}
Uncompress_Read(4 * clen, read);
read += beg % 4;
read[len] = 4;
if (ascii == 1)
{
Lower_Read(read);
read[-1] = '\0';
}
else if (ascii == 2)
{
Upper_Read(read);
read[-1] = '\0';
}
else
read[-1] = 4;
return (read);
}
/*******************************************************************************************
*
* QV BUFFER ALLOCATION QV READ ACCESS
*
********************************************************************************************/
// Allocate and return a buffer of 5 vectors big enough for the largest read in 'db'
char** New_QV_Buffer(HITS_DB* db)
{
char** entry;
char* qvs;
int i;
qvs = (char*) Malloc(db->maxlen * 5, "Allocating New QV Buffer");
entry = (char**) Malloc(sizeof(char*) * 5, "Allocating New QV Buffer");
if (qvs == NULL || entry == NULL)
EXIT(NULL);
for (i = 0; i < 5; i++)
entry[i] = qvs + i * db->maxlen;
return (entry);
}
void Free_QV_Buffer(char** buf)
{
free(buf[0]);
free(buf);
}
// Load into entry the QV streams for the i'th read from db. The parameter ascii applies to
// the DELTAG stream as described for Load_Read.
int Load_QVentry(HITS_DB* db, int i, char** entry, int ascii)
{
HITS_READ* reads;
FILE* quiva;
int rlen;
if (db != Active_DB)
{
if (db->tracks == NULL || strcmp(db->tracks->name, ".@qvs") != 0)
{
EPRINTF( EPLACE, "%s: QV's are not loaded (Load_QVentry)\n", Prog_Name);
EXIT(1);
}
Active_QV = (HITS_QV*) db->tracks;
Active_DB = db;
}
if (i >= db->nreads)
{
EPRINTF( EPLACE, "%s: Index out of bounds (Load_QVentry)\n", Prog_Name);
EXIT(1);
}
reads = db->reads;
quiva = Active_QV->quiva;
rlen = reads[i].rlen;
fseeko(quiva, reads[i].coff, SEEK_SET);
if (Uncompress_Next_QVentry(quiva, entry, Active_QV->coding + Active_QV->table[i], rlen))
EXIT(1);
if (ascii != 1)
{
char* deltag = entry[1];
if (ascii != 2)
{
char x = deltag[rlen];
deltag[rlen] = '\0';
Number_Read(deltag);
deltag[rlen] = x;
}
else
{
int j;
int u = 'A' - 'a';
for (j = 0; j < rlen; j++)
deltag[j] = (char) (deltag[j] + u);
}
}
return (0);
}
/*******************************************************************************************
*
* BLOCK LOAD OF ALL READS (PRIMARILY FOR DALIGNER)
*
********************************************************************************************/
// Allocate a block big enough for all the uncompressed sequences, read them into it,
// reset the 'off' in each read record to be its in-memory offset, and set the
// bases pointer to point at the block after closing the bases file. If ascii is
// non-zero then the reads are converted to ACGT ascii, otherwise the reads are left
// as numeric strings over 0(A), 1(C), 2(G), and 3(T).
int Read_All_Sequences(HITS_DB* db, int ascii)
{
FILE* bases;
int nreads = db->nreads;
HITS_READ* reads = db->reads;
void (*translate)(char* s);
char* seq;
int64 o, off;
int i, len, clen;
bases = Fopen(Catenate(db->path, "", "", ".bps"), "r");
if (bases == NULL)
EXIT(1);
seq = (char*) Malloc(db->totlen + nreads + 4, "Allocating All Sequence Reads");
if (seq == NULL)
{
fclose(bases);
EXIT(1);
}
*seq++ = 4;
if (ascii == 1)
translate = Lower_Read;
else
translate = Upper_Read;
o = 0;
for (i = 0; i < nreads; i++)
{
len = reads[i].rlen;
off = reads[i].boff;
if (ftello(bases) != off)
fseeko(bases, off, SEEK_SET);
clen = COMPRESSED_LEN(len);
if (clen > 0)
{
if (fread(seq + o, clen, 1, bases) != 1)
{
EPRINTF( EPLACE, "%s: Read of .bps file failed (Read_All_Sequences)\n", Prog_Name);
free(seq);
fclose(bases);
EXIT(1);
}
}
Uncompress_Read(len, seq + o);
if (ascii)
translate(seq + o);
reads[i].boff = o;
o += (len + 1);
}
reads[nreads].boff = o;
fclose(bases);
db->bases = (void*) seq;
db->loaded = 1;
return (0);
}
int List_DB_Files(char* path, void actor(char* path, char* extension))
{
int status, plen, rlen, dlen;
char *root, *pwd, *name;
int isdam;
DIR* dirp;
struct dirent* dp;
status = 0;
pwd = PathTo(path);
plen = strlen(path);
if (strcmp(path + (plen - 4), ".dam") == 0)
root = Root(path, ".dam");
else
root = Root(path, ".db");
rlen = strlen(root);
if (root == NULL || pwd == NULL)
{
free(pwd);
free(root);
EXIT(1);
}
if ((dirp = opendir(pwd)) == NULL)
{
EPRINTF( EPLACE, "%s: Cannot open directory %s (List_DB_Files)\n", Prog_Name, pwd);
status = -1;
goto error;
}
isdam = 0;
while ((dp = readdir(dirp)) != NULL) // Get case dependent root name (if necessary)
{
name = dp->d_name;
if (strcmp(name, Catenate("", "", root, ".db")) == 0)
break;
if (strcmp(name, Catenate("", "", root, ".dam")) == 0)
{
isdam = 1;
break;
}
if (strcasecmp(name, Catenate("", "", root, ".db")) == 0)
{
strncpy(root, name, rlen);
break;
}
if (strcasecmp(name, Catenate("", "", root, ".dam")) == 0)
{
strncpy(root, name, rlen);
isdam = 1;
break;
}
}
if (dp == NULL)
{
EPRINTF( EPLACE, "%s: Cannot find %s (List_DB_Files)\n", Prog_Name, pwd);
status = -1;
closedir(dirp);
goto error;
}
if (isdam)
actor(Catenate(pwd, "/", root, ".dam"), "dam");
else
actor(Catenate(pwd, "/", root, ".db"), "db");
rewinddir(dirp); // Report each auxiliary file
while ((dp = readdir(dirp)) != NULL)
{
name = dp->d_name;
dlen = strlen(name);
#ifdef HIDE_FILES
if (name[0] != '.')
continue;
dlen -= 1;
name += 1;
#endif
if (dlen < rlen + 1)
continue;
if (name[rlen] != '.')
continue;
if (strncmp(name, root, rlen) != 0)
continue;
actor(Catenate(pwd, PATHSEP, name, ""), name + (rlen + 1));
}
closedir(dirp);
error: free(pwd);
free(root);
return (status);
}
void Print_Read(char* s, int width)
{
int i;
if (s[0] < 4)
{
for (i = 0; s[i] != 4; i++)
{
if (i % width == 0 && i != 0)
printf("\n");
printf("%d", s[i]);
}
printf("\n");
}
else
{
for (i = 0; s[i] != '\0'; i++)
{
if (i % width == 0 && i != 0)
printf("\n");
printf("%c", s[i]);
}
printf("\n");
}
}
int DB_block_range(char* db, int block, int* _beg, int* _end)
{
int beg = *_beg = -1;
int end = *_end = -1;
if (block <= 0)
{
return 0;
}
FILE* fileDb;
char* path = (char*) malloc(strlen(db) + 20);
char* root = Root(db, NULL);
sprintf(path, "%s.db", root);
free(root);
if ((fileDb = fopen(path, "r")) == NULL)
{
fprintf( stderr, "failed to open database\n");
return -1;
}
char buf[PATH_MAX + 128];
int in_ranges = 0;
int curb = 0;
while (!feof(fileDb))
{
if (!fgets(buf, PATH_MAX + 127, fileDb))
{
break;
}
if (in_ranges)
{
char* num = buf;
while (!isdigit(*num))
{
num += 1;
}
beg = end;
end = atoi(num);
if (curb == block)
{
*_beg = beg;
*_end = end;
break;
}
curb += 1;
}
else if (strstr(buf, "size = "))
{
in_ranges = 1;
}
}
free(path);
fclose(fileDb);
return (*_beg < *_end);
}
int DB_Blocks(char* db) // HEIDELBERG_MODIFICATION
{
FILE* fileDb;
char* path = (char*) malloc(strlen(db) + 20);
char* dir = PathTo(db);
char* root = Root(db, ".db");
sprintf(path, "%s/%s.db", dir, root);
free(root);
free(dir);
if ((fileDb = fopen(path, "r")) == NULL)
{
fprintf( stderr, "failed to open database %s\n", db);
return -1;
}
int nfiles;
if (fscanf(fileDb, "files = %d\n", &nfiles) != 1)
{
fprintf( stderr, "format error in database file %s\n", db);
return -1;
}
int i;
for (i = 0; i < nfiles; i++)
{
char buffer[30001];
if (fgets(buffer, 30000, fileDb) == NULL)
{
fprintf( stderr, "format error in database file %s \n", db);
return -1;
}
}
int nblocks;
if (fscanf(fileDb, "blocks = %d\n", &nblocks) != 1)
{
fprintf( stderr, "could not locate 'blocks' entry in db %s \n", db);
return -1;
}
fclose(fileDb);
free(path);
return nblocks;
}
char* getDir(int RUN_ID, int subjectID) // HEIDELBERG_MODIFICATION
{
char* out = malloc(35);
if (subjectID == 0) // complete DB
{
out[0] = '.';
out[1] = '\0';
return out;
}
if (RUN_ID < 10)
{
if (subjectID < 10)
{
sprintf(out, "d00%d_0000%d", RUN_ID, subjectID);
}
else if (subjectID < 100)
{
sprintf(out, "d00%d_000%d", RUN_ID, subjectID);
}
else if (subjectID < 1000)
{
sprintf(out, "d00%d_00%d", RUN_ID, subjectID);
}
else if (subjectID < 10000)
{
sprintf(out, "d00%d_0%d", RUN_ID, subjectID);
}
else
{
sprintf(out, "d00%d_%d", RUN_ID, subjectID);
}
}
else if (RUN_ID < 100)
{
if (subjectID < 10)
{
sprintf(out, "d0%d_0000%d", RUN_ID, subjectID);
}
else if (subjectID < 100)
{
sprintf(out, "d0%d_000%d", RUN_ID, subjectID);
}
else if (subjectID < 1000)
{
sprintf(out, "d0%d_00%d", RUN_ID, subjectID);
}
else if (subjectID < 10000)
{
sprintf(out, "d0%d_0%d", RUN_ID, subjectID);
}
else
{
sprintf(out, "d0%d_%d", RUN_ID, subjectID);
}
}
else
{
if (subjectID < 10)
{
sprintf(out, "d%d_0000%d", RUN_ID, subjectID);
}
else if (subjectID < 100)
{
sprintf(out, "d%d_000%d", RUN_ID, subjectID);
}
else if (subjectID < 1000)
{
sprintf(out, "d%d_00%d", RUN_ID, subjectID);
}
else if (subjectID < 10000)
{
sprintf(out, "d%d_0%d", RUN_ID, subjectID);
}
else
{
sprintf(out, "d%d_%d", RUN_ID, subjectID);
}
}
return out;
}
|
MartinPippel/DAmar
|
scrub/LAseparate.c
|
<filename>scrub/LAseparate.c
/*
* LAseparate.c
*
* Created on: 10 Jul 2018
* Author: pippel
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/param.h>
#include <unistd.h>
#include "../dalign/align.h"
#include "../db/DB.h"
#include "../lib/colors.h"
#include "../lib/oflags.h"
#include "../lib/pass.h"
#include "../lib/read_loader.h"
#include "../lib/tracks.h"
#include "../lib/utils.h"
#define DEF_ARG_L 0
#define DEF_ARG_O 0
#define DEF_ARG_R "rep"
#undef DEBUG_CHAIN
static void usage()
{
fprintf(stderr, "[-vLT] [-lo <int>] [-r <track>] <db> <overlaps_in> <overlaps_out> <overlaps_out_discard>\n");
fprintf(stderr, "options: -v ... verbose\n");
fprintf(stderr, " -L ... two pass processing with read caching\n");
fprintf(stderr, " -o ... min overlap length (default: %d)\n", DEF_ARG_O);
fprintf(stderr, " -l ... min read length (default: %d)\n", DEF_ARG_L);
fprintf(stderr, " -r ... repeat track name (default %s)\n", DEF_ARG_R);
fprintf(stderr, " -T ... separate Type: 0 - for RepComp, 1 - for ForceAlign\n");
}
typedef struct
{
Overlap **ovls;
int novl;
int maxOvl;
} Chain;
typedef struct
{
// settings
int nMinAlnLength;
int nMinReadLength;
int nVerbose;
int type;
// status
int nKeptOvls;
int nDiscardOvls;
HITS_DB* db;
HITS_TRACK* trackRepeat;
int useRLoader;
Read_Loader* rl;
ovl_header_twidth twidth;
Chain *ovlChains;
int curChains;
int maxChains;
} SeparateContext;
extern char* optarg;
extern int optind, opterr, optopt;
static int cmp_chain_len(const void *a, const void *b)
{
Chain* c1 = (Chain *) a;
Chain* c2 = (Chain *) b;
int i;
int olen1 = c1->ovls[0]->path.aepos - c1->ovls[0]->path.abpos;
for (i = 1; i < c1->novl; i++)
{
olen1 += c1->ovls[i]->path.aepos - c1->ovls[i]->path.abpos;
if (c1->ovls[i - 1]->path.aepos > c1->ovls[i]->path.abpos)
olen1 -= c1->ovls[i - 1]->path.aepos > c1->ovls[i]->path.abpos;
}
int olen2 = c2->ovls[0]->path.aepos - c2->ovls[0]->path.abpos;
for (i = 1; i < c2->novl; i++)
{
olen2 += c2->ovls[i]->path.aepos - c2->ovls[i]->path.abpos;
if (c2->ovls[i - 1]->path.aepos > c2->ovls[i]->path.abpos)
olen2 -= c2->ovls[i - 1]->path.aepos > c2->ovls[i]->path.abpos;
}
return (olen2 - olen1);
}
static int cmp_ovls_abeg(const void* a, const void* b)
{
Overlap* o1 = *(Overlap**) a;
Overlap* o2 = *(Overlap**) b;
int cmp = o1->path.abpos - o2->path.abpos;
if (!cmp)
{
cmp = (o1->path.aepos - o1->path.abpos) - (o2->path.aepos - o2->path.abpos);
}
return cmp;
}
static int contained(int ab, int ae, int bb, int be)
{
if (ab >= bb && ae <= be)
{
return 1;
}
return 0;
}
#ifdef DEBUG_CHAIN
static void printChain(Chain *chain)
{
printf("CHAIN: nvols %d, %7d vs %7d %s\n", chain->novl, chain->ovls[0]->aread, chain->ovls[0]->bread, (chain->ovls[0]->flags & OVL_COMP) ? "COMP" : "NORM");
int i;
for (i = 0; i < chain->novl; ++i)
{
printf("%3d in A [%8d,%8d] in B [%8d,%8d] %5.2f\n", i, chain->ovls[i]->path.abpos, chain->ovls[i]->path.aepos, chain->ovls[i]->path.bbpos,
chain->ovls[i]->path.bepos, chain->ovls[i]->path.diffs * 100.0 / (chain->ovls[i]->path.aepos - chain->ovls[i]->path.abpos));
}
}
#endif
static int getRepeatBases(SeparateContext *ctx, Overlap *ovl, int read)
{
if (ctx->trackRepeat == NULL)
{
return 0;
}
assert(ovl->aread == read || ovl->bread == read);
int bLen = ovl->path.bepos - ovl->path.bbpos;
// get repeats track
track_anno* rep_anno = ctx->trackRepeat->anno;
track_data* rep_data = ctx->trackRepeat->data;
track_anno rb, re;
int nrep = 0;
rb = rep_anno[read] / sizeof(track_data);
re = rep_anno[read + 1] / sizeof(track_data);
// loop through all repeats in a
int rBeg, rEnd;
while (rb < re)
{
rBeg = rep_data[rb];
rEnd = rep_data[rb + 1];
if (ovl->aread == read)
{
nrep += intersect(ovl->path.abpos, ovl->path.aepos, rBeg, rEnd);
}
else
{
if (ovl->flags & OVL_COMP)
{
nrep += intersect(bLen - ovl->path.bepos, bLen - ovl->path.bbpos, rBeg, rEnd);
}
else
{
nrep += intersect(ovl->path.bbpos, ovl->path.bepos, rBeg, rEnd);
}
}
rb += 2;
}
return nrep;
}
static int loader_handler(void* _ctx, Overlap* ovl, int novl)
{
SeparateContext* ctx = (SeparateContext*) _ctx;
Read_Loader* rl = ctx->rl;
int i;
for (i = 0; i < novl; i++)
{
int b = ovl[i].bread;
int trim_b_left, trim_b_right;
trim_b_left = 0;
trim_b_right = DB_READ_LEN(ctx->db, b);
if (ovl[i].flags & OVL_COMP)
{
int tmp = trim_b_left;
int blen = DB_READ_LEN(ctx->db, ovl[i].bread);
trim_b_left = blen - trim_b_right;
trim_b_right = blen - tmp;
}
if (trim_b_left >= trim_b_right)
{
continue;
}
int bbt = MAX(trim_b_left, ovl[i].path.bbpos);
int bet = MIN(trim_b_right, ovl[i].path.bepos);
if (bbt >= bet)
{
continue;
}
if (bbt == ovl[i].path.bbpos && bet == ovl[i].path.bepos)
{
continue;
}
bbt = MAX(trim_b_left, ovl[i].path.bbpos);
bet = MIN(trim_b_right, ovl[i].path.bepos);
if (bbt < bet && (bbt != ovl[i].path.bbpos || bet != ovl[i].path.bepos))
{
rl_add(rl, ovl[i].aread);
rl_add(rl, ovl[i].bread);
continue;
}
int bepos = ovl[i].path.bepos;
if (bepos > bet)
{
rl_add(rl, ovl[i].aread);
rl_add(rl, ovl[i].bread);
}
}
return 1;
}
static void separate_pre(PassContext* pctx, SeparateContext* fctx)
{
printf( ANSI_COLOR_GREEN "PASS separate\n" ANSI_COLOR_RESET);
fctx->twidth = pctx->twidth;
fctx->nKeptOvls = 0;
fctx->nDiscardOvls = 0;
fctx->curChains = 0;
fctx->maxChains = 5;
fctx->ovlChains = (Chain*) malloc(sizeof(Chain) * fctx->maxChains);
bzero(fctx->ovlChains, sizeof(Chain) * fctx->maxChains);
}
static void separate_post(SeparateContext* ctx)
{
int i;
for (i = 0; i < ctx->maxChains; i++)
{
Chain *chain = ctx->ovlChains + i;
if (chain)
free(chain->ovls);
else
break;
}
free(ctx->ovlChains);
printf("Kept ovls: %10d\n", ctx->nKeptOvls);
printf("Discard ovls: %10d\n", ctx->nDiscardOvls);
}
static void chain(SeparateContext*ctx, Overlap *ovls, int n)
{
/// TODO hard coded - was taken from LAanalyze which is adapted for contig vs contig alignments
int MIN_OVL_LOOKAHEAD = 5000;
int MAX_OVL_LOOKAHEAD = 30000;
int STRIDE_OVL_LOOKAHEAD = 5000;
if (n < 2)
return;
#ifdef DEBUG_CHAIN
printf("chain(%d,%d,%d) CHAIN: n%d m%d\n", ovls->aread, ovls->bread, n, ctx->curChains, ctx->maxChains);
#endif
int aread, bread;
int alen, blen;
int i;
aread = ovls->aread;
bread = ovls->bread;
alen = DB_READ_LEN(ctx->db, aread);
blen = DB_READ_LEN(ctx->db, bread);
int nremain = n;
// mark contained overlaps
#ifdef DEBUG_CHAIN
printf("mark contained overlaps\n");
#endif
{
int j;
for (i = 0; i < n; i++)
{
Overlap *ovl_i = ovls + i;
if (ovl_i->flags & (OVL_CONT))
continue;
for (j = i + 1; j < n; j++)
{
Overlap *ovl_j = ovls + j;
if (ovl_j->flags & (OVL_CONT))
continue;
if (contained(ovl_j->path.abpos, ovl_j->path.aepos, ovl_i->path.abpos, ovl_i->path.aepos) && contained(ovl_j->path.bbpos, ovl_j->path.bepos, ovl_i->path.bbpos, ovl_i->path.bepos))
{
ovl_j->flags |= (OVL_CONT);
}
}
}
}
{
for (i = 0; i < n; i++)
{
Overlap *ovl_i = ovls + i;
if (ovl_i->flags & (OVL_CONT | OVL_DISCARD))
{
ovl_i->flags |= OVL_DISCARD;
nremain--;
}
}
}
#ifdef DEBUG_CHAIN
printf("nremain %d\n", nremain);
#endif
if (nremain < 1)
return;
assert(nremain >= 1);
while (nremain > 0)
{
int longestUniqOvlBases = -1;
int longestUniqOvlIdx = -1;
int longestOvlBases = -1;
int longestOvlIdx = -1;
// find longest overlap based on number of unique bases
for (i = 0; i < n; i++)
{
Overlap *ovl = ovls + i;
if (ovl->flags & (OVL_CONT | OVL_DISCARD | OVL_TEMP))
{
continue;
}
int aLen = ovl->path.aepos - ovl->path.abpos;
int bLen = ovl->path.bepos - ovl->path.bbpos;
int aRep = getRepeatBases(ctx, ovl, ovl->aread);
int bRep = getRepeatBases(ctx, ovl, ovl->bread);
#ifdef DEBUG_CHAIN
printf("%d - %d [%d, %d] [%d, %d], aR %d/%d, bR %d/%d\n", aread, bread, ovl->path.abpos, ovl->path.aepos, ovl->path.bbpos, ovl->path.bepos, aLen, aRep,
bLen, bRep);
#endif
int tmpBases = MAX(aLen - aRep, bLen - bRep);
if (tmpBases > longestUniqOvlBases)
{
longestUniqOvlBases = tmpBases;
longestUniqOvlIdx = i;
}
tmpBases = MAX(aLen, bLen);
if (tmpBases > longestOvlBases)
{
longestOvlBases = tmpBases;
longestOvlIdx = i;
}
}
if (longestUniqOvlBases < ctx->twidth && longestOvlBases > longestUniqOvlBases)
{
#ifdef DEBUG_CHAIN
printf("Number of unique bases to low. Use longest overlap.\n");
#endif
longestUniqOvlBases = longestOvlBases;
longestUniqOvlIdx = longestOvlIdx;
}
#ifdef DEBUG_CHAIN
printf("longest overlap:\n");
printf("idx: %d --> uB %d, %d - %d [%d, %d] [%d, %d]\n", longestUniqOvlIdx, longestUniqOvlBases, ovls[longestUniqOvlIdx].aread,
ovls[longestUniqOvlIdx].bread, ovls[longestUniqOvlIdx].path.abpos, ovls[longestUniqOvlIdx].path.aepos, ovls[longestUniqOvlIdx].path.bbpos,
ovls[longestUniqOvlIdx].path.bepos);
#endif
// try to "elongate" longest overlap
// 1st on the right
// 2nd on the left side
if (ctx->curChains == ctx->maxChains)
{
ctx->maxChains = ctx->maxChains * 1.2 + 5;
ctx->ovlChains = (Chain*) realloc(ctx->ovlChains, sizeof(Chain) * ctx->maxChains);
bzero(ctx->ovlChains + ctx->curChains, sizeof(Chain) * (ctx->maxChains - ctx->curChains));
}
Chain *chain = ctx->ovlChains + ctx->curChains;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d, nremain: %d\n", chain->novl, chain->maxOvl, nremain);
#endif
if (chain->ovls == NULL)
{
chain->novl = 0;
chain->maxOvl = 10;
chain->ovls = (Overlap**) malloc(sizeof(Overlap*) * chain->maxOvl);
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d\n", chain->novl, chain->maxOvl);
#endif
}
chain->ovls[0] = ovls + longestUniqOvlIdx;
chain->ovls[0]->flags |= OVL_TEMP;
chain->novl++;
nremain--;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d, nremain %d\n", chain->novl, chain->maxOvl, nremain);
#endif
int ab1, ae1;
int bb1, be1;
int ab2, ae2;
int bb2, be2;
if (nremain && longestUniqOvlIdx + 1 < n)
{
ab1 = ovls[longestUniqOvlIdx].path.abpos;
ae1 = ovls[longestUniqOvlIdx].path.aepos;
bb1 = ovls[longestUniqOvlIdx].path.bbpos;
be1 = ovls[longestUniqOvlIdx].path.bepos;
#ifdef DEBUG_CHAIN
printf("extend longest overlap in right direction\n");
#endif
// 1st right
int cont = 1;
int curBestUniqOffset = 1;
int curBestUniqBases = -1;
int curBestBases = -1;
int curBestOffset = 1;
int curBestIntersection = MAX(alen, blen);
while (cont)
{
int stepSize;
for (stepSize = MIN_OVL_LOOKAHEAD; stepSize <= MAX_OVL_LOOKAHEAD && curBestUniqBases == -1; stepSize += STRIDE_OVL_LOOKAHEAD)
{
#ifdef DEBUG_CHAIN
printf("FOR LOOP stepsize %d\n", stepSize);
#endif
for (i = longestUniqOvlIdx + curBestUniqOffset; i < n; i++)
{
Overlap * ovl = ovls + i;
ab2 = ovl->path.abpos;
ae2 = ovl->path.aepos;
bb2 = ovl->path.bbpos;
be2 = ovl->path.bepos;
if ((ovl->flags & OVL_COMP) != (ovls[longestUniqOvlIdx].flags & OVL_COMP))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> different orientations\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_CONT)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> really contained repeat\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_TEMP)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> is part of another chain\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_DISCARD)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> discarded\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
// todo mark those as discard ????
if (contained(ab2, ae2, ab1, ae1))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> contained repeat in A-interval\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
// todo mark those as discard ????
if (contained(bb2, be2, bb1, be1))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> contained repeat in B-interval\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ae2 < ae1 || be2 < be1) // also overlap must follow right direction
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> improper right extension direction (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2,
bb2, be2, stepSize);
#endif
continue;
}
if (MAX(ab2 - ae1, bb2 - be1) > stepSize)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> gap size too large (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
continue;
}
if (ae1 - ab2 > ae2 - ae1 || be1 - bb2 > be2 - be1) // at least 50% overhang
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> overhang too short (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
continue;
}
// check if current overlap is better (longer/more unique bases ?) then curBest
int curUniqBasesInAIvl = (ae2 - ab2) - getRepeatBases(ctx, ovl, aread);
int curUniqBasesInBIvl = (be2 - bb2) - getRepeatBases(ctx, ovl, bread);
if (curBestIntersection > MAX(intersect(ab1, ae1, ab2, ae2), intersect(bb1, be1, bb2, be2)) && curBestBases < MIN(ae2 - ab2, be2 - bb2))
{
curBestBases = MIN(ae2 - ab2, be2 - bb2);
curBestOffset = i - longestUniqOvlIdx;
curBestIntersection = MAX(intersect(ab1, ae1, ab2, ae2), intersect(bb1, be1, bb2, be2));
}
if (curBestUniqBases < MIN(curUniqBasesInAIvl, curUniqBasesInBIvl))
{
#ifdef DEBUG_CHAIN
printf("found right current best overlap %d %d %d: [%d, %d] [%d, %d] right side\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
curBestUniqOffset = i - longestUniqOvlIdx;
curBestUniqBases = MIN(curUniqBasesInAIvl, curUniqBasesInBIvl);
}
else if (curBestUniqBases == -1 && stepSize + STRIDE_OVL_LOOKAHEAD > MAX_OVL_LOOKAHEAD) // for repetitive genomes
{
Overlap *tmpOvl = ovls + (longestUniqOvlIdx + curBestOffset);
if ((intersect(ab1, ae1, tmpOvl->path.abpos, tmpOvl->path.aepos) < ae1 - tmpOvl->path.abpos) && (intersect(bb1, be1, tmpOvl->path.bbpos, tmpOvl->path.bepos) < be1 - tmpOvl->path.bbpos))
{
curBestUniqOffset = curBestOffset;
curBestUniqBases = 1;
}
}
else
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> cannot be anchored (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
}
}
}
// check if left best overlap can be used to extend overlap group on the right side
if (curBestUniqBases < 0) // i.e. there was no good overlap at right side
{
#ifdef DEBUG_CHAIN
printf("could not extend ovlgroup on right side with proper overlap (with stepSize %d)\n", stepSize - STRIDE_OVL_LOOKAHEAD);
#endif
break;
}
/// todo further sanity check necessary ???
ab2 = ovls[longestUniqOvlIdx + curBestUniqOffset].path.abpos;
ae2 = ovls[longestUniqOvlIdx + curBestUniqOffset].path.aepos;
bb2 = ovls[longestUniqOvlIdx + curBestUniqOffset].path.bbpos;
be2 = ovls[longestUniqOvlIdx + curBestUniqOffset].path.bepos;
#ifdef DEBUG_CHAIN
printf("extend ovlgroup with (right): %d %d %d: [%d, %d] [%d, %d] stepSize %d\n", longestUniqOvlIdx + curBestUniqOffset,
ovls[longestUniqOvlIdx + curBestUniqOffset].aread, ovls[longestUniqOvlIdx + curBestUniqOffset].bread, ab1, ae1, ab2, ae2,
stepSize - STRIDE_OVL_LOOKAHEAD);
#endif
if (chain->novl == chain->maxOvl)
{
chain->maxOvl = chain->maxOvl * 1.2 + 5;
chain->ovls = (Overlap**) realloc(chain->ovls, sizeof(Overlap*) * chain->maxOvl);
}
// append left side overlaps at the end of chain, i.e. chain must be sorted afterwards by abpos
chain->ovls[chain->novl] = ovls + (longestUniqOvlIdx + curBestUniqOffset);
chain->ovls[chain->novl]->flags |= OVL_TEMP;
chain->novl++;
nremain--;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d nremain %d\n", chain->novl, chain->maxOvl, nremain);
#endif
ab1 = ab2;
ae1 = ae2;
bb1 = bb2;
be1 = be2;
curBestUniqOffset++;
curBestOffset = curBestUniqOffset;
curBestUniqBases = -1;
curBestBases = -1;
curBestIntersection = MAX(alen, blen);
if (longestUniqOvlIdx + curBestUniqOffset >= n)
{
cont = 0;
}
}
}
if (nremain && longestUniqOvlIdx > 0)
{
ab1 = ovls[longestUniqOvlIdx].path.abpos;
ae1 = ovls[longestUniqOvlIdx].path.aepos;
bb1 = ovls[longestUniqOvlIdx].path.bbpos;
be1 = ovls[longestUniqOvlIdx].path.bepos;
#ifdef DEBUG_CHAIN
printf("extend longest overlap in left direction\n");
#endif
// 2nd left side
int cont = 1;
int curBestUniqOffset = 1;
int curBestUniqBases = -1;
int curBestBases = -1;
int curBestOffset = 1;
int curBestIntersection = MAX(alen, blen);
while (cont)
{
int stepSize;
for (stepSize = MIN_OVL_LOOKAHEAD; stepSize <= MAX_OVL_LOOKAHEAD && curBestUniqBases == -1; stepSize += STRIDE_OVL_LOOKAHEAD)
{
#ifdef DEBUG_CHAIN
printf("FOR LOOP stepsize %d\n", stepSize);
#endif
// try to find next best overlap with lookahead of stepSize bases
for (i = longestUniqOvlIdx - curBestUniqOffset; i >= 0; --i)
{
Overlap * ovl = ovls + i;
#ifdef DEBUG_CHAIN
printf("LEFT: Check ovl: a[%d, %d] b[%d,%d]\n", ovl->path.abpos, ovl->path.aepos, ovl->path.bbpos, ovl->path.bepos);
#endif
ab2 = ovl->path.abpos;
ae2 = ovl->path.aepos;
bb2 = ovl->path.bbpos;
be2 = ovl->path.bepos;
if ((ovl->flags & OVL_COMP) != (ovls[longestUniqOvlIdx].flags & OVL_COMP))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> different orientations\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_CONT)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> really contained repeat\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_TEMP)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> is part of another chain\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_DISCARD)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> discarded\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
// todo mark those as discard ????
if (contained(ab2, ae2, ab1, ae1))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> contained repeat in A-interval\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
// todo mark those as discard ????
if (contained(bb2, be2, bb1, be1))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> contained repeat in B-interval\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ab2 > ab1 || bb2 > bb1) // also overlap must follow left direction
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> improper left extension direction (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2,
bb2, be2, stepSize);
#endif
continue;
}
if (MAX(ab1 - ae2, bb1 - be2) > stepSize)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> gap size too large (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
continue;
}
if (ae2 - ab1 > ab1 - ab2 || be2 - bb1 > bb1 - bb2) // at least 50% overhang
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> overhang too short (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
continue;
}
// check if current overlap is better (longer/more unique bases ?) then curLeftBest
int curUniqBasesInAIvl = (ae2 - ab2) - getRepeatBases(ctx, ovl, aread);
int curUniqBasesInBIvl = (be2 - bb2) - getRepeatBases(ctx, ovl, bread);
if (curBestIntersection > MAX(intersect(ab2, ae2, ab1, ae1), intersect(bb2, be2, bb1, be1)) && curBestBases < MIN(ae2 - ab2, be2 - bb2))
{
curBestBases = MIN(ae2 - ab2, be2 - bb2);
curBestOffset = longestUniqOvlIdx - i;
curBestIntersection = MAX(intersect(ab2, ae2, ab1, ae1), intersect(bb2, be2, bb1, be1));
}
if (curBestUniqBases < MIN(curUniqBasesInAIvl, curUniqBasesInBIvl))
{
#ifdef DEBUG_CHAIN
printf("found left current best overlap %d %d %d: [ab2 %d, ae2 %d] [bb2 %d, be2 %d] left side\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
curBestUniqOffset = longestUniqOvlIdx - i;
curBestUniqBases = curUniqBasesInAIvl + curUniqBasesInBIvl;
}
else if (curBestUniqBases == -1 && stepSize + STRIDE_OVL_LOOKAHEAD > MAX_OVL_LOOKAHEAD) // for repetitive genomes
{
Overlap *tmpOvl = ovls + (longestUniqOvlIdx - curBestOffset);
if ((intersect(tmpOvl->path.abpos, tmpOvl->path.aepos, ab1, ae1) < ae1 - tmpOvl->path.abpos) && (intersect(tmpOvl->path.bbpos, tmpOvl->path.bepos, bb1, be1) < be1 - tmpOvl->path.bbpos))
{
curBestUniqOffset = curBestOffset;
curBestUniqBases = 1;
}
}
else
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> cannot be anchored (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
}
}
}
// check if left best overlap can be used to extend overlap group on the left side
if (curBestUniqBases < 0) // i.e. there was no good overlap at left side
{
#ifdef DEBUG_CHAIN
printf("could not extend ovlgroup on left side with proper overlap (stepSize %d)\n", stepSize - STRIDE_OVL_LOOKAHEAD);
#endif
break;
}
/// todo further sanity check necessary ???
ab2 = ovls[longestUniqOvlIdx - curBestUniqOffset].path.abpos;
ae2 = ovls[longestUniqOvlIdx - curBestUniqOffset].path.aepos;
bb2 = ovls[longestUniqOvlIdx - curBestUniqOffset].path.bbpos;
be2 = ovls[longestUniqOvlIdx - curBestUniqOffset].path.bepos;
#ifdef DEBUG_CHAIN
printf("extend ovlgroup with (left): %d %d %d: [%d, %d] [%d, %d] with stepSize %d\n", longestUniqOvlIdx - curBestUniqOffset,
ovls[longestUniqOvlIdx - curBestUniqOffset].aread, ovls[longestUniqOvlIdx - curBestUniqOffset].bread, ab1, ae1, ab2, ae2,
stepSize - STRIDE_OVL_LOOKAHEAD);
#endif
if (ctx->curChains == ctx->maxChains)
{
ctx->maxChains = ctx->maxChains * 1.2 + 5;
ctx->ovlChains = (Chain*) realloc(ctx->ovlChains, sizeof(Chain) * ctx->maxChains);
bzero(ctx->ovlChains + ctx->curChains, sizeof(Chain) * (ctx->maxChains - ctx->curChains));
}
if (chain->novl == chain->maxOvl)
{
chain->maxOvl = chain->maxOvl * 1.2 + 5;
chain->ovls = (Overlap**) realloc(chain->ovls, sizeof(Overlap*) * chain->maxOvl);
}
// append left side overlaps at the end of chain, i.e. chain must be sorted afterwards by abpos
chain->ovls[chain->novl] = ovls + (longestUniqOvlIdx - curBestUniqOffset);
chain->ovls[chain->novl]->flags |= OVL_TEMP;
chain->novl++;
nremain--;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d nremain %d\n", chain->novl, chain->maxOvl, nremain);
#endif
ab1 = ab2;
ae1 = ae2;
bb1 = bb2;
be1 = be2;
curBestUniqOffset++;
curBestOffset = curBestUniqOffset;
curBestUniqBases = -1;
curBestBases = -1;
curBestIntersection = MAX(alen, blen);
if (longestUniqOvlIdx - curBestUniqOffset < 0)
{
cont = 0;
}
}
if (chain->novl > 1)
{ // sort chain
qsort(chain->ovls, chain->novl, sizeof(Overlap*), cmp_ovls_abeg);
}
}
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d nremain: %d\n", chain->novl, chain->maxOvl, nremain);
#endif
// find possible ovls that could be added to chain (i.e. fill gaps)
if (chain->novl > 1 && nremain > 0)
{
#ifdef DEBUG_CHAIN
printf("find possible ovls that could be added to chain (i.e. fill gaps)\n");
#endif
int chainIdx = 0;
int chainLastIdx = chain->novl - 1;
int j;
for (i = 0; i < n; i++)
{
Overlap *ovl = ovls + i;
if ((ovl->flags & (OVL_TEMP | OVL_CONT | OVL_DISCARD)) || ((ovl->flags & OVL_COMP) != (chain->ovls[chainIdx]->flags & OVL_COMP)))
continue;
if (ovl->path.abpos < chain->ovls[chainIdx]->path.abpos)
continue;
if (ovl->path.abpos > chain->ovls[chainLastIdx]->path.abpos)
break;
int ovhBases = 100;
for (j = chainIdx; j < chainLastIdx; j++)
{
if (chain->ovls[j]->path.aepos - ovhBases < ovl->path.abpos && chain->ovls[j + 1]->path.abpos + ovhBases > ovl->path.aepos && chain->ovls[j]->path.bepos - ovhBases < ovl->path.bbpos && chain->ovls[j + 1]->path.bbpos + ovhBases > ovl->path.bepos)
{
Overlap *lastAddedOvl = chain->ovls[chain->novl - 1];
if (intersect(ovl->path.abpos, ovl->path.aepos, lastAddedOvl->path.abpos, lastAddedOvl->path.aepos) > ovhBases || intersect(ovl->path.bbpos, ovl->path.bepos, lastAddedOvl->path.bbpos, lastAddedOvl->path.bepos) > ovhBases)
break;
if (chain->novl == chain->maxOvl)
{
chain->maxOvl = chain->maxOvl * 1.2 + 5;
chain->ovls = (Overlap**) realloc(chain->ovls, sizeof(Overlap*) * chain->maxOvl);
}
// append left side overlaps at the end of chain, i.e. chain must be sorted afterwards by abpos
ovl->flags |= OVL_TEMP;
chain->ovls[chain->novl] = ovl;
chain->novl++;
nremain--;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d nremain %d\n", chain->novl, chain->maxOvl, nremain);
#endif
}
if (ovl->path.abpos > chain->ovls[j + 1]->path.abpos)
chainIdx++;
}
}
if (chainLastIdx < chain->novl - 1)
{
qsort(chain->ovls, chain->novl, sizeof(Overlap*), cmp_ovls_abeg);
}
}
if (nremain)
{
// mark remaining ovls as DISC if the overlap with a chain overlap !!
#ifdef DEBUG_CHAIN
printf("// mark remaining ovls as DISC if they overlap with a chain overlap !!\n");
#endif
int chainIdx = 0;
int chainLastIdx = chain->novl - 1;
int j;
for (i = 0; i < n; i++)
{
Overlap *ovl = ovls + i;
if ((ovl->flags & (OVL_TEMP | OVL_CONT | OVL_DISCARD)) || ((ovl->flags & OVL_COMP) != (chain->ovls[chainIdx]->flags & OVL_COMP)))
continue;
for (j = chainIdx; j <= chainLastIdx; j++)
{
if (intersect(chain->ovls[j]->path.abpos, chain->ovls[j]->path.aepos, ovl->path.abpos, ovl->path.aepos) || intersect(chain->ovls[j]->path.bbpos, chain->ovls[j]->path.bepos, ovl->path.bbpos, ovl->path.bepos))
{
ovl->flags |= OVL_DISCARD;
nremain--;
#ifdef DEBUG_CHAIN
printf("DISCARD [%d, %d] [%d, %d] nremain %d\n", ovl->path.abpos, ovl->path.aepos, ovl->path.bbpos, ovl->path.bepos, nremain);
#endif
}
if (j + 1 < chain->novl && ovl->path.abpos > chain->ovls[j + 1]->path.abpos)
chainIdx++;
}
}
}
#ifdef DEBUG_CHAIN
printChain(chain);
#endif
// sanity check // there should be no intersection with other chains (with same orientation) possible
int valid = 1;
if (ctx->curChains)
{
#ifdef DEBUG_CHAIN
printf("DO SANITY CHECK\n");
#endif
int j;
for (i = 0; i < ctx->curChains && valid; i++)
{
if ((chain->ovls[0]->flags & OVL_COMP) == (ctx->ovlChains[i].ovls[0]->flags && OVL_COMP))
{
for (j = 0; j < chain->novl; j++)
{
if ((chain->ovls[j]->path.abpos > ctx->ovlChains[i].ovls[0]->path.abpos && chain->ovls[j]->path.aepos < ctx->ovlChains[i].ovls[ctx->ovlChains[i].novl - 1]->path.aepos)
|| (chain->ovls[j]->path.bbpos > ctx->ovlChains[i].ovls[0]->path.bbpos && chain->ovls[j]->path.bepos < ctx->ovlChains[i].ovls[ctx->ovlChains[i].novl - 1]->path.bepos))
{
#ifdef DEBUG_CHAIN
printf("CHAIN is invalid - DISCARD\n");
#endif
valid = 0;
break;
}
}
}
}
}
if (valid)
ctx->curChains++;
else
{
int j;
for (j = 0; j < chain->novl; j++)
{
chain->ovls[j]->flags |= OVL_DISCARD;
}
chain->novl = 0;
}
#ifdef DEBUG_CHAIN
printf("curChain: %d, remain unchained OVls: %d\n", ctx->curChains, nremain);
#endif
}
#ifdef DEBUG_CHAIN
printf("FINAL CHAINS: %d %7d vs %7d\n", ctx->curChains, ctx->ovlChains[0].ovls[0]->aread, ctx->ovlChains[0].ovls[0]->bread);
for (i = 0; i < ctx->curChains; i++)
{
printf(" CHAIN %d/%d: #novl %d\n", i + 1, ctx->curChains, ctx->ovlChains[0].novl);
int j;
for (j = 0; j < ctx->ovlChains[i].novl; j++)
{
printf(" OVL %d/%d: a[%7d, %7d] b[%7d, %7d] %s\n", j + 1, ctx->ovlChains[i].novl, ctx->ovlChains[i].ovls[j]->path.abpos,
ctx->ovlChains[i].ovls[j]->path.aepos, ctx->ovlChains[i].ovls[j]->path.bbpos, ctx->ovlChains[i].ovls[j]->path.bepos,
(ctx->ovlChains[i].ovls[j]->flags & OVL_COMP) ? "COMP" : "NORM");
}
}
#endif
// sort chains according to alignment lengths
if (ctx->curChains > 1)
{
#ifdef DEBUG_CHAIN
printf("SORT CHAINS (longest first):\n");
#endif
qsort(ctx->ovlChains, ctx->curChains, sizeof(Chain), cmp_chain_len);
#ifdef DEBUG_CHAIN
printf("FINAL CHAINS: %d %7d vs %7d\n", ctx->curChains, ctx->ovlChains[0].ovls[0]->aread, ctx->ovlChains[0].ovls[0]->bread);
for (i = 0; i < ctx->curChains; i++)
{
printf(" CHAIN %d/%d: #novl %d\n", i + 1, ctx->curChains, ctx->ovlChains[0].novl);
int j;
for (j = 0; j < ctx->ovlChains[i].novl; j++)
{
printf(" OVL %d/%d: a[%7d, %7d] b[%7d, %7d] %s\n", j + 1, ctx->ovlChains[i].novl, ctx->ovlChains[i].ovls[j]->path.abpos,
ctx->ovlChains[i].ovls[j]->path.aepos, ctx->ovlChains[i].ovls[j]->path.bbpos, ctx->ovlChains[i].ovls[j]->path.bepos,
(ctx->ovlChains[i].ovls[j]->flags & OVL_COMP) ? "COMP" : "NORM");
}
}
#endif
}
}
static int separate_handler(void* _ctx, Overlap* ovl, int novl)
{
SeparateContext* ctx = (SeparateContext*) _ctx;
int i;
chain(ctx, ovl, novl);
if (ctx->type == 0) // separate for repcomp
{
if (ctx->curChains)
{
Chain *bestChain = ctx->ovlChains;
int properBeg = 0;
int properEnd = 0;
int gapBasesInA = 0;
int gapBasesInB = 0;
int itsBasesInA = 0;
int itsBasesInB = 0;
int overlapBases = 0;
// check for proper begin
if (MIN(bestChain->ovls[0]->path.abpos, bestChain->ovls[0]->path.bbpos) < 1000)
properBeg = 1;
// check for proper end
if (bestChain->ovls[bestChain->novl - 1]->path.aepos + 1000 > DB_READ_LEN(ctx->db, ovl->aread) || bestChain->ovls[bestChain->novl - 1]->path.bepos + 1000 > DB_READ_LEN(ctx->db, ovl->bread))
properEnd = 1;
#ifdef DEBUG
printf("properBeg: %d, properEnd %d\n", properBeg, properEnd);
#endif
if (properBeg && properEnd)
{
int i, its_a, its_b;
overlapBases = MAX(bestChain->ovls[0]->path.aepos - bestChain->ovls[0]->path.abpos, bestChain->ovls[0]->path.bepos - bestChain->ovls[0]->path.bbpos);
for (i = 1; i < bestChain->novl; i++)
{
its_a = its_b = 0;
overlapBases += MAX(bestChain->ovls[i]->path.aepos - bestChain->ovls[i]->path.abpos, bestChain->ovls[i]->path.bepos - bestChain->ovls[i]->path.bbpos);
// check for intersection in A
if (bestChain->ovls[i]->path.abpos < bestChain->ovls[i - 1]->path.aepos)
{
its_a = bestChain->ovls[i - 1]->path.aepos - bestChain->ovls[i]->path.abpos;
if (its_a > 1000)
{
itsBasesInA = -1;
break;
}
itsBasesInA += its_a;
}
// check for gap in A
else
{
int gap = bestChain->ovls[i]->path.abpos - bestChain->ovls[i - 1]->path.aepos;
// if (gap > 1000)
// {
// gapBasesInA = -1;
// break;
// }
gapBasesInA += gap;
}
// check for intersection in B
if (bestChain->ovls[i]->path.bbpos < bestChain->ovls[i - 1]->path.bepos)
{
its_b = bestChain->ovls[i - 1]->path.bepos - bestChain->ovls[i]->path.bbpos;
if (its_b > 1000)
{
itsBasesInB = -1;
break;
}
itsBasesInB += its_b;
}
// check for gap in B
else
{
int gap = bestChain->ovls[i]->path.bbpos - bestChain->ovls[i - 1]->path.bepos;
// if (gap > 1000)
// {
// gapBasesInB = -1;
// break;
// }
gapBasesInB += gap;
}
overlapBases -= MAX(its_a, its_b);
}
}
#ifdef DEBUG
printf("if(%d && %d && %d >=0 && %d >=0 && %d >=0 && %d >=0 && %d * 0.3 > MAX(%d, %d))\n", properBeg, properEnd, itsBasesInA, itsBasesInB, gapBasesInA,
gapBasesInB, overlapBases, gapBasesInA, gapBasesInB);
#endif
// if there is a proper chain between A and B reads, then discard all overlaps between A and B for the repcomp step, (otherwise do repcomp)
if (properBeg && properEnd && itsBasesInA >= 0 && itsBasesInB >= 0 && gapBasesInA >= 0 && gapBasesInB >= 0 && overlapBases * 0.3 > MAX(gapBasesInA, gapBasesInB))
{
#ifdef DEBUG
printf("FOUND PROPER CHAIN - EXCLUDE ALL OVLS FROM REPCOMP INPUT\n");
#endif
for (i = 0; i < novl; i++)
{
ovl[i].flags |= OVL_DISCARD;
ctx->nDiscardOvls++;
}
}
else // reset all discard flags that were set during chain detection
{
for (i = 0; i < novl; i++)
{
if (ovl[i].flags & OVL_DISCARD)
{
ovl[i].flags &= ~OVL_DISCARD;
}
ctx->nKeptOvls++;
}
}
}
else // there is only one overlap !!! check this
{
int properBeg = (MIN(ovl->path.abpos, ovl->path.bbpos) < 1000);
int properEnd = (ovl->path.aepos + 1000 > DB_READ_LEN(ctx->db, ovl->aread) || ovl->path.bepos + 1000 > DB_READ_LEN(ctx->db, ovl->bread));
if (properBeg && properEnd)
{
#ifdef DEBUG
printf("FOUND PROPER SINGLE OVL - EXCLUDE OVL FROM REPCOMP INPUT\n");
#endif
ovl->flags |= OVL_DISCARD;
ctx->nDiscardOvls++;
}
else
{
ctx->nKeptOvls++;
}
}
}
else if (ctx->type == 1)
{
if (ctx->curChains == 1) // ignore everything, where you have more then 1 chain
{
Chain *bestChain = ctx->ovlChains;
int properBeg = 0;
int properEnd = 0;
int gapBasesInA = 0;
int gapBasesInB = 0;
int itsBasesInA = 0;
int itsBasesInB = 0;
int overlapBases = 0;
// check for proper begin
if (MIN(bestChain->ovls[0]->path.abpos, bestChain->ovls[0]->path.bbpos) < 1000)
properBeg = 1;
// check for proper end
if (bestChain->ovls[bestChain->novl - 1]->path.aepos + 1000 > DB_READ_LEN(ctx->db, ovl->aread) || bestChain->ovls[bestChain->novl - 1]->path.bepos + 1000 > DB_READ_LEN(ctx->db, ovl->bread))
properEnd = 1;
#ifdef DEBUG
printf("properBeg: %d, properEnd %d\n", properBeg, properEnd);
#endif
if (properBeg && properEnd)
{
if (bestChain->novl == 1)
{
int realBeg = (MIN(bestChain->ovls[0]->path.abpos, bestChain->ovls[0]->path.bbpos) == 0);
int realEnd = (bestChain->ovls[0]->path.aepos == DB_READ_LEN(ctx->db, bestChain->ovls[0]->aread) || bestChain->ovls[0]->path.bepos == DB_READ_LEN(ctx->db, bestChain->ovls[0]->bread));
if (realBeg && realEnd)
{
properBeg = 0;
}
}
else
{
int i, its_a, its_b;
overlapBases = MAX(bestChain->ovls[0]->path.aepos - bestChain->ovls[0]->path.abpos, bestChain->ovls[0]->path.bepos - bestChain->ovls[0]->path.bbpos);
for (i = 1; i < bestChain->novl; i++)
{
its_a = its_b = 0;
overlapBases += MAX(bestChain->ovls[i]->path.aepos - bestChain->ovls[i]->path.abpos, bestChain->ovls[i]->path.bepos - bestChain->ovls[i]->path.bbpos);
// check for intersection in A
if (bestChain->ovls[i]->path.abpos < bestChain->ovls[i - 1]->path.aepos)
{
its_a = bestChain->ovls[i - 1]->path.aepos - bestChain->ovls[i]->path.abpos;
if (its_a > 1000)
{
itsBasesInA = -1;
break;
}
itsBasesInA += its_a;
}
// check for gap in A
else
{
int gap = bestChain->ovls[i]->path.abpos - bestChain->ovls[i - 1]->path.aepos;
// if (gap > 1000)
// {
// gapBasesInA = -1;
// break;
// }
gapBasesInA += gap;
}
// check for intersection in B
if (bestChain->ovls[i]->path.bbpos < bestChain->ovls[i - 1]->path.bepos)
{
its_b = bestChain->ovls[i - 1]->path.bepos - bestChain->ovls[i]->path.bbpos;
if (its_b > 1000)
{
itsBasesInB = -1;
break;
}
itsBasesInB += its_b;
}
// check for gap in B
else
{
int gap = bestChain->ovls[i]->path.bbpos - bestChain->ovls[i - 1]->path.bepos;
// if (gap > 1000)
// {
// gapBasesInB = -1;
// break;
// }
gapBasesInB += gap;
}
overlapBases -= MAX(its_a, its_b);
}
}
}
#ifdef DEBUG
printf("if(%d && %d && %d >=0 && %d >=0 && %d >=0 && %d >=0 && %d * 0.3 > MAX(%d, %d))\n", properBeg, properEnd, itsBasesInA, itsBasesInB, gapBasesInA,
gapBasesInB, overlapBases, gapBasesInA, gapBasesInB);
#endif
if (properBeg && properEnd && itsBasesInA >= 0 && itsBasesInB >= 0 && gapBasesInA >= 0 && gapBasesInB >= 0 && overlapBases * 0.3 > MAX(gapBasesInA, gapBasesInB))
{
#ifdef DEBUG
printf("FOUND PROPER CHAIN - INCLUDE ALL CHAIN OVLS FOR FORCEALIGN INPUT\n");
#endif
for (i = 0; i < novl; i++)
{
if (ovl[i].flags & OVL_DISCARD)
ctx->nDiscardOvls++;
else
ctx->nKeptOvls++;
}
}
else // multiple chains: discard all overlaps, i.e. no forcealign
{
for (i = 0; i < novl; i++)
{
ovl[i].flags |= OVL_DISCARD;
ctx->nDiscardOvls++;
}
}
}
else if (ctx->curChains > 1) // multiple chains: discard all overlaps, i.e. no forcealign
{
for (i = 0; i < novl; i++)
{
ovl[i].flags |= OVL_DISCARD;
ctx->nDiscardOvls++;
}
}
else // there is only one overlap !!! check this
{
int properBeg = (MIN(ovl->path.abpos, ovl->path.bbpos) < 1000);
int properEnd = (ovl->path.aepos + 1000 > DB_READ_LEN(ctx->db, ovl->aread) || ovl->path.bepos + 1000 > DB_READ_LEN(ctx->db, ovl->bread));
int realBeg = (MIN(ovl->path.abpos, ovl->path.bbpos) == 0);
int realEnd = (ovl->path.aepos == DB_READ_LEN(ctx->db, ovl->aread) || ovl->path.bepos == DB_READ_LEN(ctx->db, ovl->bread));
if ((properBeg && properEnd) && !(realBeg && realEnd))
{
#ifdef DEBUG
printf("FOUND PROPER SINGLE OVL - INCLUDE OVL FOR FORCEALIGN INPUT\n");
#endif
ctx->nKeptOvls++;
}
else
{
ovl->flags |= OVL_DISCARD;
ctx->nDiscardOvls++;
}
}
}
// reset chain and ovl counter
for (i = 0; i < ctx->curChains; i++)
ctx->ovlChains[i].novl = 0;
ctx->curChains = 0;
return 1;
}
static int separateDiscard_handler(void* _ctx, Overlap* ovl, int novl)
{
SeparateContext* ctx = (SeparateContext*) _ctx;
int i;
chain(ctx, ovl, novl);
if (ctx->type == 0) // separate for repcomp
{
if (ctx->curChains)
{
Chain *bestChain = ctx->ovlChains;
int properBeg = 0;
int properEnd = 0;
int gapBasesInA = 0;
int gapBasesInB = 0;
int itsBasesInA = 0;
int itsBasesInB = 0;
int overlapBases = 0;
// check for proper begin
if (MIN(bestChain->ovls[0]->path.abpos, bestChain->ovls[0]->path.bbpos) < 1000)
properBeg = 1;
// check for proper end
if (bestChain->ovls[bestChain->novl - 1]->path.aepos + 1000 > DB_READ_LEN(ctx->db, ovl->aread) || bestChain->ovls[bestChain->novl - 1]->path.bepos + 1000 > DB_READ_LEN(ctx->db, ovl->bread))
properEnd = 1;
#ifdef DEBUG
printf("properBeg: %d, properEnd %d\n", properBeg, properEnd);
#endif
if (properBeg && properEnd)
{
int i, its_a, its_b;
overlapBases = MAX(bestChain->ovls[0]->path.aepos - bestChain->ovls[0]->path.abpos, bestChain->ovls[0]->path.bepos - bestChain->ovls[0]->path.bbpos);
for (i = 1; i < bestChain->novl; i++)
{
its_a = its_b = 0;
overlapBases += MAX(bestChain->ovls[i]->path.aepos - bestChain->ovls[i]->path.abpos, bestChain->ovls[i]->path.bepos - bestChain->ovls[i]->path.bbpos);
// check for intersection in A
if (bestChain->ovls[i]->path.abpos < bestChain->ovls[i - 1]->path.aepos)
{
its_a = bestChain->ovls[i - 1]->path.aepos - bestChain->ovls[i]->path.abpos;
if (its_a > 1000)
{
itsBasesInA = -1;
break;
}
itsBasesInA += its_a;
}
// check for gap in A
else
{
int gap = bestChain->ovls[i]->path.abpos - bestChain->ovls[i - 1]->path.aepos;
// if (gap > 1000)
// {
// gapBasesInA = -1;
// break;
// }
gapBasesInA += gap;
}
// check for intersection in B
if (bestChain->ovls[i]->path.bbpos < bestChain->ovls[i - 1]->path.bepos)
{
its_b = bestChain->ovls[i - 1]->path.bepos - bestChain->ovls[i]->path.bbpos;
if (its_b > 1000)
{
itsBasesInB = -1;
break;
}
itsBasesInB += its_b;
}
// check for gap in B
else
{
int gap = bestChain->ovls[i]->path.bbpos - bestChain->ovls[i - 1]->path.bepos;
// if (gap > 1000)
// {
// gapBasesInB = -1;
// break;
// }
gapBasesInB += gap;
}
overlapBases -= MAX(its_a, its_b);
}
}
#ifdef DEBUG
printf("if(%d && %d && %d >=0 && %d >=0 && %d >=0 && %d >=0 && %d * 0.3 > MAX(%d, %d))\n", properBeg, properEnd, itsBasesInA, itsBasesInB, gapBasesInA,
gapBasesInB, overlapBases, gapBasesInA, gapBasesInB);
#endif
// if there is a proper chain between A and B reads, then discard all overlaps between A and B for the repcomp step, (otherwise do repcomp)
if (properBeg && properEnd && itsBasesInA >= 0 && itsBasesInB >= 0 && gapBasesInA >= 0 && gapBasesInB >= 0 && overlapBases * 0.3 > MAX(gapBasesInA, gapBasesInB))
{
#ifdef DEBUG
printf("FOUND PROPER CHAIN - EXCLUDE ALL OVLS FROM REPCOMP INPUT\n");
#endif
for (i = 0; i < novl; i++)
{
ovl[i].flags |= OVL_DISCARD;
}
}
else // reset all discard flags that were set during chain detection
{
for (i = 0; i < novl; i++)
{
if (ovl[i].flags & OVL_DISCARD)
{
ovl[i].flags &= ~OVL_DISCARD;
}
}
}
}
else // there is only one overlap !!! check this
{
int properBeg = (MIN(ovl->path.abpos, ovl->path.bbpos) < 1000);
int properEnd = (ovl->path.aepos + 1000 > DB_READ_LEN(ctx->db, ovl->aread) || ovl->path.bepos + 1000 > DB_READ_LEN(ctx->db, ovl->bread));
if (properBeg && properEnd)
{
#ifdef DEBUG
printf("FOUND PROPER SINGLE OVL - EXCLUDE OVL FROM REPCOMP INPUT\n");
#endif
ovl->flags |= OVL_DISCARD;
}
}
// revert flags
for (i = 0; i < novl; i++)
{
if (ovl[i].flags & OVL_DISCARD)
{
ovl[i].flags &= ~OVL_DISCARD;
ctx->nKeptOvls++;
}
else
{
ovl[i].flags |= (OVL_DISCARD);
ctx->nDiscardOvls++;
}
}
}
else if (ctx->type == 1) // separate for forcealign
{
if (ctx->curChains == 1) // ignore everything, where you have more then 1 chain
{
Chain *bestChain = ctx->ovlChains;
int properBeg = 0;
int properEnd = 0;
int gapBasesInA = 0;
int gapBasesInB = 0;
int itsBasesInA = 0;
int itsBasesInB = 0;
int overlapBases = 0;
// check for proper begin
if (MIN(bestChain->ovls[0]->path.abpos, bestChain->ovls[0]->path.bbpos) < 1000)
properBeg = 1;
// check for proper end
if (bestChain->ovls[bestChain->novl - 1]->path.aepos + 1000 > DB_READ_LEN(ctx->db, ovl->aread) || bestChain->ovls[bestChain->novl - 1]->path.bepos + 1000 > DB_READ_LEN(ctx->db, ovl->bread))
properEnd = 1;
#ifdef DEBUG
printf("properBeg: %d, properEnd %d\n", properBeg, properEnd);
#endif
// it could still be possible, that only a single alignment remained in the chain and all others were excluded
// if that happens we have check if that single alignment is fully proper, then there is no need to call forcealign for this!!!!
if (properBeg && properEnd)
{
if (bestChain->novl == 1)
{
int realBeg = (MIN(bestChain->ovls[0]->path.abpos, bestChain->ovls[0]->path.bbpos) == 0);
int realEnd = (bestChain->ovls[0]->path.aepos == DB_READ_LEN(ctx->db, bestChain->ovls[0]->aread) || bestChain->ovls[0]->path.bepos == DB_READ_LEN(ctx->db, bestChain->ovls[0]->bread));
if (realBeg && realEnd)
{
properBeg = 0;
}
}
else
{
int i, its_a, its_b;
overlapBases = MAX(bestChain->ovls[0]->path.aepos - bestChain->ovls[0]->path.abpos, bestChain->ovls[0]->path.bepos - bestChain->ovls[0]->path.bbpos);
for (i = 1; i < bestChain->novl; i++)
{
its_a = its_b = 0;
overlapBases += MAX(bestChain->ovls[i]->path.aepos - bestChain->ovls[i]->path.abpos, bestChain->ovls[i]->path.bepos - bestChain->ovls[i]->path.bbpos);
// check for intersection in A
if (bestChain->ovls[i]->path.abpos < bestChain->ovls[i - 1]->path.aepos)
{
its_a = bestChain->ovls[i - 1]->path.aepos - bestChain->ovls[i]->path.abpos;
if (its_a > 1000)
{
itsBasesInA = -1;
break;
}
itsBasesInA += its_a;
}
// check for gap in A
else
{
int gap = bestChain->ovls[i]->path.abpos - bestChain->ovls[i - 1]->path.aepos;
// if (gap > 1000)
// {
// gapBasesInA = -1;
// break;
// }
gapBasesInA += gap;
}
// check for intersection in B
if (bestChain->ovls[i]->path.bbpos < bestChain->ovls[i - 1]->path.bepos)
{
its_b = bestChain->ovls[i - 1]->path.bepos - bestChain->ovls[i]->path.bbpos;
if (its_b > 1000)
{
itsBasesInB = -1;
break;
}
itsBasesInB += its_b;
}
// check for gap in B
else
{
int gap = bestChain->ovls[i]->path.bbpos - bestChain->ovls[i - 1]->path.bepos;
// if (gap > 1000)
// {
// gapBasesInB = -1;
// break;
// }
gapBasesInB += gap;
}
overlapBases -= MAX(its_a, its_b);
}
}
}
#ifdef DEBUG
printf("if(%d && %d && %d >=0 && %d >=0 && %d >=0 && %d >=0 && %d * 0.3 > MAX(%d, %d))\n", properBeg, properEnd, itsBasesInA, itsBasesInB, gapBasesInA,
gapBasesInB, overlapBases, gapBasesInA, gapBasesInB);
#endif
if (properBeg && properEnd && itsBasesInA >= 0 && itsBasesInB >= 0 && gapBasesInA >= 0 && gapBasesInB >= 0 && overlapBases * 0.3 > MAX(gapBasesInA, gapBasesInB))
{
;
#ifdef DEBUG
printf("FOUND PROPER CHAIN - INCLUDE ALL CHAIN OVLS FOR FORCEALIGN INPUT\n");
#endif
}
else // multiple chains: discard all overlaps, i.e. no forcealign
{
for (i = 0; i < novl; i++)
{
ovl[i].flags |= OVL_DISCARD;
}
}
}
else if (ctx->curChains > 1) // multiple chains: discard all overlaps, i.e. no forcealign
{
for (i = 0; i < novl; i++)
{
ovl[i].flags |= OVL_DISCARD;
}
}
else // there is only one overlap !!! check this
{
int properBeg = (MIN(ovl->path.abpos, ovl->path.bbpos) < 1000);
int properEnd = (ovl->path.aepos + 1000 > DB_READ_LEN(ctx->db, ovl->aread) || ovl->path.bepos + 1000 > DB_READ_LEN(ctx->db, ovl->bread));
int realBeg = (MIN(ovl->path.abpos, ovl->path.bbpos) == 0);
int realEnd = (ovl->path.aepos == DB_READ_LEN(ctx->db, ovl->aread) || ovl->path.bepos == DB_READ_LEN(ctx->db, ovl->bread));
if ((properBeg && properEnd) && !(realBeg && realEnd))
{
;
#ifdef DEBUG
printf("FOUND PROPER SINGLE OVL - INCLUDE OVL FOR FORCEALIGN INPUT\n");
#endif
}
else
{
ovl->flags |= OVL_DISCARD;
}
}
// revert flags
for (i = 0; i < novl; i++)
{
if (ovl[i].flags & OVL_DISCARD)
{
ovl[i].flags &= ~OVL_DISCARD;
ctx->nKeptOvls++;
}
else
{
ovl[i].flags |= (OVL_DISCARD);
ctx->nDiscardOvls++;
}
}
}
// reset chain and ovl counter
for (i = 0; i < ctx->curChains; i++)
ctx->ovlChains[i].novl = 0;
ctx->curChains = 0;
return 1;
}
int main(int argc, char* argv[])
{
HITS_DB db;
SeparateContext sctx;
PassContext* pctx;
FILE* fileOvlIn;
FILE* fileOvlOut;
FILE* fileOvlOutDiscard;
bzero(&sctx, sizeof(SeparateContext));
sctx.db = &db;
// args
char* pcTrackRepeats = DEF_ARG_R;
int arg_purge = 1;
sctx.nMinAlnLength = -1;
sctx.nMinReadLength = -1;
sctx.nVerbose = 0;
sctx.useRLoader = 0;
int c;
opterr = 0;
while ((c = getopt(argc, argv, "vLo:l:r:T:")) != -1)
{
switch (c)
{
case 'L':
sctx.useRLoader = 1;
break;
case 'v':
sctx.nVerbose++;
break;
case 'o':
sctx.nMinAlnLength = atoi(optarg);
break;
case 'l':
sctx.nMinReadLength = atoi(optarg);
break;
case 'T':
sctx.type = atoi(optarg);
if (sctx.type < 0 || sctx.type > 1)
{
fprintf(stderr, "Unsupported type: %d\n", sctx.type);
exit(1);
}
break;
case 'r':
pcTrackRepeats = optarg;
break;
default:
fprintf(stderr, "unknown option %c\n", c);
usage();
exit(1);
}
}
if (argc - optind != 4)
{
usage();
exit(1);
}
char* pcPathReadsIn = argv[optind++];
char* pcPathOverlapsIn = argv[optind++];
char* pcPathOverlapsOut = argv[optind++];
char* pcPathOverlapsOutDiscard = argv[optind++];
if ((fileOvlIn = fopen(pcPathOverlapsIn, "r")) == NULL)
{
fprintf(stderr, "could not open %s\n", pcPathOverlapsIn);
exit(1);
}
if ((fileOvlOut = fopen(pcPathOverlapsOut, "w")) == NULL)
{
fprintf(stderr, "could not open %s\n", pcPathOverlapsOut);
exit(1);
}
if ((fileOvlOutDiscard = fopen(pcPathOverlapsOutDiscard, "w")) == NULL)
{
fprintf(stderr, "could not open %s\n", pcPathOverlapsOutDiscard);
exit(1);
}
if (Open_DB(pcPathReadsIn, &db))
{
fprintf(stderr, "could not open %s\n", pcPathReadsIn);
exit(1);
}
if (pcTrackRepeats)
{
sctx.trackRepeat = track_load(&db, pcTrackRepeats);
if (!sctx.trackRepeat)
{
fprintf(stderr, "could not load track %s\n", pcTrackRepeats);
exit(1);
}
}
// passes
if (sctx.useRLoader)
{
sctx.rl = rl_init(&db, 1);
pctx = pass_init(fileOvlIn, NULL);
pctx->data = &sctx;
pctx->split_b = 1;
pctx->load_trace = 0;
pass(pctx, loader_handler);
rl_load_added(sctx.rl);
pass_free(pctx);
}
pctx = pass_init(fileOvlIn, fileOvlOut);
pctx->split_b = 1;
pctx->load_trace = 1;
pctx->unpack_trace = 1;
pctx->data = &sctx;
pctx->write_overlaps = 1;
pctx->purge_discarded = arg_purge;
separate_pre(pctx, &sctx);
pass(pctx, separate_handler);
separate_post(&sctx);
int ninclude = sctx.nKeptOvls;
int nexclude = sctx.nDiscardOvls;
assert(sctx.nKeptOvls + sctx.nDiscardOvls == pctx->novl);
pass_free(pctx);
pctx = pass_init(fileOvlIn, fileOvlOutDiscard);
pctx->split_b = 1;
pctx->load_trace = 1;
pctx->unpack_trace = 1;
pctx->data = &sctx;
pctx->write_overlaps = 1;
pctx->purge_discarded = arg_purge;
separate_pre(pctx, &sctx);
pass(pctx, separateDiscard_handler); // invert discard flag
separate_post(&sctx);
assert((sctx.nKeptOvls == nexclude) && (sctx.nDiscardOvls == ninclude));
pass_free(pctx);
// cleanup
if (sctx.useRLoader)
{
rl_free(sctx.rl);
}
Close_DB(&db);
fclose(fileOvlOut);
fclose(fileOvlOutDiscard);
fclose(fileOvlIn);
return 0;
}
|
MartinPippel/DAmar
|
scrub/LAtrim.c
|
/*******************************************************************************************
*
* applies the trim track to an overlap file and realigns the trimmed ends to establish
* new trace points, bbpos and bepos
*
* Author : <NAME>
*
* Date : November 2014
*
*******************************************************************************************/
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <unistd.h>
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/pass.h"
#include "lib/read_loader.h"
#include "lib/tracks.h"
#include "lib/trim.h"
#include "lib/utils.h"
#include "dalign/align.h"
#include "db/DB.h"
// arguments
#define DEF_ARG_P 0
#define DEF_ARG_T TRACK_TRIM
// switches
#define VERBOSE
// trim context
typedef struct
{
HITS_DB* db; // database
HITS_TRACK* trackTrim;
Read_Loader* rl;
TRIM* trim;
} TrimContext;
// for getopt()
extern char* optarg;
extern int optind, opterr, optopt;
static void trim_pre( PassContext* pctx, TrimContext* tctx, Read_Loader* rl )
{
#ifdef VERBOSE
printf( ANSI_COLOR_GREEN "PASS trim\n" ANSI_COLOR_RESET );
#endif
tctx->trim = trim_init( tctx->db, pctx->twidth, tctx->trackTrim, rl );
}
static void trim_post( TrimContext* tctx, int verbose )
{
if ( verbose )
{
printf( "nOvls : %13lld nTrimOvls : %13lld\n", tctx->trim->nOvls, tctx->trim->nTrimmedOvls );
printf( "nOvlBases: %13lld nTrimBases: %13lld\n", tctx->trim->nOvlBases, tctx->trim->nTrimmedBases );
}
trim_close( tctx->trim );
}
static int trim_handler( void* _ctx, Overlap* ovl, int novl )
{
TrimContext* ctx = (TrimContext*)_ctx;
int i;
for ( i = 0; i < novl; i++ )
{
trim_overlap( ctx->trim, ovl + i );
}
return 1;
}
static int loader_handler( void* _ctx, Overlap* ovl, int novl )
{
TrimContext* ctx = (TrimContext*)_ctx;
Read_Loader* rl = ctx->rl;
int i;
for ( i = 0; i < novl; i++ )
{
int b = ovl[ i ].bread;
int trim_b_left, trim_b_right;
get_trim( ctx->db, ctx->trackTrim, b, &trim_b_left, &trim_b_right );
if ( ovl[ i ].flags & OVL_COMP )
{
int tmp = trim_b_left;
int blen = DB_READ_LEN( ctx->db, ovl[ i ].bread );
trim_b_left = blen - trim_b_right;
trim_b_right = blen - tmp;
}
if ( trim_b_left >= trim_b_right )
{
continue;
}
int bbt = MAX( trim_b_left, ovl[ i ].path.bbpos );
int bet = MIN( trim_b_right, ovl[ i ].path.bepos );
if ( bbt >= bet )
{
continue;
}
if ( bbt == ovl[ i ].path.bbpos && bet == ovl[ i ].path.bepos )
{
continue;
}
bbt = MAX( trim_b_left, ovl[ i ].path.bbpos );
bet = MIN( trim_b_right, ovl[ i ].path.bepos );
if ( bbt < bet && ( bbt != ovl[ i ].path.bbpos || bet != ovl[ i ].path.bepos ) )
{
rl_add( rl, ovl[ i ].aread );
rl_add( rl, ovl[ i ].bread );
continue;
}
int bepos = ovl[ i ].path.bepos;
if ( bepos > bet )
{
rl_add( rl, ovl[ i ].aread );
rl_add( rl, ovl[ i ].bread );
}
}
return 1;
}
static void usage()
{
fprintf( stderr, "usage: [-vpL] [-t <track>] <db> <overlaps.in> <overlaps.out>\n" );
fprintf( stderr, "options: -v ... verbose\n" );
fprintf( stderr, " -p ... purge discarded overlaps\n" );
fprintf( stderr, " -t ... trim track name (default: %s)\n", DEF_ARG_T );
fprintf( stderr, " -L ... two pass processing with read caching\n");
}
int main( int argc, char* argv[] )
{
HITS_DB db;
FILE* fileOvlIn;
FILE* fileOvlOut;
PassContext* pctx;
TrimContext tctx;
// process arguments
tctx.db = &db;
char* arg_track = DEF_ARG_T;
int arg_purge = DEF_ARG_P;
int arg_verbose = 0;
int arg_rloader = 0;
int c;
opterr = 0;
while ( ( c = getopt( argc, argv, "vpLt:" ) ) != -1 )
{
switch ( c )
{
case 'p':
arg_purge = 1;
break;
case 'v':
arg_verbose = 1;
break;
case 'L':
arg_rloader = 1;
break;
case 't':
arg_track = optarg;
break;
default:
usage();
exit( 1 );
}
}
if ( argc - optind != 3 )
{
usage();
exit( 1 );
}
char* pcPathReadsIn = argv[ optind++ ];
char* pcPathOverlapsIn = argv[ optind++ ];
char* pcPathOverlapsOut = argv[ optind++ ];
if ( Open_DB( pcPathReadsIn, &db ) )
{
fprintf( stderr, "could not open database '%s'\n", pcPathReadsIn );
exit( 1 );
}
if ( ( fileOvlIn = fopen( pcPathOverlapsIn, "r" ) ) == NULL )
{
fprintf( stderr, "could not open '%s'\n", pcPathOverlapsIn );
exit( 1 );
}
if ( ( fileOvlOut = fopen( pcPathOverlapsOut, "w" ) ) == NULL )
{
fprintf( stderr, "could not open '%s'\n", pcPathOverlapsOut );
exit( 1 );
}
tctx.trackTrim = track_load( &db, arg_track );
if ( tctx.trackTrim == NULL )
{
fprintf( stderr, "could not open trim track '%s'\n", arg_track );
exit( 1 );
}
tctx.db = &db;
if ( arg_rloader )
{
tctx.rl = rl_init( &db, 1 );
pctx = pass_init( fileOvlIn, NULL );
pctx->data = &tctx;
pctx->split_b = 1;
pctx->load_trace = 0;
pass( pctx, loader_handler );
rl_load_added( tctx.rl );
pass_free( pctx );
}
// trim
pctx = pass_init( fileOvlIn, fileOvlOut );
pctx->split_b = 0;
pctx->load_trace = 1;
pctx->unpack_trace = 1;
pctx->data = &tctx;
pctx->write_overlaps = 1;
pctx->purge_discarded = arg_purge;
trim_pre( pctx, &tctx, tctx.rl );
pass( pctx, trim_handler );
trim_post( &tctx, arg_verbose );
pass_free( pctx );
// cleanup
if ( arg_rloader )
{
rl_free( tctx.rl );
}
if ( db.tracks == NULL )
track_close( tctx.trackTrim );
Close_DB( &db );
fclose( fileOvlOut );
return 0;
}
|
MartinPippel/DAmar
|
lib.ext/fgetln.h
|
/*
fgetln is only available on bsd derived systems.
getline on the other hand is only in gnu libc derived systems.
if fgetln is missing emulate it using getline
*/
#include <stdio.h>
#if !defined(fgetln) && !HAVE_FGETLN
static char* fgetln_(FILE* stream, size_t* len)
{
static char* linep = NULL;
static size_t linecap = 0;
ssize_t length = getline(&linep, &linecap, stream);
if (length == -1)
{
free(linep);
linep = NULL;
linecap = 0;
length = 0;
}
if (len)
{
*len = length;
}
return linep;
}
#define fgetln fgetln_
#endif
|
MartinPippel/DAmar
|
touring/OGbuild.c
|
/*******************************************************************************************
*
* Builds the overlap graph
* (C implementation of build_og.py)
*
* Date : January 2016
*
* Author : <NAME>
*
*******************************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <sys/param.h>
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/pass.h"
#include "lib/tracks.h"
#include "lib/utils.h"
#include "db/DB.h"
#include "dalign/align.h"
// read status
#define STATUS_CONTAINED ( 1 << 0 )
#define STATUS_WIDOW ( 1 << 1 )
#define STATUS_PROPER ( 1 << 2 )
#define STATUS_USED ( 1 << 3 )
#define STATUS_OPTIONAL ( 1 << 4 )
// graph format
typedef enum { FORMAT_GML, FORMAT_GRAPHML, FORMAT_TGF } GraphFormat;
// contained edges sorting
typedef enum { EDGE_SORT_OVL, EDGE_SORT_OVH } OgEdgeSort;
// defaults
#define DEF_ARG_C 0
#define DEF_ARG_F "graphml"
#define DEF_ARG_P "ovl"
#define DEF_ARG_T TRACK_TRIM
// switches
#undef DEBUG_INSPECT
// used to store overlaps, basically a copy of everything we need from an Overlap struct
typedef struct
{
int a, b;
int ab, ae, bb, be;
int flags;
int ovh;
unsigned short diffs;
} OgEdge;
// maintains the state of the app
typedef struct
{
HITS_DB* db;
HITS_TRACK* trimtrack;
char *trimName;
// stats counters
uint64 stats_edges;
uint64 stats_redges;
uint64 stats_symdiscard;
uint64 stats_pedges_dropped;
// command line args
char* path_graph;
int contained;
int split;
GraphFormat gformat;
OgEdgeSort edgeprio;
// read -> component id
int* comp;
int ncomp;
// discard during second pass
int* discard;
int ndiscard;
int maxdiscard;
// read -> status
unsigned char* status;
uint64* nleft;
uint64* nright;
OgEdge* left;
OgEdge* right;
int* curleft;
int* curright;
} OgBuildContext;
// getopt
extern char* optarg;
extern int optind, opterr, optopt;
// graph output
static void print_graph_graphml_edge(FILE* f, OgEdge* e, char side)
{
int div = 100.0 * 2 * e->diffs / ( (e->ae - e->ab) + (e->be - e->bb) );
fprintf(f, " <edge source=\"%d\" target=\"%d\">\n", e->a, e->b);
fprintf(f, " <data key=\"length\">%d</data>\n", e->ovh);
fprintf(f, " <data key=\"flags\">%d</data>\n", e->flags);
fprintf(f, " <data key=\"divergence\">%d</data>\n", div);
fprintf(f, " <data key=\"end\">%c</data>\n", side);
fprintf(f, " </edge>\n");
}
static void print_graph_gml_edge(FILE* f, OgEdge* e, char side)
{
int div = 100.0 * 2 * e->diffs / ( (e->ae - e->ab) + (e->be - e->bb) );
fprintf(f, " edge [\n");
fprintf(f, " source %d\n", e->a);
fprintf(f, " target %d\n", e->b);
fprintf(f, " length %d\n", e->ovh);
fprintf(f, " flags %d\n", e->flags);
fprintf(f, " divergence %d\n", div);
fprintf(f, " end \"%c\"\n", side);
fprintf(f, " ]\n");
}
//
// TGF export
//
// we are using the label as storage for various additional values
// the standard format
//
// id_i label_i
// #
// id_j id_k label_edge_i
//
// turns into
//
// id_i optional_i left_edges_i right_edges_i
// #
// id_j id_k overhang_i flags_i divergence_i side_i
//
static void print_graph_tgf_edge(FILE* f, OgEdge* e, char side)
{
int div = 100.0 * 2 * e->diffs / ( (e->ae - e->ab) + (e->be - e->bb) );
fprintf(f, "%d %d %d %d %d %c\n", e->a, e->b, e->ovh, e->flags, div, side);
}
static void print_graph_tgf(OgBuildContext* octx, FILE* f, int component)
{
uint64* nleft = octx->nleft;
uint64* nright = octx->nright;
OgEdge* left = octx->left;
OgEdge* right = octx->right;
unsigned char* status = octx->status;
int* niedges = malloc(sizeof(int) * octx->db->nreads);
int* noedges = malloc(sizeof(int) * octx->db->nreads);
bzero(niedges, sizeof(int) * octx->db->nreads);
bzero(noedges, sizeof(int) * octx->db->nreads);
int aread;
for ( aread = 0; aread < octx->db->nreads; aread++ )
{
if ( !(status[aread] & STATUS_PROPER) )
{
continue;
}
if ( component != -1 && octx->comp[aread] != component )
{
continue;
}
int used = 0;
uint64 b = nleft[aread];
uint64 e = nleft[aread + 1];
while (b < e)
{
OgEdge* e = left + b;
int bread = e->b;
if ( (status[bread] & STATUS_PROPER) )
{
status[bread] |= STATUS_USED;
used = 1;
noedges[aread]++;
niedges[bread]++;
}
b++;
}
b = nright[aread];
e = nright[aread + 1];
while (b < e)
{
OgEdge* e = right + b;
int bread = e->b;
if ( (status[bread] & STATUS_PROPER) )
{
status[bread] |= STATUS_USED;
used = 1;
noedges[aread]++;
niedges[bread]++;
}
b++;
}
if (used)
{
status[aread] |= STATUS_USED;
}
}
for ( aread = 0; aread < octx->db->nreads; aread++ )
{
if ( !(status[aread] & STATUS_USED) )
{
continue;
}
int optional = (status[aread] & STATUS_OPTIONAL) ? 1 : 0;
fprintf(f, "%d %d %d %d\n", aread, optional, niedges[aread], noedges[aread]);
status[aread] ^= STATUS_USED;
}
fprintf(f, "#\n");
for ( aread = 0; aread < octx->db->nreads; aread++ )
{
if ( !(status[aread] & STATUS_PROPER) )
{
continue;
}
if ( component != -1 && octx->comp[aread] != component )
{
continue;
}
uint64 b = nleft[aread];
uint64 e = nleft[aread + 1];
while (b < e)
{
OgEdge* e = left + b;
if ( (status[e->b] & STATUS_PROPER) )
{
print_graph_tgf_edge(f, e, 'l');
}
b++;
}
b = nright[aread];
e = nright[aread + 1];
while (b < e)
{
OgEdge* e = right + b;
if ( (status[e->b] & STATUS_PROPER) )
{
print_graph_tgf_edge(f, e, 'r');
}
b++;
}
}
free(niedges);
free(noedges);
}
static void print_graph_gml(OgBuildContext* octx, FILE* f, const char* title, char** comments, int ncomments, int component)
{
fprintf(f, "graph [\n");
int i;
for ( i = 0; i < ncomments; i++ )
{
fprintf(f, " comment \"%s\"\n", comments[i]);
}
if (title)
{
fprintf(f, " label \"%s\"\n", title);
}
fprintf(f, " directed 1\n");
uint64* nleft = octx->nleft;
uint64* nright = octx->nright;
OgEdge* left = octx->left;
OgEdge* right = octx->right;
unsigned char* status = octx->status;
int aread;
for ( aread = 0; aread < octx->db->nreads; aread++ )
{
if ( !(status[aread] & STATUS_PROPER) )
{
continue;
}
if ( component != -1 && octx->comp[aread] != component )
{
continue;
}
int used = 0;
uint64 b = nleft[aread];
uint64 e = nleft[aread + 1];
while (b < e)
{
OgEdge* e = left + b;
if ( (status[e->b] & STATUS_PROPER) )
{
status[ e->b ] |= STATUS_USED;
print_graph_gml_edge(f, e, 'l');
used = 1;
}
b++;
}
b = nright[aread];
e = nright[aread + 1];
while (b < e)
{
OgEdge* e = right + b;
if ( (status[e->b] & STATUS_PROPER) )
{
status[ e->b ] |= STATUS_USED;
print_graph_gml_edge(f, e, 'r');
used = 1;
}
b++;
}
if (used)
{
status[aread] |= STATUS_USED;
}
}
for ( aread = 0; aread < octx->db->nreads; aread++ )
{
if ( !(status[aread] & STATUS_USED) )
{
continue;
}
int optional = (status[aread] & STATUS_OPTIONAL) ? 1 : 0;
fprintf(f, " node [\n");
fprintf(f, " id %d\n", aread);
fprintf(f, " read %d\n", aread);
fprintf(f, " optional %d\n", optional);
fprintf(f, " ]\n");
status[aread] ^= STATUS_USED;
}
fprintf(f, "]\n");
}
static void print_graph_graphml(OgBuildContext* octx, FILE* f, const char* title, char** comments, int ncomments, int component)
{
fprintf(f, "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
if (ncomments)
{
fprintf(f, "<!--\n");
int i;
for ( i = 0; i < ncomments; i++ )
{
fprintf(f, " %s\n", comments[i]);
}
fprintf(f, "-->\n");
}
fprintf(f, "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\"\n");
fprintf(f, " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
fprintf(f, " xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\">\n");
fprintf(f, " <key attr.name=\"length\" attr.type=\"int\" for=\"edge\" id=\"length\" />\n");
fprintf(f, " <key attr.name=\"flags\" attr.type=\"int\" for=\"edge\" id=\"flags\" />\n");
fprintf(f, " <key attr.name=\"end\" attr.type=\"string\" for=\"edge\" id=\"end\" />\n");
fprintf(f, " <key attr.name=\"divergence\" attr.type=\"int\" for=\"edge\" id=\"divergence\" />\n");
fprintf(f, " <key attr.name=\"read\" attr.type=\"int\" for=\"node\" id=\"read\" />\n");
fprintf(f, " <key attr.name=\"optional\" attr.type=\"int\" for=\"node\" id=\"optional\" />\n");
fprintf(f, " <graph id=\"%s\" edgedefault=\"directed\">\n", title);
uint64* nleft = octx->nleft;
uint64* nright = octx->nright;
OgEdge* left = octx->left;
OgEdge* right = octx->right;
unsigned char* status = octx->status;
int aread;
for ( aread = 0; aread < octx->db->nreads; aread++ )
{
if ( !(status[aread] & STATUS_PROPER) )
{
continue;
}
if ( component != -1 && octx->comp[aread] != component )
{
continue;
}
int used = 0;
uint64 b = nleft[aread];
uint64 e = nleft[aread + 1];
while (b < e)
{
OgEdge* e = left + b;
if ( (status[e->b] & STATUS_PROPER) )
{
status[ e->b ] |= STATUS_USED;
print_graph_graphml_edge(f, e, 'l');
used = 1;
}
b++;
}
b = nright[aread];
e = nright[aread + 1];
while (b < e)
{
OgEdge* e = right + b;
if ( (status[e->b] & STATUS_PROPER) )
{
status[ e->b ] |= STATUS_USED;
print_graph_graphml_edge(f, e, 'r');
used = 1;
}
b++;
}
if (used)
{
status[aread] |= STATUS_USED;
}
}
for ( aread = 0; aread < octx->db->nreads; aread++ )
{
if ( !(status[aread] & STATUS_USED) )
{
continue;
}
int optional = (status[aread] & STATUS_OPTIONAL) ? 1 : 0;
fprintf(f, " <node id=\"%d\">\n", aread);
fprintf(f, " <data key=\"read\">%d</data>\n", aread);
fprintf(f, " <data key=\"optional\">%d</data>\n", optional);
fprintf(f, " </node>\n");
status[aread] ^= STATUS_USED;
}
fprintf(f, " </graph>\n");
fprintf(f, "</graphml>\n");
}
// assign reads to components
static void assign_component(OgBuildContext* octx)
{
int nreads = octx->db->nreads;
int* comp = octx->comp;
unsigned char* status = octx->status;
int i;
for (i = 0; i < nreads; i++)
{
comp[i] = -1;
}
int maxstack = 1000;
int curstack = 0;
int curstack_new = 0;
int* stack = malloc( sizeof(int) * maxstack );
int* stack_new = malloc( sizeof(int) * maxstack );
int curcomp = 0;
OgEdge* left = octx->left;
OgEdge* right = octx->right;
uint64* nleft = octx->nleft;
uint64* nright = octx->nright;
// for all reads
int j;
for (j = 0; j < nreads; j++)
{
if ( comp[j] != -1 )
{
continue;
}
if ( !(status[j] & STATUS_PROPER) )
{
continue;
}
// initialize stack with read
stack[0] = j;
curstack = 1;
comp[j] = curcomp;
int empty = 1;
// keep going until stack exhausted
while (curstack)
{
for (i = 0; i < curstack; i++)
{
// get element from stack
int rid = stack[i];
uint64 b = nleft[ rid ];
uint64 e = nleft[ rid + 1 ];
// push reads to the left onto the new stack
while (b < e)
{
OgEdge* edge = left + b;
if ( comp[ edge->b ] == -1 && (status[edge->b] & STATUS_PROPER) )
{
comp[ edge->b ] = curcomp;
stack_new[curstack_new] = edge->b;
curstack_new++;
if (curstack_new == maxstack)
{
maxstack += 1000;
stack = realloc(stack, sizeof(int) * maxstack);
stack_new = realloc(stack_new, sizeof(int) * maxstack);
}
}
b++;
}
b = nright[ rid ];
e = nright[ rid + 1 ];
// push reads to the right onto the new stack
while (b < e)
{
OgEdge* edge = right + b;
if ( comp[ edge->b ] == -1 && (status[edge->b] & STATUS_PROPER) )
{
comp[ edge->b ] = curcomp;
stack_new[curstack_new] = edge->b;
curstack_new++;
if (curstack_new == maxstack)
{
maxstack += 1000;
stack = realloc(stack, sizeof(int) * maxstack);
stack_new = realloc(stack_new, sizeof(int) * maxstack);
}
}
b++;
}
}
// were we able to go somewhere (widowed nodes)
if (curstack_new > 0)
{
empty = 0;
}
// swap stacks
curstack = curstack_new;
curstack_new = 0;
int* temp = stack;
stack = stack_new;
stack_new = temp;
}
// dead node
if (empty)
{
comp[j] = -1;
}
else
{
curcomp++;
}
}
printf(" %d components\n", curcomp);
octx->ncomp = curcomp;
free(stack);
free(stack_new);
}
// sort OgEdge by .a and .b
static int cmp_ogedge(const void* a, const void* b)
{
OgEdge* x = (OgEdge*)a;
OgEdge* y = (OgEdge*)b;
int cmp = x->a - y->a;
if (cmp == 0)
{
cmp = x->b - y->b;
}
return cmp;
}
static int cmp_ogedge_ovh_rev(const void* a, const void* b)
{
OgEdge* x = (OgEdge*)a;
OgEdge* y = (OgEdge*)b;
return y->ovh - x->ovh;
}
static int cmp_ogedge_ovl_rev(const void* a, const void* b)
{
OgEdge* x = (OgEdge*)a;
OgEdge* y = (OgEdge*)b;
int xlen = x->ae - x->ab;
int ylen = y->ae - y->ab;
return ylen - xlen;
}
static int cmp_int(const void* a, const void* b)
{
int* x = (int*)a;
int* y = (int*)b;
return (*x) - (*y);
}
static int cmp_2int(const void* a, const void* b)
{
int* x = (int*)a;
int* y = (int*)b;
if ( x[0] == y[0] )
{
return x[1] - y[1];
}
return x[0] - y[0];
}
static int remove_dupes(OgEdge* e, int n)
{
int dropped = 0;
OgEdge* prev = e;
int i;
for ( i = 1; i < n; i++ )
{
OgEdge* cur = e + i;
if (cur->b == prev->b)
{
prev->a = -1;
prev->b = -1;
dropped++;
}
prev = cur;
}
return dropped;
}
static int remove_lr_dupes(OgEdge* l, int nl, OgEdge* r, int nr)
{
int dropped = 0;
int i;
for ( i = 0 ; i < nl ; i++)
{
OgEdge* le = l + i;
int j;
for ( j = 0 ; j < nr ; j++)
{
OgEdge* re = r + j;
if (le->b == re->b)
{
re->a = -1;
re->b = -1;
dropped += 1;
}
}
}
return dropped;
}
static void remove_parallel_edges(OgBuildContext* octx)
{
int64 dropped = 0;
int nreads = DB_NREADS(octx->db);
printf("parallel edges\n");
int rid;
for ( rid = 0; rid < nreads; rid++)
{
uint64 lb = octx->nleft[rid];
uint64 le = octx->nleft[rid + 1];
if ( lb < le )
{
dropped += remove_dupes(octx->left + lb, le - lb);
}
uint64 rb = octx->nright[rid];
uint64 re = octx->nright[rid + 1];
if ( rb < re )
{
dropped += remove_dupes(octx->right + rb, re - rb);
}
if ( lb < le && rb < re )
{
dropped += remove_lr_dupes(octx->left + lb, le - lb, octx->right + rb, re - rb);
}
}
printf(" %'lld parallel edges\n", dropped);
}
static int compress_graph_side(OgBuildContext* octx, OgEdge* edges, uint64* n)
{
int adj = 0;
int nreads = octx->db->nreads;
int rid;
for ( rid = 0 ; rid < nreads ; rid++ )
{
uint64 b = n[rid];
uint64 e = n[rid + 1];
n[rid] -= adj;
uint64 i;
for ( i = b ; i < e ; i++ )
{
OgEdge* edge = edges + i;
if (edge->a == -1 || edge->b == -1)
{
adj++;
}
else
{
edges[i - adj] = edges[i];
}
}
}
n[rid] -= adj;
return adj;
}
static void compress_graph(OgBuildContext* octx)
{
int dropped = 0;
int nreads = octx->db->nreads;
dropped += compress_graph_side(octx, octx->left, octx->nleft);
octx->left = realloc(octx->left, sizeof(OgEdge) * octx->nleft[nreads]);
dropped += compress_graph_side(octx, octx->right, octx->nright);
octx->right = realloc(octx->right, sizeof(OgEdge) * octx->nright[nreads]);
if (dropped > 0)
{
printf("removed %d edges\n", dropped);
}
}
static void sort_edges(OgBuildContext* octx)
{
printf("sorting edges\n");
int rid;
for ( rid = 0; rid < octx->db->nreads; rid++)
{
uint64 b = octx->nleft[rid];
uint64 e = octx->nleft[rid + 1];
qsort(octx->left + b, e - b, sizeof(OgEdge), cmp_ogedge);
b = octx->nright[rid];
e = octx->nright[rid + 1];
qsort(octx->right + b, e - b, sizeof(OgEdge), cmp_ogedge);
}
}
static int proper_edges(OgBuildContext* octx, OgEdge* edge, int n)
{
unsigned char* status = octx->status;
int cnt = 0;
int i;
for ( i = 0; i < n; i++ )
{
OgEdge* e = edge + i;
// DOUBLE-CHECK - OPTIONAL edges
if (e->flags & OVL_OPTIONAL)
{
continue;
}
assert( e->b != -1 );
if ( ( status[ e->b ] & STATUS_PROPER ) )
{
cnt++;
}
}
return cnt;
}
static void add_contained_edges(OgBuildContext* octx, int contained)
{
printf("adding contained edges (c = %d)\n", contained);
if (contained == -1)
{
contained = INT_MAX;
}
unsigned char* status = octx->status;
int nreads = octx->db->nreads;
OgEdge* left = octx->left;
OgEdge* right = octx->right;
uint64* nleft = octx->nleft;
uint64* nright = octx->nright;
int curinspect = 0;
int maxinspect = nreads;
int* inspect = malloc(sizeof(int) * maxinspect);
int* inspect_new = malloc(sizeof(int) * maxinspect);
int i;
for (i = 0; i < nreads; i++)
{
if (status[i] != STATUS_PROPER)
{
continue;
}
inspect[ curinspect ] = i;
curinspect++;
}
printf(" inspecting %'d proper reads\n", curinspect);
int round = 0;
while (curinspect > 0)
{
int curinspect_new = 0;
for ( i = 0; i < curinspect; i++)
{
int aread = inspect[i];
if (status[aread] != STATUS_PROPER)
{
continue;
}
uint64 b = nleft[aread];
uint64 e = nleft[aread + 1];
int left_nc = proper_edges(octx, left + b, e - b);
if (left_nc == 0)
{
if (octx->edgeprio == EDGE_SORT_OVH)
{
qsort(left + b, e - b, sizeof(OgEdge), cmp_ogedge_ovh_rev);
}
else if (octx->edgeprio == EDGE_SORT_OVL)
{
qsort(left + b, e - b, sizeof(OgEdge), cmp_ogedge_ovl_rev);
}
else
{
fprintf(stderr, "unknown edge priority mode %d\n", octx->edgeprio);
exit(1);
}
uint64 j;
int n;
for ( j = b, n = 0 ; j < e && n < contained ; j++ )
{
int bread = left[j].b;
// DOUBLE-CHECK - optional edges
if (left[j].flags & OVL_OPTIONAL)
{
continue;
}
#ifdef DEBUG_INSPECT
printf("INSPECT L %7d / %7d -> %7d OVH %7d %d\n", left[j].a, aread, bread, left[j].ovh, e - b);
#endif
status[bread] = STATUS_PROPER;
status[bread] |= STATUS_OPTIONAL;
inspect_new[curinspect_new] = bread;
curinspect_new++;
if (curinspect_new == maxinspect)
{
maxinspect = 1.2 * maxinspect + 1000;
inspect_new = realloc(inspect_new, sizeof(int) * maxinspect);
inspect = realloc(inspect, sizeof(int) * maxinspect);
}
n++;
}
}
b = nright[aread];
e = nright[aread + 1];
int right_nc = proper_edges(octx, right + b, e - b);
if (right_nc == 0)
{
if (octx->edgeprio == EDGE_SORT_OVH)
{
qsort(right + b, e - b, sizeof(OgEdge), cmp_ogedge_ovh_rev);
}
else if (octx->edgeprio == EDGE_SORT_OVL)
{
qsort(right + b, e - b, sizeof(OgEdge), cmp_ogedge_ovl_rev);
}
else
{
fprintf(stderr, "unknown edge priority mode %d\n", octx->edgeprio);
exit(1);
}
uint64 j;
int n;
for ( j = b, n = 0 ; j < e && n < contained ; j++ )
{
int bread = right[j].b;
// DOUBLE-CHECK - optional edges
if (right[j].flags & OVL_OPTIONAL)
{
continue;
}
#ifdef DEBUG_INSPECT
printf("INSPECT R %7d / %7d -> %7d OVH %7d %d\n", right[j].a, aread, bread, right[j].ovh, e - b);
#endif
status[bread] = STATUS_PROPER;
status[bread] |= STATUS_OPTIONAL;
inspect_new[curinspect_new] = bread;
curinspect_new++;
if (curinspect_new == maxinspect)
{
maxinspect = 1.2 * maxinspect + 1000;
inspect_new = realloc(inspect_new, sizeof(int) * maxinspect);
inspect = realloc(inspect, sizeof(int) * maxinspect);
}
n++;
}
}
}
qsort(inspect_new, curinspect_new, sizeof(int), cmp_int);
curinspect = curinspect_new;
int* temp = inspect;
inspect = inspect_new;
inspect_new = temp;
round++;
if (curinspect > 0)
{
printf(" set %d reads to proper\n", curinspect);
}
}
free(inspect);
free(inspect_new);
}
/*
static int reduce_edges(OgBuildContext* octx)
{
unsigned char* status = octx->status;
int nreads = octx->db->nreads;
int dropped = 0;
printf("left edges %llu\nright edges %llu\n", octx->nleft[nreads], octx->nright[nreads]);
uint64 i;
for ( i = 0; i < octx->nleft[nreads]; i++)
{
OgEdge* e = octx->left + i;
assert( e->a >= 0 && e->b >= 0 );
if ( status[e->b] == STATUS_CONTAINED )
{
e->a = -1;
e->b = -1;
dropped++;
}
}
for ( i = 0; i < octx->nright[nreads]; i++)
{
OgEdge* e = octx->right + i;
assert( e->a >= 0 && e->b >= 0 );
if ( status[e->b] == STATUS_CONTAINED )
{
e->a = -1;
e->b = -1;
dropped++;
}
}
return dropped;
}
*/
static void write_graph(OgBuildContext* octx, const char* path)
{
if (octx->split)
{
char* pathcomp = malloc( strlen(path) + 30 );
int i;
for (i = 0; i < octx->ncomp; i++)
{
char* ext;
if (octx->gformat == FORMAT_GML)
{
ext = "gml";
}
else if (octx->gformat == FORMAT_TGF)
{
ext = "tgf";
}
else
{
ext = "graphml";
}
sprintf(pathcomp, "%s_%05d.%s", path, i, ext);
FILE* f = fopen(pathcomp, "w");
if (f)
{
if (octx->gformat == FORMAT_GML)
{
print_graph_gml(octx, f, "og", NULL, 0, i);
}
else if (octx->gformat == FORMAT_TGF)
{
print_graph_tgf(octx, f, i);
}
else
{
print_graph_graphml(octx, f, "og", NULL, 0, i);
}
fclose(f);
}
else
{
fprintf(stderr, "failed to create %s\n", pathcomp);
}
}
free(pathcomp);
}
else
{
FILE* f = fopen(path, "w");
if (f)
{
if (octx->gformat == FORMAT_GML)
{
print_graph_gml(octx, f, "og", NULL, 0, -1);
}
else if (octx->gformat == FORMAT_TGF)
{
print_graph_tgf(octx, f, -1);
}
else
{
print_graph_graphml(octx, f, "og", NULL, 0, -1);
}
fclose(f);
}
else
{
fprintf(stderr, "failed to create %s\n", path);
}
}
}
static void post_build(OgBuildContext* octx)
{
printf(" %'llu edges\n", octx->stats_edges);
printf(" %'llu redges\n", octx->stats_redges);
printf(" %'llu symmetric discards\n", octx->stats_symdiscard);
sort_edges(octx);
remove_parallel_edges(octx);
compress_graph(octx);
if (octx->contained != 0)
{
add_contained_edges(octx, octx->contained);
}
compress_graph(octx);
if (octx->split)
{
printf("components\n");
assign_component(octx);
}
write_graph(octx, octx->path_graph);
free(octx->nleft);
free(octx->nright);
free(octx->left);
free(octx->right);
free(octx->curleft);
free(octx->curright);
free(octx->status);
free(octx->comp);
}
static void drop_parallel_edges(Overlap* ovls, int novl)
{
int i = 0;
while (i < novl - 1)
{
if ( ovls[i].flags & OVL_DISCARD )
{
i += 1;
continue ;
}
int j = i + 1;
if ( ovls[i].bread == ovls[j].bread )
{
int dropped = 0;
for ( ; j < novl && ovls[i].bread == ovls[j].bread ; j++ )
{
if ( ovls[j].flags & OVL_DISCARD )
{
continue;
}
ovls[j].flags |= OVL_DISCARD;
dropped += 1;
}
if (dropped > 0)
{
ovls[i].flags |= OVL_DISCARD;
dropped += 1;
}
// ctx->filtered_parallel_edges += dropped;
}
i = j;
}
}
static void assign_edge(OgEdge* edge, Overlap* ovl)
{
edge->a = ovl->aread;
edge->b = ovl->bread;
edge->flags = ovl->flags;
edge->diffs = ovl->path.diffs;
edge->ovh = -1;
edge->ab = ovl->path.abpos;
edge->ae = ovl->path.aepos;
edge->bb = ovl->path.bbpos;
edge->be = ovl->path.bepos;
}
static void assign_edge_reversed(OgEdge* edge, Overlap* ovl, int alen, int blen)
{
edge->a = ovl->bread;
edge->b = ovl->aread;
edge->flags = ovl->flags;
edge->diffs = ovl->path.diffs;
edge->ovh = -1;
if (ovl->flags & OVL_COMP)
{
edge->ab = blen - ovl->path.bepos;
edge->ae = blen - ovl->path.bbpos;
edge->bb = alen - ovl->path.aepos;
edge->be = alen - ovl->path.abpos;
}
else
{
edge->ab = ovl->path.bbpos;
edge->ae = ovl->path.bepos;
edge->bb = ovl->path.abpos;
edge->be = ovl->path.aepos;
}
}
static int handler_build(void* _ctx, Overlap* ovls, int novl)
{
OgBuildContext* octx = (OgBuildContext*)_ctx;
unsigned char* status = octx->status;
uint64 edges = 0;
uint64 redges = 0;
uint64 symdiscard = 0;
uint64* nleft = octx->nleft;
OgEdge* left = octx->left;
int* curleft = octx->curleft;
uint64* nright = octx->nright;
OgEdge* right = octx->right;
int* curright = octx->curright;
int aread = ovls->aread;
int trim_ab, trim_ae;
int alen = DB_READ_LEN(octx->db, aread);
drop_parallel_edges(ovls, novl);
get_trim(octx->db, octx->trimtrack, aread, &trim_ab, &trim_ae);
int i;
for ( i = 0; i < novl; i++ )
{
Overlap* ovl = ovls + i;
if (ovl->aread == ovl->bread)
{
continue;
}
int ab = ovl->path.abpos;
int ae = ovl->path.aepos;
if (ab == trim_ab && ae == trim_ae)
{
status[aread] = STATUS_CONTAINED;
continue;
}
int bread = ovl->bread;
int blen = DB_READ_LEN(octx->db, bread);
int trim_bb, trim_be;
get_trim(octx->db, octx->trimtrack, bread, &trim_bb, &trim_be);
if ( ovl->flags & OVL_COMP )
{
int t = trim_bb;
trim_bb = blen - trim_be;
trim_be = blen - t;
}
int bb = ovl->path.bbpos;
int be = ovl->path.bepos;
if ( bb == trim_bb && be == trim_be )
{
status[bread] = STATUS_CONTAINED;
continue;
}
if ( (ovl->flags & OVL_DISCARD) || (ovl->flags & OVL_SYMDISCARD) )
{
continue;
}
int j = octx->db->reads[aread].flags;
if ( j != -1 )
{
int discard = 0;
for ( j = 0; j < octx->ndiscard; j += 2)
{
int a_disc = octx->discard[j];
int b_disc = octx->discard[j + 1];
if ( a_disc > aread )
{
break;
}
if ( bread == b_disc )
{
discard = 1;
break;
}
}
if (discard)
{
// printf("sym-discard %d -> %d\n", aread, bread);
symdiscard += 1;
continue;
}
}
if ( ab == trim_ab )
{
int ovh = bb - trim_bb;
if (ovh <= 0)
{
if (ovh < 0)
{
fprintf(stderr, "error: ovh %5d <= 0 %7d -> %7d. Trim track most likely incompatible with overlaps.\n", ovh, aread, bread);
exit(1);
}
}
else
{
OgEdge* edge = left + nleft[aread] + curleft[aread];
assign_edge(edge, ovl);
edge->ovh = ovh;
curleft[aread]++;
edges++;
if ( ae < trim_ae )
{
if ( ovl->flags & OVL_COMP )
{
edge = left + nleft[bread] + curleft[bread];
curleft[bread]++;
}
else
{
edge = right + nright[bread] + curright[bread];
curright[bread]++;
}
if (status[bread] == STATUS_WIDOW)
{
status[bread] = STATUS_PROPER;
}
assign_edge_reversed(edge, ovl, alen, blen);
edge->ovh = trim_ae - ae;
redges++;
}
}
}
if ( ae == trim_ae )
{
int ovh = trim_be - be;
if ( ovh <= 0 )
{
if (ovh < 0)
{
fprintf(stderr, "error: ovh %5d <= 0 %7d -> %7d. Trim track most likely incompatible with overlaps.\n", ovh, aread, bread);
exit(1);
}
}
else
{
OgEdge* edge = right + nright[aread] + curright[aread];
assign_edge(edge, ovl);
edge->ovh = ovh;
curright[aread]++;
edges++;
if ( ab > trim_ab )
{
if ( ovl->flags & OVL_COMP )
{
edge = right + nright[bread] + curright[bread];
curright[bread]++;
}
else
{
edge = left + nleft[bread] + curleft[bread];
curleft[bread]++;
}
if (status[bread] == STATUS_WIDOW)
{
status[bread] = STATUS_PROPER;
}
assign_edge_reversed(edge, ovl, alen, blen);
edge->ovh = ab - trim_ab;
redges++;
}
}
}
}
if ( status[aread] == STATUS_WIDOW && edges > 0 )
{
status[aread] = STATUS_PROPER;
}
octx->stats_symdiscard += symdiscard;
octx->stats_edges += edges;
octx->stats_redges += redges;
return 1;
}
// initialize data structures for pass(es)
static void pre_build(PassContext* pctx, OgBuildContext* octx)
{
UNUSED(pctx);
HITS_DB* db = octx->db;
int nreads = db->nreads;
octx->trimtrack = track_load(db, octx->trimName);
if (!octx->trimtrack)
{
fprintf(stderr, "ERROR: failed to open %s\n", octx->trimName);
exit(1);
}
octx->status = malloc( nreads );
int i;
for ( i = 0; i < nreads; i++)
{
octx->status[i] = STATUS_WIDOW;
}
octx->nleft = calloc( nreads + 1, sizeof(uint64) );
octx->nright = calloc( nreads + 1, sizeof(uint64) );
octx->curleft = calloc( nreads, sizeof(int) );
octx->curright = calloc( nreads, sizeof(int) );
octx->comp = malloc( sizeof(int) * nreads );
}
static int handler_count(void* _ctx, Overlap* ovls, int novl)
{
OgBuildContext* octx = (OgBuildContext*)_ctx;
uint64* nleft = octx->nleft;
uint64* nright = octx->nright;
int aread = ovls->aread;
int trim_ab, trim_ae;
// int alen = DB_READ_LEN(octx->db, aread);
drop_parallel_edges(ovls, novl);
get_trim(octx->db, octx->trimtrack, aread, &trim_ab, &trim_ae);
int i;
for ( i = 0; i < novl; i++ )
{
Overlap* ovl = ovls + i;
if (ovl->aread == ovl->bread)
{
continue;
}
if ( ovl->flags & OVL_SYMDISCARD )
{
if (octx->ndiscard + 2 >= octx->maxdiscard)
{
octx->maxdiscard = octx->maxdiscard * 1.2 + 100;
octx->discard = realloc(octx->discard, sizeof(int) * octx->maxdiscard);
}
octx->discard[ octx->ndiscard ] = ovl->bread;
octx->discard[ octx->ndiscard + 1 ] = ovl->aread;
octx->ndiscard += 2;
}
if ( (ovl->flags & OVL_DISCARD) )
{
continue;
}
int ab = ovl->path.abpos;
int ae = ovl->path.aepos;
if (ab == trim_ab && ae == trim_ae)
{
continue;
}
int bread = ovl->bread;
int blen = DB_READ_LEN(octx->db, bread);
int trim_bb, trim_be;
get_trim(octx->db, octx->trimtrack, bread, &trim_bb, &trim_be);
if ( ovl->flags & OVL_COMP )
{
int t = trim_bb;
trim_bb = blen - trim_be;
trim_be = blen - t;
}
int bb = ovl->path.bbpos;
int be = ovl->path.bepos;
if ( bb == trim_bb && be == trim_be )
{
continue;
}
if ( ab == trim_ab )
{
int ovh = bb - trim_bb;
if (ovh <= 0)
{
if (ovh < 0)
{
fprintf(stderr, "error: ovh %5d <= 0 %7d -> %7d. Trim track most likely incompatible with overlaps.\n", ovh, aread, bread);
}
}
else
{
nleft[aread]++;
if ( ae < trim_ae )
{
if ( ovl->flags & OVL_COMP )
{
nleft[bread]++;
}
else
{
nright[bread]++;
}
}
}
}
if ( ae == trim_ae )
{
int ovh = trim_be - be;
if ( ovh <= 0 )
{
if (ovh < 0)
{
fprintf(stderr, "error: ovh %5d <= 0 %7d -> %7d. Trim track most likely incompatible with overlaps.\n", ovh, aread, bread);
}
}
else
{
nright[aread]++;
if ( ab > trim_ab )
{
if ( ovl->flags & OVL_COMP )
{
nright[bread]++;
}
else
{
nleft[bread]++;
}
}
}
}
}
return 1;
}
static uint64 to_offsets(uint64* counts, int n)
{
uint64 off = 0;
int i;
for (i = 0; i < n; i++)
{
uint64 coff = counts[i];
counts[i] = off;
off += coff;
}
counts[i] = off;
return counts[i];
}
static void post_count(OgBuildContext* octx)
{
HITS_DB* db = octx->db;
qsort(octx->discard, octx->ndiscard / 2, 2 * sizeof(int), cmp_2int);
int i;
for ( i = 0; i < DB_NREADS(octx->db); i++ )
{
octx->db->reads[i].flags = -1;
}
for ( i = 0; i < octx->ndiscard; i += 2 )
{
int rid = octx->discard[i];
octx->db->reads[ rid ].flags = i;
}
int needed;
needed = to_offsets(octx->nleft, db->nreads);
octx->left = calloc( needed, sizeof(OgEdge) );
printf("%d left edges\n", needed);
needed = to_offsets(octx->nright, db->nreads);
octx->right = calloc( needed, sizeof(OgEdge) );
printf("%d right edges\n", needed);
}
static void usage()
{
printf( "usage: [-s] [-c <int>] [-t <track>] [-f gml|graphml|tgf] [-p ovl|ovh] database input.las output.format\n\n" );
printf( "Builds the overlap graph based on the alignments in the input las file.\n\n" );
printf( "options: -c n try to add otherwise containted reads to dead ends in the graph\n" );
printf( " 0 disabled, >0 maximum number of edges, -1 all edges (default %d)\n", DEF_ARG_C );
printf( " -p mode which edges should be added when running in -c mode (default %s)\n" , DEF_ARG_P);
printf( " ovl longest overlap, ovh longer overhang\n" );
printf( " -f frmt output graph format. gml, graphml or tgf (default %s)\n", DEF_ARG_F );
printf( " -s write on file for each component of the overlap graph.\n" );
printf( " files are named output.<component.number>.format\n" );
printf( " -t track which trim track to use (%s)\n", DEF_ARG_T );
}
int main(int argc, char* argv[])
{
HITS_DB db;
FILE* fileOvlIn;
PassContext* pctx;
OgBuildContext octx;
bzero(&octx, sizeof(OgBuildContext));
// process arguments
char* edgeprio = DEF_ARG_P;
char* gformat = DEF_ARG_F;
octx.contained = DEF_ARG_C;
octx.trimName = DEF_ARG_T;
opterr = 0;
int c;
while ((c = getopt(argc, argv, "sc:f:p:t:")) != -1)
{
switch (c)
{
case 'p':
edgeprio = optarg;
break;
case 'f':
gformat = optarg;
break;
case 's':
octx.split = 1;
break;
case 't':
octx.trimName = optarg;
break;
case 'c':
octx.contained = atoi(optarg);
break;
default:
usage();
exit(1);
}
}
if (argc - optind < 3)
{
usage();
exit(1);
}
char* pcPathReadsIn = argv[optind++];
char* pcPathOverlaps = argv[optind++];
octx.path_graph = argv[optind++];
if ( strcmp(gformat, "gml") == 0 )
{
octx.gformat = FORMAT_GML;
}
else if ( strcmp(gformat, "graphml") == 0 )
{
octx.gformat = FORMAT_GRAPHML;
}
else if ( strcmp(gformat, "tgf") == 0 )
{
octx.gformat = FORMAT_TGF;
}
else
{
fprintf(stderr, "error: unknown graph format %s\n", gformat);
usage();
exit(1);
}
if ( strcmp(edgeprio, "ovh") == 0 )
{
octx.edgeprio = EDGE_SORT_OVH;
}
else if ( strcmp(edgeprio, "ovl") == 0 )
{
octx.edgeprio = EDGE_SORT_OVL;
}
else
{
fprintf(stderr, "error: unknown edge priority %s\n", edgeprio);
usage();
exit(1);
}
if ( (fileOvlIn = fopen(pcPathOverlaps, "r")) == NULL )
{
fprintf(stderr, "could not open '%s'\n", pcPathOverlaps);
exit(1);
}
if (Open_DB(pcPathReadsIn, &db))
{
fprintf(stderr, "could not open '%s'\n", pcPathReadsIn);
exit(1);
}
if (octx.contained < -1)
{
fprintf(stderr, "unvalid value %d for -c\n", octx.contained);
exit(1);
}
// init
octx.db = &db;
pctx = pass_init(fileOvlIn, NULL);
pctx->split_b = 0;
pctx->load_trace = 0;
pctx->progress = 1;
pctx->data = &octx;
// pass
pre_build(pctx, &octx);
printf(ANSI_COLOR_GREEN "PASS - calculating memory requirements" ANSI_COLOR_RESET "\n");
pass(pctx, handler_count);
post_count(&octx);
printf(ANSI_COLOR_GREEN "PASS - building graph" ANSI_COLOR_RESET "\n");
octx.stats_pedges_dropped = 0;
pass(pctx, handler_build);
printf(ANSI_COLOR_GREEN "processing graph" ANSI_COLOR_RESET "\n");
post_build(&octx);
// cleanup
Close_DB(&db);
pass_free(pctx);
fclose(fileOvlIn);
return 0;
}
|
MartinPippel/DAmar
|
lib/compression.c
|
<gh_stars>10-100
#include <zlib.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "utils.h"
#define ULONG_MAX 0xFFFFFFFFUL
#undef DEBUG_COMPRESSION
#define COMPRESS_MAX_CHUNK ( 8 * 1024 * 1024 )
void compress_chunks(void* ibuf, uint64_t ilen, void** _obuf, uint64_t* _olen)
{
#ifdef DEBUG_COMPRESSION
printf("compress_chunks: ilen %lu\n", ilen);
#endif
uLongf chunk = COMPRESS_MAX_CHUNK;
uint64_t omax = ilen * 1.02 + 12 + sizeof(uint64_t) * ( ilen / chunk + 1 );
void* obuf = malloc(omax);
if(obuf == NULL)
{
printf("[ERROR] compress_chunks: Could not allocate obuf of size: %lu\n", omax);
exit(1);
}
void* ocur = obuf;
void* icur = ibuf;
#ifdef DEBUG_COMPRESSION
printf("compress_chunks ilen %" PRIu64 " omax %" PRIu64 "\n", ilen, omax);
#endif
while ( ilen != 0 )
{
if ( chunk > ilen )
{
chunk = ilen;
}
if(omax < (ocur - obuf))
{
printf("omax: %lu is smaller then chunk size %lu!!!\n", omax, (ocur - obuf));
}
#ifdef DEBUG_COMPRESSION
printf("cchunk: %lu, omax: %lu, ocur: %p, obuf: %p, ilen: %lu, chunk: %lu\n", omax - (ocur - obuf), omax, ocur, obuf, ilen, chunk);
#endif
uLongf cchunk;
if (omax - (ocur - obuf) >= ULONG_MAX)
{
cchunk=ULONG_MAX/2;
}
else
{
cchunk = omax - (ocur - obuf);
}
compress(ocur + sizeof(uint64_t), &cchunk, icur, chunk);
#ifdef DEBUG_COMPRESSION
printf("compressed chunk of %lu to %lu\n", chunk, cchunk);
#endif
*((uint64_t*)ocur) = cchunk;
ocur += cchunk + sizeof(uint64_t);
icur += chunk;
ilen -= chunk;
}
*_obuf = obuf;
*_olen = ocur - obuf;
// return ( ocur - obuf );
}
void uncompress_chunks(void* ibuf, uint64_t ilen, void* obuf, uint64_t olen)
{
UNUSED(olen);
void* icur = ibuf;
void* ocur = obuf;
#ifdef DEBUG_COMPRESSION
printf("uncompress_chunks ilen = %" PRIu64 "\n", ilen);
#endif
while ( (uint64_t)(icur - ibuf) != ilen )
{
uLongf clen = *((uint64_t*)icur);
// uLongf destlen = olen - (ocur - obuf);
uLongf destlen = COMPRESS_MAX_CHUNK;
#ifdef DEBUG_COMPRESSION
printf("uncompress %lu into %" PRIu64 " %ld", clen, olen, destlen);
#endif
uncompress(ocur, &destlen, icur + sizeof(uint64_t), clen);
#ifdef DEBUG_COMPRESSION
printf(" to %lu\n", destlen);
#endif
icur += sizeof(uint64_t) + clen;
ocur += destlen;
}
}
#ifdef DEBUG_COMPRESSION
void test_chunks()
{
/* TESTING - BEGIN */
uint64_t bmax = 1024 * 1024 * 10;
uint64_t* buf = malloc(sizeof(uint64_t) * bmax);
uint64_t* cbuf = NULL;
uint64_t clen = 0;
bzero(buf, sizeof(uint64_t) * bmax);
uint64_t i;
for ( i = 0 ; i < bmax ; i++ )
{
buf[i] = i;
}
compress_chunks(buf, sizeof(uint64_t) * bmax, (void*)&cbuf, &clen);
printf("clen = %" PRIu64 "\n", clen);
printf("compressed to %d%%\n", (int)(100.0 * clen / (sizeof(uint64_t) * bmax)) );
bzero(buf, sizeof(uint64_t) * bmax);
uncompress_chunks(cbuf, clen, buf, sizeof(uint64_t) * bmax);
for ( i = 0 ; i < bmax ; i++ )
{
if (buf[i] != i)
{
printf("buf[%" PRIu64 "] = %" PRIu64 "\n", i, buf[i]);
}
}
}
#endif
|
MartinPippel/DAmar
|
lib.ext/types.h
|
<reponame>MartinPippel/DAmar<filename>lib.ext/types.h
/* "types.h" */
/*
IMPORTANT NOTE: This is part of the code that appeared in
Dr. Dobb's Journal issue #233 (August 1995)
Volume 20 Issue 8
in an article entitled `Implementing Bit Vectors in C'
by <NAME>
Pages 42, 44, 46 (article) and pages 96, 98-100 (code)
The code is (c) copyright 1995 by <NAME>, Inc.
See "bitarr.c" for further details.
*/
#pragma once
#include <stddef.h>
typedef enum bool {FALSE, TRUE} bool;
typedef size_t elem_t;
typedef unsigned char bit;
typedef char * string;
|
MartinPippel/DAmar
|
lib/utils.h
|
#pragma once
#include <inttypes.h>
#include "db/DB.h"
#define UNUSED(x) (void)(x)
int fread_integers(FILE* fileIn, int** out_values, int* out_nvalues);
int intersect(int ab, int ae, int bb, int be);
void get_trim(HITS_DB* db, HITS_TRACK* trimtrack, int rid, int* b, int* e);
void wrap_write(FILE* fileOut, char* seq, int len, int width);
void revcomp(char* c, int len);
void rev(char* c, int len);
char* format_bytes(unsigned long bytes);
char* bp_format(uint64_t num, int dec);
char* bp_format_alloc(uint64_t num, int dec, int alloc);
uint64_t bp_parse(const char* num);
#if !defined( fgetln )
char* fgetln_( FILE* stream, size_t* len );
#define fgetln fgetln_
#endif
|
MartinPippel/DAmar
|
lib/pass.h
|
#pragma once
#include <sys/types.h>
#include "db/DB.h"
#include "dalign/align.h"
#define DB_READ_FLAGS(db, rid) ( (db)->reads[ (rid) ].flags )
#define DB_READ_LEN(db, rid) ( (db)->reads[ (rid) ].rlen )
#define READ_LEN(r) ( (r)->rlen )
#define DB_READ_MAXLEN(db) ( (db)->maxlen )
#define DB_NREADS(db) ( (db)->nreads )
//#define DB_READ_ID(db, rid) ( (db)->reads[ (rid) ].id )
#define TBYTES(twidth) ( (twidth) <= TRACE_XOVR ? sizeof(uint8) : sizeof(uint16) )
#define OVERLAP_IO_SIZE (sizeof(Overlap) - sizeof(void*))
typedef uint64 ovl_header_novl;
typedef int ovl_header_twidth;
typedef uint16 ovl_trace;
typedef struct
{
// overlaps and trace
FILE* fileOvlIn;
FILE* fileOvlOut;
ovl_header_twidth twidth;
ovl_header_novl novl; // number of overlaps reads in
ovl_header_novl novl_out; // written out
ovl_header_novl novl_out_discarded; // written out with OVL_DISCARD flag
long sizeOvlIn;
long progress_tick;
long progress_nexttick;
off_t off_start;
off_t off_end;
uint64 tmax;
uint64 tcur;
ovl_trace* trace;
size_t tbytes;
// user supplied data
void* data;
// pass settings
int split_b;
int load_trace;
int unpack_trace;
int write_overlaps;
int purge_discarded;
int progress;
} PassContext;
typedef int (*pass_handler)(void*, Overlap*, int);
PassContext* pass_init(FILE* fileOvlIn, FILE* fileOvlOut);
void pass(PassContext* ctx, pass_handler handler);
void pass_free(PassContext* ctx);
void read_unpacked_trace(FILE* fileOvl, Overlap* ovl, size_t tbytes);
int ovl_header_read(FILE* fileOvl, ovl_header_novl* novl, ovl_header_twidth* twidth);
void ovl_header_write(FILE* fileOvl, ovl_header_novl novl, ovl_header_twidth twidth);
|
MartinPippel/DAmar
|
db/DBshow.c
|
<gh_stars>10-100
/************************************************************************************\
* *
* Copyright (c) 2014, Dr. <NAME> (EWM). 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. *
* *
* · The name of EWM may not be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY EWM ”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 EWM 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. *
* *
* For any issues regarding this software and its use, contact EWM at: *
* *
* <NAME>. *
* Bautzner Str. 122e *
* 01099 Dresden *
* GERMANY *
* Email: <EMAIL> *
* *
\************************************************************************************/
/*******************************************************************************************
*
* Display a specified set of reads of a database in fasta format.
*
* Author: <NAME>
* Date : September 2013
* Mod : With DB overhaul, made this a routine strictly for printing a selected subset
* and created DB2fasta for recreating all the fasta files of a DB
* Date : April 2014
* Mod : Added options to display QV streams
* Date : July 2014
*
********************************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include "DB.h"
#include "fileUtils.h"
#include "lib/tracks.h"
#include "lib/utils.h"
#ifdef HIDE_FILES
#define PATHSEP "/."
#else
#define PATHSEP "/"
#endif
static void usage()
{
fprintf(stderr, "usage: [-unqUQ] [-cwx <int>] [-rtm <track>] <path:db|dam> [ <reads:FILE> | <reads:range> ... ]\n");
fprintf(stderr, "options: -n ... DNA sequence is not displayed\n");
fprintf(stderr, " -q ... report QV streams\n");
fprintf(stderr, " -U ... report DNA sequence in upper case\n");
fprintf(stderr, " -Q ... QV streams are reported into a .quiva file\n");
fprintf(stderr, " -w ... specify number of characters per line\n");
fprintf(stderr, " -x ... filter out reads that are shorter than -x length\n");
fprintf(stderr, " -t ... trim reads according to trim track \n");
fprintf(stderr, " -r ... repeat track to invert sequence to upper/lower (depending is -U is set)\n");
fprintf(stderr, " -m ... report interval track as header and in DNA sequence in defined lower/upper format\n");
fprintf(stderr, " -c ... cut tips until <int> number of uniqe bases remain\n");
}
extern char *optarg;
extern int optind, opterr, optopt;
#define LAST_READ_SYMBOL '$'
void get_uniqueTipInterval(HITS_TRACK* reptrack, int rid, int* b, int* e, int nUbase)
{
track_anno* anno = (track_anno*) reptrack->anno;
track_anno ob = anno[rid] / sizeof(track_data);
track_anno oe = anno[rid + 1] / sizeof(track_data);
track_anno oc;
if (ob < oe)
{
track_data* data = (track_data*) reptrack->data;
int beg, end;
beg = *b;
end = *e;
// find begin interval
oc = ob;
while (oc < oe)
{
if (data[oc] - beg >= nUbase)
{
break;
}
beg = data[oc + 1];
oc += 2;
}
// find end interval
oc = oe;
while (oc > ob)
{
if (end - data[oc - 1] >= nUbase)
{
break;
}
end = data[oc - 2];
oc -= 2;
}
if(beg + 1 >= *e)
beg = *e;
if(end - 1 <= *b)
end = *b;
*b = beg;
*e = end;
}
}
int main(int argc, char *argv[])
{
HITS_DB _db, *db = &_db;
HITS_TRACK* pacbio_track = NULL;
HITS_TRACK* seqID_track = NULL;
HITS_TRACK* source_track = NULL;
HITS_TRACK* trim_track = NULL;
HITS_TRACK* rep_track = NULL;
FILE *hdrs = NULL;
int nfiles;
char **flist = NULL;
int *findx = NULL;
int reps, *pts;
int input_pts;
Read_Iterator *iter = NULL;
FILE *input;
char *trim = NULL;
char *rep = NULL;
int UPPER, CUT_UNTIL_UBASES;
int DOSEQ, DOQVS, QUIVA, DAM;
int WIDTH, MINLEN;
int MMAX, MTOP;
char **MASK;
// Process arguments
{
DAM = 0;
UPPER = 1;
DOQVS = 0;
DOSEQ = 1;
QUIVA = 0;
WIDTH = 80;
MINLEN = 0;
CUT_UNTIL_UBASES = 0;
MTOP = 0;
MMAX = 10;
MASK = (char **) Malloc(MMAX * sizeof(char *), "Allocating mask track array");
if (MASK == NULL)
exit(1);
int c;
opterr = 0;
while ((c = getopt(argc, argv, "nqUQw:m:x:t:r:c:")) != -1)
{
switch (c)
{
case 'n':
DOSEQ = 0;
break;
case 'q':
DOQVS = 1;
break;
case 'U':
UPPER = 2;
break;
case 't':
trim = optarg;
break;
case 'r':
rep = optarg;
break;
case 'Q':
QUIVA = 1;
break;
case 'w':
{
WIDTH = atoi(optarg);
if (WIDTH <= 0)
{
fprintf(stderr, "[ERROR] invalid line width of %d\n", WIDTH);
exit(1);
}
}
break;
case 'c':
{
CUT_UNTIL_UBASES = atoi(optarg);
if (CUT_UNTIL_UBASES < 0)
{
fprintf(stderr, "[ERROR] -c argument must be positive %d!\n", CUT_UNTIL_UBASES);
exit(1);
}
}
break;
case 'x':
{
MINLEN = atoi(optarg);
if (MINLEN < 0)
{
fprintf(stderr, "[ERROR] invalid minimum read length of %d\n", MINLEN);
exit(1);
}
}
break;
case 'm':
{
if (MTOP >= MMAX)
{
MMAX = 1.2 * MTOP + 10;
MASK = (char **) Realloc(MASK, MMAX * sizeof(char *), "Reallocating mask track array");
if (MASK == NULL)
exit(1);
}
// ignore pacbio track
if (strcasecmp(optarg, TRACK_PACBIO_HEADER) == 0)
break;
// ignore seq id track
if (strcasecmp(optarg, TRACK_SEQID) == 0)
break;
if (strcasecmp(optarg, TRACK_SOURCE) == 0)
break;
MASK[MTOP] = optarg;
MTOP++;
}
break;
default:
fprintf(stderr, "[ERROR] Unsupported argument %s\n", argv[optind]);
usage();
exit(1);
}
}
if (QUIVA && (!DOSEQ || MTOP > 0))
{
fprintf(stderr, "[ERROR] -Q (quiva) format request inconsistent with -n and -m options\n");
exit(1);
}
if (QUIVA)
DOQVS = 1;
if (optind + 1 > argc)
{
fprintf(stderr, "[ERROR]: Database is required\n");
usage();
exit(1);
}
}
// Open DB or DAM, and if a DAM open also .hdr file
{
char *pwd, *root;
int status;
status = Open_DB(argv[optind], db);
if (status < 0)
exit(1);
if (status == 1)
{
root = Root(argv[optind], ".dam");
pwd = PathTo(argv[optind]);
hdrs = Fopen(Catenate(pwd, PATHSEP, root, ".hdr"), "r");
if (hdrs == NULL)
exit(1);
DAM = 1;
if (QUIVA || DOQVS)
{
fprintf(stderr, "%s: -Q and -q options not compatible with a .dam DB\n", Prog_Name);
exit(1);
}
free(root);
free(pwd);
}
}
// Load QVs if requested
if (DOQVS)
{
if (Load_QVs(db) < 0)
{
fprintf(stderr, "%s: QVs requested, but no .qvs for data base\n", Prog_Name);
exit(1);
}
}
// Check tracks and load tracks for DB
{
int i, status;
for (i = 0; i < MTOP; i++)
{
// status = Check_Track(db, MASK[i]);
// if (status == -2)
// printf("[WARNING] - DBshow: -m%s option given but no track found.\n", MASK[i]);
// else if (status == -1)
// printf("[WARNING] - DBshow: %s track not sync'd with db.\n", MASK[i]);
// else
track_load(db, MASK[i]);
}
}
// If not a DAM then get prolog names and index ranges from the .db file
if (!DAM)
{
char *pwd, *root;
FILE *dstub;
int i;
root = Root(argv[optind], ".db");
pwd = PathTo(argv[optind]);
if (db->part > 0)
{
char* sep = rindex(root, '.');
*sep = '\0';
}
dstub = Fopen(Catenate(pwd, "/", root, ".db"), "r");
if (dstub == NULL)
exit(1);
free(pwd);
free(root);
if (fscanf(dstub, DB_NFILE, &nfiles) != 1)
SYSTEM_READ_ERROR
flist = (char **) Malloc(sizeof(char *) * nfiles, "Allocating file list");
findx = (int *) Malloc(sizeof(int *) * (nfiles + 1), "Allocating file index");
if (flist == NULL || findx == NULL)
exit(1);
findx += 1;
findx[-1] = 0;
for (i = 0; i < nfiles; i++)
{
char prolog[MAX_NAME], fname[MAX_NAME];
if (fscanf(dstub, DB_FDATA, findx + i, fname, prolog) != 3)
SYSTEM_READ_ERROR
if (Check_Track(db, TRACK_PACBIO_HEADER) == 0)
{
if ((flist[i] = Strdup(prolog, "Adding to file list")) == NULL)
exit(1);
}
else
{
if ((flist[i] = Strdup(fname, "Adding to file list")) == NULL)
exit(1);
}
}
fclose(dstub);
if (db->part > 0)
{
for (i = 0; i < nfiles; i++)
findx[i] -= db->ufirst;
}
}
// Load Tracks pacbio and seqID if present
{
int status;
status = Check_Track(db, TRACK_PACBIO_HEADER);
if (status == 0)
pacbio_track = track_load(db, TRACK_PACBIO_HEADER);
status = Check_Track(db, TRACK_SEQID);
if (status == 0)
seqID_track = track_load(db, TRACK_SEQID);
status = Check_Track(db, TRACK_SOURCE);
if (status == 0)
source_track = track_load(db, TRACK_SOURCE);
if (trim != NULL)
{
for (trim_track = db->tracks; trim_track != NULL; trim_track = trim_track->next)
{
if (strcmp(trim_track->name, trim) == 0)
break;
}
if (trim_track == NULL)
trim_track = track_load(db, trim);
}
if (rep != NULL)
{
for (rep_track = db->tracks; rep_track != NULL; rep_track = rep_track->next)
{
if (strcmp(rep_track->name, rep) == 0)
break;
}
if (rep_track == NULL)
rep_track = track_load(db, rep);
}
}
// Process read index arguments into a list of read ranges
optind++;
input_pts = 0;
if (optind + 1 == argc)
{
if (argv[optind][0] != LAST_READ_SYMBOL || argv[optind][1] != '\0')
{
char *eptr, *fptr;
int b, e;
b = strtol(argv[optind], &eptr, 10);
if (eptr > argv[optind] && b >= 0)
{
if (*eptr == '-')
{
if (eptr[1] != LAST_READ_SYMBOL || eptr[2] != '\0')
{
e = strtol(eptr + 1, &fptr, 10);
input_pts = (fptr <= eptr + 1 || *fptr != '\0' || e <= 0);
}
}
else
input_pts = (*eptr != '\0');
}
else
input_pts = 1;
}
}
if (input_pts)
{
input = Fopen(argv[optind], "r");
if (input == NULL)
exit(1);
iter = init_read_iterator(input);
}
else
{
pts = (int *) Malloc(sizeof(int) * 2 * (optind - 1), "Allocating read parameters");
if (pts == NULL)
exit(1);
reps = 0;
if (argc - optind >= 1)
{
int c, b, e;
char *eptr, *fptr;
for (c = optind; c < argc; c++)
{
if (argv[c][0] == LAST_READ_SYMBOL)
{
b = db->nreads;
eptr = argv[c] + 1;
}
else
b = strtol(argv[c], &eptr, 10);
if (eptr > argv[c])
{
if (b < 0)
{
fprintf(stderr, "%s: %d is not a valid index\n", Prog_Name, b);
exit(1);
}
if (*eptr == 0)
{
pts[reps++] = b;
pts[reps++] = b + 1;
continue;
}
else if (*eptr == '-')
{
if (eptr[1] == LAST_READ_SYMBOL)
{
e = db->nreads;
fptr = eptr + 2;
}
else
e = strtol(eptr + 1, &fptr, 10);
if (fptr > eptr + 1 && *fptr == 0 && e > 0)
{
pts[reps++] = b;
pts[reps++] = e;
if (b > e)
{
fprintf(stderr, "%s: Empty range '%s'\n", Prog_Name, argv[c]);
exit(1);
}
continue;
}
}
}
fprintf(stderr, "%s: argument '%s' is not an integer range\n", Prog_Name, argv[c]);
exit(1);
}
}
else
{
pts[reps++] = 0;
pts[reps++] = db->nreads;
}
}
// Display each read (and/or QV streams) in the active DB according to the
// range pairs in pts[0..reps) and according to the display options.
{
HITS_READ *reads;
HITS_TRACK *first;
char *read, **entry;
int c, b, e, i;
int hilight, substr;
int map;
int (*iscase)(int);
track_anno *pacbio_anno, *seqID_anno, *source_anno;
track_data *pacbio_data, *seqID_data, *source_data;
pacbio_anno = seqID_anno = source_anno = NULL;
pacbio_data = seqID_data = source_data = NULL;
int trim_b, trim_e;
int uniq_b, uniq_e;
if (pacbio_track)
{
pacbio_anno = pacbio_track->anno;
pacbio_data = pacbio_track->data;
}
if (seqID_track)
{
seqID_anno = seqID_track->anno;
seqID_data = seqID_track->data;
}
if (source_track)
{
source_anno = source_track->anno;
source_data = source_track->data;
}
read = New_Read_Buffer(db);
if (DOQVS)
{
entry = New_QV_Buffer(db);
first = db->tracks->next;
}
else
{
entry = NULL;
first = db->tracks;
}
if (UPPER == 1)
{
hilight = 'A' - 'a';
iscase = islower;
}
else
{
hilight = 'a' - 'A';
iscase = isupper;
}
map = 0;
reads = db->reads;
substr = 0;
c = 0;
while (1)
{
if (input_pts)
{
if (next_read(iter))
break;
b = iter->read;
e = b + 1;
substr = (iter->beg >= 0);
}
else
{
if (c >= reps)
break;
b = pts[c];
e = pts[c + 1];
if (e > db->nreads)
e = db->nreads; // - 1;
c += 2;
}
for (i = b; i < e; i++)
{
int len;
int fst, lst;
// int flags, qv;
HITS_READ *r;
HITS_TRACK *track;
r = reads + i;
if (trim_track != NULL)
{
get_trim(db, trim_track, i, &trim_b, &trim_e);
}
else
{
trim_b = 0;
trim_e = r->rlen;
}
uniq_b = trim_b;
uniq_e = trim_e;
if (rep_track != NULL && CUT_UNTIL_UBASES > 0)
{
get_uniqueTipInterval(rep_track, i, &uniq_b, &uniq_e, CUT_UNTIL_UBASES);
}
len = uniq_e - uniq_b;
if (len < MINLEN)
{
fprintf(stderr, "[WARNING] - Read %d is shorter than minimum read length (%d < %d)", i, len, MINLEN);
if (trim_track)
{
fprintf(stderr," oLen=%d", r->rlen);
fprintf(stderr," trim=%d,%d", trim_b, trim_e);
}
if (rep_track && CUT_UNTIL_UBASES > 0)
{
fprintf(stderr," uniqTips%d=%d,%d", CUT_UNTIL_UBASES, uniq_b, uniq_e);
}
fprintf(stderr, "\n");
fflush(stderr);
continue;
}
// flags = r->flags;
// qv = (flags & DB_QV);
if (DAM)
{
char header[MAX_NAME];
fseeko(hdrs, r->coff, SEEK_SET);
if (fgets(header, MAX_NAME, hdrs) == NULL)
{
fprintf(stderr, "ERROR: failed to read header\n");
exit(1);
}
header[strlen(header) - 1] = '\0';
printf("%s :: Contig %d[%d]", header, b, len);
}
else
{
while (i < findx[map - 1])
map -= 1;
while (i >= findx[map])
map += 1;
if (QUIVA)
printf("@%s_%d_%d", flist[map], i, len);
else
{
if (pacbio_track)
{
int s, f;
s = pacbio_anno[i] / sizeof(track_data);
f = pacbio_anno[i + 1] / sizeof(track_data);
if (s < f)
printf(">%s/%d/%d_%d", flist[map], pacbio_data[s], pacbio_data[s + 1], pacbio_data[s + 2]);
else
printf(">%s_%d_%d_%d", flist[map], -1, i, len);
}
else if (seqID_track)
{
int s, f;
s = seqID_anno[i] / sizeof(track_data);
f = seqID_anno[i + 1] / sizeof(track_data);
if (s < f)
printf(">%s_%d_%d_%d", flist[map], seqID_data[s], i, len);
else // fall back if seqID is empty for corresponding reads
printf(">%s_%d_%d_%d", flist[map], -1, i, len);
}
else
{
printf(">%s_%d_%d_%d", flist[map], -1, i, len);
}
if (source_track)
{
int s, f;
s = source_anno[i] / sizeof(track_data);
f = source_anno[i + 1] / sizeof(track_data);
if (s < f)
{
printf(" %s=%d", TRACK_SOURCE, source_data[s]);
}
}
if (trim_track)
{
printf(" oLen=%d", r->rlen);
printf(" trim=%d,%d", trim_b, trim_e);
}
if (rep_track && CUT_UNTIL_UBASES > 0)
{
printf(" uniqTips%d=%d,%d", CUT_UNTIL_UBASES, uniq_b, uniq_e);
}
}
}
if (DOQVS)
Load_QVentry(db, i, entry, UPPER);
if (DOSEQ)
Load_Read(db, i, read, UPPER);
for (track = first; track != NULL; track = track->next)
{
if (strcmp(track->name, TRACK_PACBIO_HEADER) == 0)
continue;
if (strcmp(track->name, TRACK_SEQID) == 0)
continue;
if (strcmp(track->name, TRACK_SOURCE) == 0)
continue;
if (trim != NULL && strcmp(track->name, trim) == 0)
continue;
if (rep != NULL && strcmp(track->name, rep) == 0)
continue;
int64 *anno;
int *data;
int64 s, f, j;
int bd, ed, m;
anno = (int64 *) track->anno;
data = (int *) track->data;
s = (anno[i] >> 2);
f = (anno[i + 1] >> 2);
if (s < f)
{
for (j = s; j < f; j += 2)
{
bd = data[j];
ed = data[j + 1];
if (DOSEQ)
for (m = bd; m < ed; m++)
if (iscase(read[m]))
read[m] = (char) (read[m] + hilight);
if (j == s)
printf(" %s=", track->name);
if (ed < trim_b || bd > trim_e)
continue;
if (bd < trim_b)
bd = trim_e;
if (ed > trim_e)
ed = trim_e;
if (j + 2 < f)
printf("%d,%d,", bd, ed);
else
printf("%d,%d", bd, ed);
}
}
}
printf("\n");
if (substr)
{
fst = iter->beg;
lst = iter->end;
}
else
{
fst = trim_b;
lst = trim_e;
}
if (QUIVA)
{
int k;
for (k = 0; k < 5; k++)
printf("%.*s\n", lst - fst, entry[k] + fst);
}
else
{
if (DOQVS)
{
int j, k;
printf("\n");
for (j = fst; j + WIDTH < lst; j += WIDTH)
{
if (DOSEQ)
printf("%.*s\n", WIDTH, read + j);
for (k = 0; k < 5; k++)
printf("%.*s\n", WIDTH, entry[k] + j);
printf("\n");
}
if (j < lst)
{
if (DOSEQ)
printf("%.*s\n", lst - j, read + j);
for (k = 0; k < 5; k++)
printf("%.*s\n", lst - j, entry[k] + j);
printf("\n");
}
}
else if (DOSEQ)
{
int j;
for (j = fst; j + WIDTH < lst; j += WIDTH)
printf("%.*s\n", WIDTH, read + j);
if (j < lst)
printf("%.*s\n", lst - j, read + j);
}
}
fflush(stdout);
}
}
}
if (input_pts)
{
fclose(input);
free(iter);
}
else
free(pts);
if (DAM)
fclose(hdrs);
else
{
int i;
for (i = 0; i < nfiles; i++)
free(flist[i]);
free(flist);
free(findx - 1);
}
Close_DB(db);
exit(0);
}
|
MartinPippel/DAmar
|
utils/H5dextract.c
|
<reponame>MartinPippel/DAmar<gh_stars>10-100
/*******************************************************************************************
*
* BAXstat : pulls out information from .bax.h5 files produced by Pacbio
* - statistics i.e. time-dependent quality values,
* - fasta/fastq and quiva files
*
*
* Author : <NAME>
* Date : Jul 20, 2014
*
*
* Date : Jul 29, 2014 - added average movie time in respect to subread length
* - fixed bug: percentage of fragments
*
*
********************************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <math.h>
#include <sys/stat.h>
#include <ctype.h>
#include <hdf5.h>
#include <time.h>
#include "lib/stats.h"
#include "limits.h"
#define DEBUG 0
#define VERBOSE_SPR 0
#define MEASURE_TIME 0
#define MAX_NAME 1024
#include "H5dextractUtils.h"
// Fetch the relevant contents of the current bax.h5 file and return the H5 file id.
static int getAttribute(hid_t file_id, char * groupName, char *attrName, char **buffer)
{
hid_t attr;
hid_t grp;
hid_t atype;
char buf[MAX_NAME];
grp = H5Gopen(file_id, groupName, H5P_DEFAULT);
if (grp < 0)
{
printf("Cannot open %s\n", groupName);
return -1;
}
int na = H5Aget_num_attrs(grp);
int i, found;
found = 0;
for (i = 0; i < na; i++)
{
attr = H5Aopen_idx(grp, (unsigned int) i);
// len = H5Aget_name(attr, MAX_NAME, buf);
// printf(" Attribute Name : %s\n", buf);
if (strcmp(buf, attrName) == 0)
{
atype = H5Tcopy(H5T_C_S1);
H5Tset_size(atype, H5T_VARIABLE);
H5Aread(attr, atype, buffer);
// fprintf(stderr, "Attribute string read was '%s'\n", *buffer);
H5Tclose(atype);
found=1;
}
H5Aclose(attr);
}
if(found == 0)
*buffer = NULL;
H5Gclose(grp);
return 0;
}
static int getBaxData(BaxData *b, BAX_OPT* bopt)
{
hid_t field_space;
hid_t field_set;
hsize_t field_len[1];
hid_t file_id;
herr_t stat;
H5Eset_auto(H5E_DEFAULT, 0, 0); // silence hdf5 error stack
file_id = H5Fopen(b->fullName, H5F_ACC_RDONLY, H5P_DEFAULT);
if (file_id < 0)
return (CANNOT_OPEN_BAX_FILE);
// ensure capacity
{
field_set = H5Dopen2(file_id, "/PulseData/BaseCalls/Basecall", H5P_DEFAULT);
field_space = H5Dget_space(field_set);
if (field_set < 0 || field_space < 0)
{
H5Fclose(file_id);
return (BAX_BASECALL_ERR);
}
H5Sget_simple_extent_dims(field_space, field_len, NULL);
b->numBase = field_len[0];
field_set = H5Dopen2(file_id, "/PulseData/BaseCalls/ZMW/NumEvent", H5P_DEFAULT);
field_space = H5Dget_space(field_set);
if (field_set < 0 || field_space < 0)
{
H5Fclose(file_id);
return (BAX_NR_EVENTS_ERR);
}
H5Sget_simple_extent_dims(field_space, field_len, NULL);
b->numZMW = field_len[0];
field_set = H5Dopen2(file_id, "/PulseData/Regions", H5P_DEFAULT);
field_space = H5Dget_space(field_set);
if (field_set < 0 || field_space < 0)
{
H5Fclose(file_id);
return (BAX_REGION_ERR);
}
H5Sget_simple_extent_dims(field_space, field_len, NULL);
b->numRegion = field_len[0];
if (getAttribute(file_id, "/ScanData/RunInfo", "SequencingKit", &(b->sequencingKit)) < 0)
fprintf(stderr, "Cannot read attribute \"SequencingKit\" from group \"/ScanData/RunInfo\" from file %s. \n", b->fullName);
if (getAttribute(file_id, "/ScanData/RunInfo", "BindingKit", &(b->bindingKit)) < 0)
fprintf(stderr, "Cannot read attribute \"BindingKit\" from group \"/ScanData/RunInfo\" from file %s. \n", b->fullName);
if (getAttribute(file_id, "/PulseData/BaseCalls", "ChangeListID", &(b->softwareVersion)) < 0)
fprintf(stderr, "Cannot read attribute \"ChangeListID\" from group \"/PulseData/BaseCalls\" from file %s. \n", b->fullName);
// optional
getAttribute(file_id, "/ScanData/RunInfo", "SequencingChemistry", &(b->sequencingChemistry));
}
ensureCapacity(b, b->numBase, b->numZMW, b->numRegion);
// type is an "enum" :
// 0 -- unsigned char
// 1 -- char
// 2 -- uInt16
// 3 -- int16
// 4 -- uInt32
// 5 -- int32
// 6 -- float
// 7 -- double
#define FETCH(field,path,error,type) \
{ field_set = H5Dopen2(file_id, path, H5P_DEFAULT); \
field_space = H5Dget_space(field_set); \
if (field_set < 0 || field_space < 0) \
{ H5Fclose(file_id); \
return (error); \
} \
switch (type) \
{ case 0: stat = H5Dread(field_set, H5T_NATIVE_UCHAR, H5S_ALL, H5S_ALL, H5P_DEFAULT, b->field); break; \
case 1: stat = H5Dread(field_set, H5T_NATIVE_CHAR, H5S_ALL, H5S_ALL, H5P_DEFAULT, b->field); break; \
case 2: stat = H5Dread(field_set, H5T_NATIVE_USHORT, H5S_ALL, H5S_ALL, H5P_DEFAULT, b->field); break; \
case 3: stat = H5Dread(field_set, H5T_NATIVE_SHORT, H5S_ALL, H5S_ALL, H5P_DEFAULT, b->field); break; \
case 4: stat = H5Dread(field_set, H5T_NATIVE_UINT, H5S_ALL, H5S_ALL, H5P_DEFAULT, b->field); break; \
case 5: stat = H5Dread(field_set, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, b->field); break; \
case 6: stat = H5Dread(field_set, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, b->field); break; \
case 7: stat = H5Dread(field_set, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, b->field); break; \
default: return -11; \
} \
if (stat < 0) \
return (error); \
H5Sclose(field_space); \
H5Dclose(field_set); \
}
// Get read lengths out of the bax file
FETCH(numEvent, "/PulseData/BaseCalls/ZMW/NumEvent", BAX_NR_EVENTS_ERR, 5);
// Get the region annotations out of the bax file
FETCH(region, "/PulseData/Regions", BAX_REGION_ERR, 5);
// check if set of hole numbers is specified, if none of them is present in current file, then skip the reading from bax file
if(bopt->wellNumbersInFileName != NULL && bopt->numWellNumbers[bopt->curBaxFile])
{
if(b->region[0] > bopt->wellNumbers[bopt->curBaxFile][bopt->numWellNumbers[bopt->curBaxFile]-2])
{
printf("first zmw of %d > %d (last zmw in selection range)\n", b->region[0], bopt->wellNumbers[bopt->curBaxFile][bopt->numWellNumbers[bopt->curBaxFile]-2]);
H5Fclose(file_id);
return IGNORE_BAX;
}
if(b->region[(b->numRegion-1)*5] < bopt->wellNumbers[bopt->curBaxFile][0])
{
printf("last zmw of %d < %d (first zmw in selection range)\n", b->region[(b->numRegion-1)*5], bopt->wellNumbers[bopt->curBaxFile][0]);
H5Fclose(file_id);
return IGNORE_BAX;
}
}
FETCH(holeStatus, "/PulseData/BaseCalls/ZMW/HoleStatus", BAX_HOLESTATUS_ERR, 0);
FETCH(hqRegionBegTime, "/PulseData/BaseCalls/ZMWMetrics/HQRegionStartTime", BAX_HQREGIONSTARTTIME_ERR, 6);
FETCH(hqRegionEndTime, "/PulseData/BaseCalls/ZMWMetrics/HQRegionEndTime", BAX_HQREGIONENDTIME_ERR, 6);
// Get all quality streams
FETCH(baseCall, "/PulseData/BaseCalls/Basecall", BAX_BASECALL_ERR, 0)
FETCH(fastQV, "/PulseData/BaseCalls/QualityValue", BAX_QV_ERR, 0)
FETCH(delQV, "/PulseData/BaseCalls/DeletionQV", BAX_DELETIONQV_ERR, 0)
FETCH(delTag, "/PulseData/BaseCalls/DeletionTag", BAX_DELETIONTAG_ERR, 0)
FETCH(insQV, "/PulseData/BaseCalls/InsertionQV", BAX_INSERTIONQV_ERR, 0)
FETCH(mergeQV, "/PulseData/BaseCalls/MergeQV", BAX_MERGEQV_ERR, 0)
FETCH(subQV, "/PulseData/BaseCalls/SubstitutionQV", BAX_SUBSTITUTIONQV_ERR, 0)
// Get times for single base calls
FETCH(widthInFrames, "/PulseData/BaseCalls/WidthInFrames", BAX_WIDTHINFRAMES_ERR, 2);
FETCH(preBaseFrames, "/PulseData/BaseCalls/PreBaseFrames", BAX_PREBASEFRAMES_ERR, 2);
// Get additional ZMW statistics
FETCH(pausiness, "/PulseData/BaseCalls/ZMWMetrics/Pausiness", BAX_PAUSINESS_ERR, 6);
FETCH(productivity, "/PulseData/BaseCalls/ZMWMetrics/Productivity", BAX_PRODUCTIVITY_ERR, 0);
FETCH(readType, "/PulseData/BaseCalls/ZMWMetrics/ReadType", BAX_READTYPE_ERR, 0);
H5Fclose(file_id);
return (0);
}
static void printBaxStatisticHeader(BaxStatistic* s, BAX_OPT *bopt)
{
FILE *out = bopt->statFile;
fprintf(out, "################ BAX statistic setup ##########\n");
fprintf(out, "# minLen: \t");
Print_Number(out, (int64) bopt->MIN_LEN, 15);
if (bopt->MAX_LEN < INT_MAX)
{
fprintf(out, "# maxLen: \t");
Print_Number(out, (int64) bopt->MAX_LEN, 15);
}
fprintf(out, "\n# minScore: \t");
Print_Number(out, (int64) s->minScore, 15);
fprintf(out, "\n# cumulative: \t");
if (s->cumulative)
fprintf(out, " yes");
else
fprintf(out, " no");
fprintf(out, "\n# readLenBinSize:\t");
Print_Number(out, (int64) s->readLenBinSize, 15);
fprintf(out, "\n# timeLenBinSize:\t");
Print_Number(out, (int64) s->timeLenBinSize, 15);
fprintf(out, "\n# minMovieTime: \t");
Print_Number(out, (int64) s->minMovieTime, 15);
if (s->minMovieTime == 0)
fprintf(out, " (default, not set)");
fprintf(out, "\n# maxMovieTime: \t");
Print_Number(out, (int64) s->maxMovieTime, 15);
if (s->maxMovieTime == MAX_TIME_LIMIT)
fprintf(out, " (default, not set)");
switch (bopt->subreadSel)
{
case all:
default:
fprintf(out, "\n# subreadSelection: all");
break;
case best:
fprintf(out, "\n# subreadSelection: best");
break;
case shortest:
fprintf(out, "\n# subreadSelection: shortest");
break;
case longest:
fprintf(out, "\n# subreadSelection: longest");
break;
}
fprintf(out, "\n###############################################\n");
fflush(out);
}
static void printBaxStatistic(BaxStatistic* s, FILE* out)
{
///////////////////// general output
{
fprintf(out, "#general ##########################\n");
fprintf(out, "\nnumFiles: \t");
Print_Number(out, (int64) s->nFiles, 15);
fprintf(out, "\nnumZMWs: \t");
Print_Number(out, (int64) s->nZMWs, 15);
fprintf(out, "\nZMWstates:\n");
int i;
for (i = SEQUENCING; i <= UNKNOWN; i++)
if (s->stateHist[i] != 0)
{
switch (i)
{
case SEQUENCING:
fprintf(out, " SEQUENCING\t");
break;
case ANTIHOLE:
fprintf(out, " ANTIHOLE\t");
break;
case FIDUCIAL:
fprintf(out, " FIDUCIAL\t");
break;
case SUSPECT:
fprintf(out, " SUSPECT\t");
break;
case ANTIMIRROR:
fprintf(out, " ANTIMIRROR\t");
break;
case FDZMW:
fprintf(out, " FDZMW\t");
break;
case FBZMW:
fprintf(out, " FBZMW\t");
break;
case ANTIBEAMLET:
fprintf(out, " ANTIBEAMLET\t");
break;
case OUTSIDEFOV:
fprintf(out, " OUTSIDEFOV\t");
break;
case UNKNOWN:
fprintf(out, " UNKNOWN\t");
break;
default:
break;
}
Print_Number(out, (int64) s->stateHist[i], 15);
fprintf(out, "\n");
}
fprintf(out, "ZMWproductivity:\n");
for (i = prod_Empty; i <= prod_NotDefined; i++)
if (s->productiveHist[i] != 0)
{
switch (i)
{
case prod_Empty:
fprintf(out, " EMPTY\t");
break;
case prod_Productive:
fprintf(out, " PRODUCTIVE\t");
break;
case prod_Other:
fprintf(out, " OTHER\t");
break;
case prod_NotDefined:
fprintf(out, " NOT_DEFINED\t");
break;
default:
break;
}
Print_Number(out, (int64) s->productiveHist[i], 15);
fprintf(out, "\n");
}
fprintf(out, "ZMWReadType:\n");
for (i = type_Empty; i <= type_NotDefined; i++)
if (s->readTypeHist[i] != 0)
{
switch (i)
{
case type_Empty:
fprintf(out, " Empty \t");
break;
case type_FullHqRead0:
fprintf(out, " FullHqRead0 \t");
break;
case type_FullHqRead1:
fprintf(out, " FullHqRead1 \t");
break;
case type_PartialHqRead0:
fprintf(out, " PartialHqRead0\t");
break;
case type_PartialHqRead1:
fprintf(out, " PartialHqRead1\t");
break;
case type_PartialHqRead2:
fprintf(out, " PartialHqRead2\t");
break;
case type_Multiload:
fprintf(out, " Multiload \t");
break;
case type_Indeterminate:
fprintf(out, " Indeterminate \t");
break;
case type_NotDefined:
fprintf(out, " NotDefined \t");
break;
default:
break;
}
Print_Number(out, (int64) s->readTypeHist[i], 15);
fprintf(out, "\n");
}
fprintf(out, "avgPausiness: \t%.4f", s->cumPausiness * 1. / s->nZMWs);
fprintf(out, "\nnumSubreadBases: ");
Print_Number(out, (int64) s->numSubreadBases, 15);
fprintf(out, "\nnumSubReads: \t");
Print_Number(out, (int64) s->numSubreads, 15);
fprintf(out, "\navgReadLen: \t");
Print_Number(out, s->numSubreads > 0 ? (int64) s->numSubreadBases / s->numSubreads : 0, 15);
int sprCount, sprBaseCount;
sprCount = sprBaseCount = 0;
for (i = 0; i < s->nLenBins; i++)
{
sprCount += s->nSlowPolymeraseRegionLenHist[i];
sprBaseCount += s->cumSlowPolymeraseRegionLenHist[i];
}
fprintf(out, "\nnumSubreadsWithSPR: \t");
Print_Number(out, sprCount, 15);
fprintf(out, " (%5.2f)", sprCount * 100. / s->numSubreads);
fprintf(out, "\nnumBasesInSPR: \t");
Print_Number(out, sprBaseCount, 15);
fprintf(out, " (%5.2f)", sprBaseCount * 100. / s->numSubreadBases);
fprintf(out, "\n");
}
////////////////////////// report subread fragmentation
{
int a;
float cumNum = 0;
fprintf(out, "\n#Subread fragmentation: #########################\n");
for (a = 0; a <= MAX_SUBREADS; a++)
{
if (s->subreadHist[a] == 0)
continue;
if (a == MAX_SUBREADS)
fprintf(out, "\n>");
else
fprintf(out, "\n ");
Print_Number(out, (int64) a, 4);
fprintf(out, "-frag: \t");
Print_Number(out, (int64) s->subreadHist[a], 10);
cumNum += a * s->subreadHist[a];
fprintf(out, "\t(%5.3f%%)\t(%5.3f%%)", a * s->subreadHist[a] * 100. / s->numSubreads, cumNum * 100. / s->numSubreads);
}
fprintf(out, "\n");
}
/////////////////////// report read length histogram
{
int a, c;
uint64 rcount, bcount;
fprintf(out, "\n#Distribution of Read Lengths (Bin size = ");
Print_Number(out, (int64) s->readLenBinSize, 0);
fprintf(out, ") #######################\n\n Bin: Count %% Reads %% Bases Average RunTimeAvg (min) SPR (reads/bases)\n");
rcount = bcount = 0;
for (a = s->nLenBins - 1; a >= 0; a--)
if (s->readLengthHist[a] > 0)
break;
for (c = 0; c < s->nLenBins - 1; c++)
if (s->readLengthHist[c] > 0)
break;
if (a < 0)
fprintf(out, "--- not any high quality read ---");
for (; a >= c; a--)
{
rcount += s->readLengthHist[a];
bcount += s->readLengthBasesHist[a];
Print_Number(out, (int64) (a * s->readLenBinSize), 7);
fprintf(out, ":");
Print_Number(out, (int64) s->readLengthHist[a], 11);
if (s->readLengthHist[a] == 0)
fprintf(out, " %5.1f %5.1f %5lld - - ( - ) / - ( - )\n", (100. * rcount) / s->numSubreads, (100. * bcount) / s->numSubreadBases, bcount / rcount);
else
fprintf(out, " %5.1f %5.1f %5lld %5.2f %7llu (%4.2f) / %7llu (%4.2f)\n", (100. * rcount) / s->numSubreads, (100. * bcount) / s->numSubreadBases, bcount / rcount, (s->readLengthTimeHist[a] / FRAME_RATE / s->readLengthHist[a]) / 60., s->nSlowPolymeraseRegionLenHist[a], s->nSlowPolymeraseRegionLenHist[a] * 100. / s->readLengthHist[a], s->cumSlowPolymeraseRegionLenHist[a], s->cumSlowPolymeraseRegionLenHist[a] * 100. / s->readLengthBasesHist[a]);
if (rcount == s->numSubreads)
break;
}
fprintf(out, "\n");
}
///////////////// report time-dependent Base distribution
{
int a, c;
int64 tmp;
int64 cumBaseA, cumBaseC, cumBaseG, cumBaseT, cumBaseN;
cumBaseA = cumBaseC = cumBaseG = cumBaseT = cumBaseN = 0;
fprintf(out, "#movie time dependent nucleotide distribution #####################################\n\n");
fprintf(out, "minutes A C G T N AT GC \n");
for (a = s->nTimBins - 1; a >= 0; a--)
if ((s->baseDistributionHist[BASE_A][a] > 0) || (s->baseDistributionHist[BASE_C][a] > 0) || (s->baseDistributionHist[BASE_G][a] > 0) || (s->baseDistributionHist[BASE_T][a] > 0) || (s->baseDistributionHist[BASE_N][a] > 0))
break;
for (c = 0; c < s->nTimBins - 1; c++)
if ((s->baseDistributionHist[BASE_A][c] > 0) || (s->baseDistributionHist[BASE_C][c] > 0) || (s->baseDistributionHist[BASE_G][c] > 0) || (s->baseDistributionHist[BASE_T][c] > 0) || (s->baseDistributionHist[BASE_N][c] > 0))
break;
if (a < 0)
fprintf(out, "--- not any high quality read ---");
for (; a >= c; a--)
{
tmp = s->baseDistributionHist[BASE_A][a] + s->baseDistributionHist[BASE_C][a] + s->baseDistributionHist[BASE_G][a] + s->baseDistributionHist[BASE_T][a] + s->baseDistributionHist[BASE_N][a];
Print_Number(out, (int64) (a * s->timeLenBinSize / 60), 7);
fprintf(out, " %1.3f %1.3f %1.3f %1.3f %1.3f %1.3f %1.3f\n", s->baseDistributionHist[BASE_A][a] * 1. / tmp, s->baseDistributionHist[BASE_C][a] * 1. / tmp, s->baseDistributionHist[BASE_G][a] * 1. / tmp, s->baseDistributionHist[BASE_T][a] * 1. / tmp, s->baseDistributionHist[BASE_N][a] * 1. / tmp, (s->baseDistributionHist[BASE_A][a] + s->baseDistributionHist[BASE_T][a]) * 1. / tmp, (s->baseDistributionHist[BASE_G][a] + s->baseDistributionHist[BASE_C][a]) * 1. / tmp);
cumBaseA += s->baseDistributionHist[BASE_A][a];
cumBaseC += s->baseDistributionHist[BASE_C][a];
cumBaseG += s->baseDistributionHist[BASE_G][a];
cumBaseT += s->baseDistributionHist[BASE_T][a];
cumBaseN += s->baseDistributionHist[BASE_N][a];
}
tmp = cumBaseA + cumBaseC + cumBaseG + cumBaseT + cumBaseN;
fprintf(out, "\n");
fprintf(out, "overall: %1.3f %1.3f %1.3f %1.3f %1.3f %1.3f %1.3f\n\n", cumBaseA * 1. / tmp, cumBaseC * 1. / tmp, cumBaseG * 1. / tmp, cumBaseT * 1. / tmp, cumBaseN * 1. / tmp, (cumBaseA + cumBaseT) * 1. / tmp, (cumBaseG + cumBaseC) * 1. / tmp);
}
///////////////// report qualities
{
int a, i, c;
int64 tmp;
int64 cumBaseQV, cumDelQV, cumInsQV, cumMerQV, cumSubQV;
cumBaseQV = cumDelQV = cumInsQV = cumMerQV = cumSubQV = 0;
// cumTimeDepQVs
fprintf(out, "#movie time dependent average quality distribution #############################\n\n");
fprintf(out, "minutes BASEQV DELQV INSQV MERQV SUBQV CONTENT %%BASES SPR (%%BASES)\n");
for (a = s->nTimBins - 1; a >= 0; a--)
if (s->cumTimeDepQVs[NUC_COUNT][a] > 0)
break;
for (c = 0; c < s->nTimBins - 1; c++)
if (s->cumTimeDepQVs[NUC_COUNT][c] > 0)
break;
if (a < 0)
fprintf(out, "--- not any high quality read ---");
for (; a >= c; a--)
{
cumBaseQV += s->cumTimeDepQVs[QV_SUM][a];
cumDelQV += s->cumTimeDepQVs[DEL_SUM][a];
cumInsQV += s->cumTimeDepQVs[INS_SUM][a];
cumMerQV += s->cumTimeDepQVs[MER_SUM][a];
cumSubQV += s->cumTimeDepQVs[SUB_SUM][a];
Print_Number(out, (int64) (a * s->timeLenBinSize / 60), 7);
fprintf(out, "%7.3f %7.3f %7.3f %7.3f %7.3f ", s->cumTimeDepQVs[QV_SUM][a] * 1. / s->cumTimeDepQVs[NUC_COUNT][a], s->cumTimeDepQVs[DEL_SUM][a] * 1. / s->cumTimeDepQVs[NUC_COUNT][a], s->cumTimeDepQVs[INS_SUM][a] * 1. / s->cumTimeDepQVs[NUC_COUNT][a], s->cumTimeDepQVs[MER_SUM][a] * 1. / s->cumTimeDepQVs[NUC_COUNT][a], s->cumTimeDepQVs[SUB_SUM][a] * 1. / s->cumTimeDepQVs[NUC_COUNT][a]);
Print_Number(out, (int64) s->cumTimeDepQVs[NUC_COUNT][a], 12);
tmp = 0;
for (i = 0; i <= a; ++i)
tmp += s->cumTimeDepQVs[NUC_COUNT][i];
fprintf(out, " %5.2f", tmp * 100. / s->numSubreadBases);
fprintf(out, " %5.2f", 100. * s->cumSlowPolymeraseRegionTimeHist[a] / s->cumTimeDepQVs[NUC_COUNT][a]);
fprintf(out, "\n");
}
fprintf(out, "\noverall: %5.3f %7.3f %7.3f %7.3f %7.3f\n\n", cumBaseQV * 1. / s->numSubreadBases, cumDelQV * 1. / s->numSubreadBases, cumInsQV * 1. / s->numSubreadBases, cumMerQV * 1. / s->numSubreadBases, cumSubQV * 1. / s->numSubreadBases);
}
}
static void getSlowPolymeraseRegions(ZMW* zmw)
{
#if MEASURE_TIME
clock_t begin, end;
begin=clock();
#endif
int a, d, i;
float numSigma = 2.0;
int slen;
slowPolymeraseRegions *spr;
double lmu, lsig;
static double help[100000];
int segW = zmw->spr->segmentWidth;
int segS = zmw->spr->shift;
int numSuspBaseThreshold = (segW * 0.5) + 1;
// loop over all selected subreads(fragments) of the current ZMW
for (i = 0; i < zmw->numFrag; i++)
{
if (zmw->toReport[i] == 0)
continue;
spr = zmw->spr + i;
slen = zmw->len[i];
for (a = 0; a < slen; a++)
help[a] = log(zmw->widthInFrames[i][a] + zmw->preBaseFrames[i][a]);
// evaluate mu and sigma for normal- and log-normal-distribution --> check which works better
n_estimate_double(help, slen, &lmu, &lsig);
int suspBase = lmu + (numSigma * lsig);
#if VERBOSE_SPR
fprintf(stdout, "SPR %d/%d_%d len%d lmu: %.2f lsig: %.2f, mu: %.2f sig: %.2f\n", zmw->number, zmw->insBeg[i], zmw->insEnd[i], zmw->len[i], lmu, lsig, mu, sig);
#endif
// iterate over segments
int numSuspBases;
int stopA = slen - segW;
int stopD;
for (a = 0; a < stopA; a += segS)
{
numSuspBases = 0;
stopD = a + segW;
for (d = a; d < stopD; d++)
{
if (help[d] > suspBase)
numSuspBases++;
}
if (numSuspBases >= numSuspBaseThreshold)
{
if (spr->nRegions == 0) // add region directly to spr
{
spr->beg[0] = a;
spr->end[0] = d;
spr->nRegions = 1;
spr->numSlowBases += (d - a + 1);
#if VERBOSE_SPR
fprintf(stdout, "add first interval: %d %d num: %d (#suspBases: %d/%d)\n", spr->beg[0], spr->end[0], spr->nRegions, numSuspBases, spr->segmentWidth);
#endif
}
else
{
// try to merge intervals
if (a < spr->end[spr->nRegions - 1])
{
#if VERBOSE_SPR
fprintf(stdout, "merge interval: %d %d num %d --> %d %d num: %d (#suspBases: %d/%d)\n", spr->beg[spr->nRegions - 1], spr->end[spr->nRegions - 1],
spr->nRegions, spr->beg[spr->nRegions - 1], d, spr->nRegions, numSuspBases, spr->segmentWidth);
#endif
spr->numSlowBases += d - spr->end[spr->nRegions - 1];
spr->end[spr->nRegions - 1] = d;
}
// add new interval
else
{
ensureSlowPolymeraseRegionsCapacity(spr);
spr->beg[spr->nRegions] = a;
spr->end[spr->nRegions] = d;
spr->numSlowBases += (d - a + 1);
#if VERBOSE_SPR
fprintf(stdout, "add new interval: %d %d num: %d (#suspBases: %d/%d)\n", spr->beg[spr->nRegions], spr->beg[spr->nRegions], spr->nRegions+1,
numSuspBases, spr->segmentWidth);
#endif
spr->nRegions++;
}
}
}
}
}
#if MEASURE_TIME
end=clock();
printf("SPR TIME: %f\n",(double)(end - begin) / CLOCKS_PER_SEC);
#endif
}
static int getNextZMW(BaxData *b, ZMW* zmw)
{
#if MEASURE_TIME
clock_t begin, end;
begin = clock();
#endif
resetZMW(zmw);
#define HOLE 0
#define TYPE 1
#define ADAPTER_REGION 0
#define INSERT_REGION 1
#define HQV_REGION 2
#define START 2
#define FINISH 3
#define SCORE 4
int *region = (b->region) + (zmw->regionRow * 5);
if (zmw->regionRow == b->numRegion)
return 0;
zmw->number = region[HOLE];
zmw->status = b->holeStatus[zmw->index];
zmw->pausiness = b->pausiness[zmw->index];
zmw->prod = b->productivity[zmw->index];
zmw->type = b->readType[zmw->index];
if (zmw->index > 0)
zmw->roff += b->numEvent[zmw->index - 1];
// parse line wise all information from Regions that belong to the same ZMW
while (region[HOLE] == zmw->number && zmw->regionRow < b->numRegion)
{
switch (region[TYPE])
{
case ADAPTER_REGION:
break;
case INSERT_REGION:
ensureZMWCapacity(zmw);
zmw->insBeg[zmw->numFrag] = region[START];
zmw->insEnd[zmw->numFrag] = region[FINISH];
zmw->numFrag++;
break;
case HQV_REGION:
zmw->hqBeg = region[START];
zmw->hqEnd = region[FINISH];
zmw->regionScore = region[SCORE];
break;
default:
fprintf(stderr, "unknown region type!\n");
exit(1);
}
region += 5;
zmw->regionRow++;
}
zmw->index++;
#if MEASURE_TIME
end=clock();
printf("ZMW TIME: %f\n",(double)(end - begin) / CLOCKS_PER_SEC);
#endif
return 1;
}
// depends on subreadSelection (all, best, longest, shortest)
// 1. adjusts insert [ start, end ] interval to high quality [ start, end ] interval and if given Min/Max movie times
// 2. checks minimal subread length, (skips subreads that violate the specified minimum length)
// 3. which subreads are pulled from BaxData streams:
// all: all subreads are pulled from basecall stream
// best: first: for each subread all quality values are reported
// --> best := 0.2*(subreadLen/HQregionLength)+0.4*(#subreadSegments - #slowPolymeraseSegments/#subreadSegments)+0.4(avgQV/max(QVsFromWholeZMW))
// longest: only longest basecall stream is fetched
// shortest: only shortest basecall stream is fetched
// set toReport flag to appropriate subreads
// returns true, if ZMW contains a valid subread that should be reported, false otherwise
static int getSubreads(BaxData *b, ZMW* zmw, BAX_OPT* bopt)
{
// adjust insert start and end positions
int i, j, slen, shortIdx = -1, longIdx = -1, noSubread = 1;
memset(zmw->toReport, 0, zmw->numFrag);
for (i = 0; i < zmw->numFrag; i++)
{
// adjust insBeg/insEnd to HQ region
{
if (zmw->insBeg[i] < zmw->hqBeg)
zmw->insBeg[i] = zmw->hqBeg;
if (zmw->insEnd[i] > zmw->hqEnd)
zmw->insEnd[i] = zmw->hqEnd;
slen = zmw->insEnd[i] - zmw->insBeg[i];
zmw->len[i] = slen;
if (slen < bopt->MIN_LEN)
continue;
if (slen > bopt->MAX_LEN)
continue;
}
// set number of frames for insTimeBeg/insTimeEnd (includes also MIN/MAX_MOVIE_TIME)
{
int tmpSubreadFrames = 0;
int curBase = 0;
unsigned short *pPBF, *pWIF;
pPBF = b->preBaseFrames + zmw->roff;
pWIF = b->widthInFrames + zmw->roff;
zmw->insTimeBeg[i] = zmw->insTimeEnd[i] = -1;
for (j = 0; j < zmw->insEnd[i]; j++)
{
curBase = *(pPBF + j) + *(pWIF + j);
if (bopt->MIN_MOVIE_TIME < (tmpSubreadFrames + curBase) / FRAME_RATE)
{
if (j > zmw->insBeg[i])
{
zmw->insBeg[i] = j;
zmw->len[i] = zmw->insEnd[i] - j;
zmw->insTimeBeg[i] = tmpSubreadFrames;
break;
}
}
// adjust insTimeBeg, if minimum movie threshold starts before subread starts (default case)
if (j >= zmw->insBeg[i])
{
zmw->insTimeBeg[i] = tmpSubreadFrames;
break;
}
tmpSubreadFrames += curBase;
}
if (zmw->insTimeBeg[i] == -1)
continue; // subread ends before MIN_MOVIE_TIME
for (; j < zmw->insEnd[i]; j++)
{
curBase = *(pPBF + j) + *(pWIF + j);
if (bopt->MAX_MOVIE_TIME < (tmpSubreadFrames + curBase) / FRAME_RATE)
{
if (j < zmw->insEnd[i])
{
zmw->insEnd[i] = j;
zmw->len[i] = j - zmw->insBeg[i];
}
zmw->insTimeEnd[i] = tmpSubreadFrames;
break;
}
tmpSubreadFrames += *(pPBF + j) + *(pWIF + j);
}
if (zmw->len[i] < bopt->MIN_LEN)
continue;
if (zmw->len[i] > bopt->MAX_LEN)
continue;
if (zmw->insTimeEnd[i] == -1)
zmw->insTimeEnd[i] = tmpSubreadFrames;
}
noSubread = 0;
if (shortIdx < 0)
shortIdx = i;
else if (slen < zmw->len[shortIdx] && slen > bopt->MIN_LEN && slen < bopt->MAX_LEN)
shortIdx = i;
if (longIdx < 0)
longIdx = i;
else if (slen > zmw->len[longIdx] && slen < bopt->MAX_LEN)
longIdx = i;
zmw->toReport[i] = 1;
}
if (noSubread)
return 0;
switch (bopt->subreadSel)
{
case longest:
memset(zmw->toReport, 0, zmw->numFrag);
zmw->toReport[longIdx] = 1;
break;
case shortest:
memset(zmw->toReport, 0, zmw->numFrag);
zmw->toReport[shortIdx] = 1;
break;
case all:
case best:
default:
break;
}
int tmpOff;
for (i = 0; i < zmw->numFrag; i++)
{
if (zmw->toReport == 0)
continue;
tmpOff = zmw->roff + zmw->insBeg[i];
// set subread stream pointer
zmw->fragSequ[i] = b->baseCall + tmpOff;
zmw->fragQual[i] = b->fastQV + tmpOff;
zmw->preBaseFrames[i] = b->preBaseFrames + tmpOff;
zmw->widthInFrames[i] = b->widthInFrames + tmpOff;
zmw->delQV[i] = b->delQV + tmpOff;
zmw->delTag[i] = b->delTag + tmpOff;
zmw->insQV[i] = b->insQV + tmpOff;
zmw->mergeQV[i] = b->mergeQV + tmpOff;
zmw->subQV[i] = b->subQV + tmpOff;
// calculate average QV
j = 0;
int tmpQV = 0;
while (j < zmw->len[i])
{
tmpQV += (int) (zmw->fragQual[i][j]);
j++;
}
zmw->avgQV[i] = (tmpQV * 1.0) / zmw->len[i];
}
// determine slow polymerase chunks within subreads
getSlowPolymeraseRegions(zmw);
// if best was selected, then set report flag to best avgQV
// eval: 0.2*(subreadLen/HQregionLength)+0.4*(subreadLen/#slowPolymeraseBaseCalls)+0.4(avgQV/max(QVsFromWholeZMW))
if (bopt->subreadSel == best && zmw->numFrag > 1)
{
// get maximum QV value from all subreads of current ZMW
int max = 0;
for (i = 0; i < zmw->numFrag; i++)
for (j = 0; j < zmw->len[i]; j++)
if (zmw->fragQual[i][j] > max)
max = zmw->fragQual[i][j];
if (max == 0) // should never happen, otherwise all basecalls have qv of 0!!!
max = 1;
int bestIdx = 0;
float bestVal = .0, tmpBestVal = .0;
for (i = 0; i < zmw->numFrag; i++)
{
if (zmw->toReport == 0)
continue;
tmpBestVal = .2 * (1.0 * zmw->len[i] / (zmw->hqEnd - zmw->hqBeg)) + .4 * (1.0 * zmw->avgQV[i] / max) + .4 * (1.0 * (zmw->len[i] - zmw->spr[i].numSlowBases) / zmw->len[i]);
#if DEBUG
printf("i: %d, len: %d tmpBestVal: %f, numFrag: %d (%f, %f, %f) \n", i, zmw->len[i], tmpBestVal, zmw->numFrag,
(1.0* zmw->len[i] / (zmw->hqEnd - zmw->hqBeg)),
(1.0* zmw->avgQV[i] / max),
(1.0* (zmw->len[i]-zmw->spr[i].numSlowBases)/zmw->len[i]));
#endif
if (tmpBestVal > bestVal && zmw->len[i] >= bopt->MIN_LEN && zmw->len[i] <= bopt->MAX_LEN)
{
bestVal = tmpBestVal;
bestIdx = i;
}
}
#if DEBUG
printf("set best index: %d\n",bestIdx);
#endif
memset(zmw->toReport, 0, zmw->numFrag);
zmw->toReport[bestIdx] = 1;
}
return 1;
}
static int isInSelectedWellRange(ZMW *zmw, BAX_OPT *bopt)
{
if (bopt->wellNumbersInFileName != NULL || !bopt->numWellNumbers[bopt->curBaxFile])
return 1;
int *range = bopt->wellNumbers[bopt->curBaxFile];
int well = zmw->number;
int i;
int reps = bopt->numWellNumbers[bopt->curBaxFile];
for (i = 1; i < reps; i += 2)
{
if (range[i - 1] <= well && well <= range[i])
return 1;
}
return 0;
}
static void getBaxStats(BaxData *b, BaxStatistic *s, BAX_OPT *bopt)
{
ZMW zmw;
initZMW(&zmw);
int i = 0, j = 0;
int hqLen;
#if MEASURE_TIME
clock_t begin, end;
#endif
while (getNextZMW(b, &zmw))
{
// check for sequencing hole
if (zmw.status != SEQUENCING)
continue;
// check if hq region violates the minimum subread length precondition
hqLen = zmw.hqEnd - zmw.hqBeg;
if (bopt->MIN_LEN > hqLen)
continue;
// check if hq quality violates the minimum subread quality precondition
if (bopt->MIN_QV > zmw.regionScore)
continue;
//
if (!isInSelectedWellRange(&zmw, bopt))
continue;
if(zmw.numFrag < bopt->zmw_minNrOfSubReads)
continue;
// determine which subreads should be reported
#if MEASURE_TIME
begin=clock();
#endif
if (!getSubreads(b, &zmw, bopt))
continue;
#if MEASURE_TIME
end=clock();
printf("SUBREAD TIME: %f\n",(double)(end - begin) / CLOCKS_PER_SEC);
#endif
if(bopt->VERBOSE > 1)
printZMW(&zmw);
// derive statistics
{
#if MEASURE_TIME
begin= clock();
#endif
int bin, numSub;
s->nZMWs++;
s->cumPausiness += zmw.pausiness;
s->productiveHist[zmw.prod]++;
s->readTypeHist[zmw.type]++;
s->stateHist[zmw.status]++;
for (i = 0, numSub = 0; i < zmw.numFrag; i++)
{
if (!zmw.toReport[i])
continue;
numSub++;
if (zmw.len[i] > MAX_READ_LEN)
bin = s->nLenBins - 1;
else
bin = zmw.len[i] / s->readLenBinSize;
s->numSubreads++;
s->numSubreadBases += zmw.len[i];
s->readLengthHist[bin]++;
s->readLengthBasesHist[bin] += zmw.len[i];
s->readLengthTimeHist[bin] += zmw.insTimeEnd[i] - zmw.insTimeBeg[i];
if (zmw.spr[i].nRegions)
{
slowPolymeraseRegions *spr = zmw.spr + i;
s->nSlowPolymeraseRegionLenHist[bin]++;
for (j = 0; j < spr->nRegions; j++)
s->cumSlowPolymeraseRegionLenHist[bin] += (spr->end[j] - spr->beg[j] + 1);
}
int tmpBaseFrames = zmw.insTimeBeg[i];
for (j = 0; j < zmw.len[i]; j++)
{
tmpBaseFrames += (zmw.preBaseFrames[i][j] + zmw.widthInFrames[i][j]);
bin = (tmpBaseFrames / FRAME_RATE) / s->timeLenBinSize;
// add base calling times to appropriate histogram bins
if (bin > s->nTimBins)
bin = s->nTimBins - 1;
// add base to appropriate histogram bins
switch (zmw.fragSequ[i][j])
{
case 'A':
s->baseDistributionHist[BASE_A][bin]++;
break;
case 'C':
s->baseDistributionHist[BASE_C][bin]++;
break;
case 'G':
s->baseDistributionHist[BASE_G][bin]++;
break;
case 'T':
s->baseDistributionHist[BASE_T][bin]++;
break;
default:
s->baseDistributionHist[BASE_N][bin]++;
break;
}
// add quality values to appropriate histogram bins
s->cumTimeDepQVs[NUC_COUNT][bin]++;
s->cumTimeDepQVs[QV_SUM][bin] += (int) zmw.fragQual[i][j];
s->cumTimeDepQVs[DEL_SUM][bin] += (int) zmw.delQV[i][j];
s->cumTimeDepQVs[INS_SUM][bin] += (int) zmw.insQV[i][j];
s->cumTimeDepQVs[MER_SUM][bin] += (int) zmw.mergeQV[i][j];
s->cumTimeDepQVs[SUB_SUM][bin] += (int) zmw.subQV[i][j];
// check time dependent slow polymerase region
if (isBaseInSlowPolymeraseRegion(zmw.spr, j + zmw.insBeg[i]))
s->cumSlowPolymeraseRegionTimeHist[bin]++;
}
}
bin = numSub;
if (bin >= MAX_SUBREADS)
bin = MAX_SUBREADS;
s->subreadHist[bin]++;
#if MEASURE_TIME
end=clock();
printf("DERIVE TIME: %f\n",(double)(end - begin) / CLOCKS_PER_SEC);
#endif
}
// fasta output
#if MEASURE_TIME
begin=clock();
#endif
if (bopt->fastaOut)
{
for (i = 0; i < zmw.numFrag; i++)
{
if (zmw.toReport[i] == 0)
continue;
fprintf(bopt->fastaFile, ">%.*s/%d/%d_%d RQ=0.%d readType=%d", b->shortNameEnd - b->shortNameBeg, b->fullName + b->shortNameBeg, zmw.number, zmw.insBeg[i], zmw.insEnd[i], zmw.regionScore, zmw.type);
if (zmw.spr[i].nRegions)
{
slowPolymeraseRegions *spr = zmw.spr + i;
fprintf(bopt->fastaFile, " spr=");
for (j = 0; j < spr->nRegions; j++)
{
fprintf(bopt->fastaFile, "%d,%d", spr->beg[j], spr->end[j]);
if (j + 1 < spr->nRegions)
fprintf(bopt->fastaFile, ",");
}
}
fprintf(bopt->fastaFile, " avgQV=%d Len=%d", (int) (zmw.avgQV[i] * 1000), zmw.len[i]);
if(b->bindingKit != NULL && b->sequencingKit != NULL && b->softwareVersion != NULL)
fprintf(bopt->fastaFile, " chemistry=%s|%s|%s", b->bindingKit, b->sequencingKit, b->softwareVersion);
if(b->sequencingChemistry != NULL)
fprintf(bopt->fastaFile, "|%s", b->sequencingChemistry);
fprintf(bopt->fastaFile, "\n");
fprintf(bopt->fastaFile, "%.*s\n", zmw.len[i], zmw.fragSequ[i]);
}
}
// fastq output
if (bopt->fastqOut)
{
for (i = 0; i < zmw.numFrag; i++)
{
if (zmw.toReport[i] == 0)
continue;
fprintf(bopt->fastqFile, "@%.*s/%d/%d_%d RQ=0.%d readType=%d", b->shortNameEnd - b->shortNameBeg, b->fullName + b->shortNameBeg, zmw.number, zmw.insBeg[i], zmw.insEnd[i], zmw.regionScore, zmw.type);
if (zmw.spr[i].nRegions)
{
slowPolymeraseRegions *spr = zmw.spr + i;
fprintf(bopt->fastqFile, " spr=");
for (j = 0; j < spr->nRegions; j++)
{
fprintf(bopt->fastqFile, "%d,%d", spr->beg[j], spr->end[j]);
if (j + 1 < spr->nRegions)
fprintf(bopt->fastqFile, ",");
}
}
fprintf(bopt->fastqFile, "\n");
fprintf(bopt->fastqFile, "%.*s\n+\n", zmw.len[i], zmw.fragSequ[i]);
for (j = 0; j < zmw.len[i]; j++)
fputc(zmw.fragQual[i][j] + PHRED_OFFSET, bopt->fastqFile);
fputc('\n', bopt->fastqFile);
}
}
// quiva output
if (bopt->quivaOut)
{
for (i = 0; i < zmw.numFrag; i++)
{
if (zmw.toReport[i] == 0)
continue;
fprintf(bopt->quivaFile, "@%.*s/%d/%d_%d RQ=0.%d\n", b->shortNameEnd - b->shortNameBeg, b->fullName + b->shortNameBeg, zmw.number, zmw.insBeg[i], zmw.insEnd[i], zmw.regionScore);
for (j = 0; j < zmw.len[i]; j++)
fputc(zmw.delQV[i][j] + PHRED_OFFSET, bopt->quivaFile);
fputc('\n', bopt->quivaFile);
fprintf(bopt->quivaFile, "%.*s\n", zmw.len[i], zmw.delTag[i]);
for (j = 0; j < zmw.len[i]; j++)
fputc(zmw.insQV[i][j] + PHRED_OFFSET, bopt->quivaFile);
fputc('\n', bopt->quivaFile);
for (j = 0; j < zmw.len[i]; j++)
fputc(zmw.mergeQV[i][j] + PHRED_OFFSET, bopt->quivaFile);
fputc('\n', bopt->quivaFile);
for (j = 0; j < zmw.len[i]; j++)
fputc(zmw.subQV[i][j] + PHRED_OFFSET, bopt->quivaFile);
fputc('\n', bopt->quivaFile);
}
}
#if MEASURE_TIME
end = clock();
printf("OUT TIME: %f\n",(double)(end - begin) / CLOCKS_PER_SEC);
#endif
#if DEBUG
printf("\n zmw %d (idx: %d) hq: %d %d %d roff %d\n ", zmw.number, zmw.index, zmw.hqBeg, zmw.hqEnd, zmw.regionScore, zmw.roff);
for(i=0; i<zmw.numFrag; i++)
printf("ins %d: %d %d -> report? %d\n ",i, zmw.insBeg[i], zmw.insEnd[i], zmw.toReport[i]);
#endif
}
}
int main(int argc, char* argv[])
{
// Check that zlib library is present
if (!H5Zfilter_avail(H5Z_FILTER_DEFLATE))
{
fprintf(stderr, "%s: zlib library is not present, check build/installation\n", argv[0]);
exit(1);
}
#if MEASURE_TIME
clock_t begin, end;
begin = clock();
#endif
BAX_OPT *bopt = parseBaxOptions(argc, argv);
if(bopt->VERBOSE > 1)
printBaxOptions(bopt);
/* here, do your time-consuming job */
BaxData b;
initBaxData(&b);
BaxStatistic s;
initBaxStatistic(&s, bopt);
printBaxStatisticHeader(&s, bopt);
#if MEASURE_TIME
end = clock();
printf("INIT TIME: %f\n", (double) (end - begin) / CLOCKS_PER_SEC);
#endif
{
int i, ecode;
for (i = 0; i < bopt->nBax; i++)
{
bopt->curBaxFile = i;
if (!bopt->CUMULATIVE)
resetBaxStatistic(&s);
initBaxNames(&b, bopt->baxIn[i]);
#if MEASURE_TIME
begin = clock();
#endif
ecode = getBaxData(&b, bopt); // parse bax.h5 file
#if MEASURE_TIME
end = clock();
printf("FETCH TIME: %f\n", (double) (end - begin) / CLOCKS_PER_SEC);
#endif
if (ecode >= 0)
{
s.nFiles++;
#if MEASURE_TIME
begin = clock();
#endif
getBaxStats(&b, &s, bopt);
#if MEASURE_TIME
end = clock();
printf("EXTRACT TIME: %f\n", (double) (end - begin) / CLOCKS_PER_SEC);
#endif
if (!bopt->CUMULATIVE)
printBaxStatistic(&s, bopt->statFile);
fflush(stdout);
}
else
{
fprintf(stderr, " Skipping %s due to failure\n", b.fullName);
printBaxError(ecode);
}
}
if (bopt->CUMULATIVE)
printBaxStatistic(&s, bopt->statFile);
}
freeBaxData(&b);
freeBaxStatistic(&s);
freeBaxOptions(bopt);
return 0;
}
|
rileyweber13/exercism-progress
|
c/isogram/src/isogram.c
|
<gh_stars>1-10
#include "isogram.h"
bool is_isogram(const char phrase[]){
int i = 0;
// we can stop on the last character that is part of the actual string and not
// the null terminator. This is because there is no where left in the string
// for the last character in the string to be repeated.
if (phrase == NULL){
return false;
}
if (phrase[0] == '\0'){
return true;
}
while (phrase[i + 1] != '\0') {
if(isalpha(phrase[i])){
int j = i + 1;
while(phrase[j] != '\0'){
if(tolower(phrase[i]) == tolower(phrase[j])){
return false;
}
j++;
}
}
i++;
}
return true;
}
|
rileyweber13/exercism-progress
|
c/isogram/src/test.c
|
#include <stdbool.h>
#include <stdio.h>
int main(int argc, const char* argv[]){
bool a = true;
bool b = false;
bool c = true;
bool d = false;
bool e = a + b;
bool f = b + d;
bool g = b + d + c;
printf("%d\n",a);
printf("%d\n",e);
printf("%d\n",f);
printf("%d\n",g);
}
|
rileyweber13/exercism-progress
|
c/word-count/src/word_count.c
|
#include "word_count.h"
int word_count(const char* input_text, word_count_word_t* words){
unsigned uniqueWords = 1;
for(unsigned i = 0; i < strlen(input_text); i++){
// for(unsigned i = 0; i < sizeof(input_text)/sizeof(input_text[0]); i++){
if(input_text[i] == ' '){
uniqueWords++;
}
else {
char currentWord[MAX_WORD_LENGTH];
unsigned j = 0;
do {
currentWord[j] = input_text[i];
j++;
i++;
} while (input_text[i] != ' ');
currentWord[j] = '\0';
bool wordNotInDict = true;
for(unsigned i = 0; i < MAX_WORDS; i ++){
if(strcmp(currentWord, words[i].text)){
wordNotInDict = false;
words[i].count++;
}
}
// if word does not exist
if (wordNotInDict){
strcpy(words[uniqueWords - 1].text, currentWord);
words[uniqueWords - 1].count = 1;
}
}
}
// just to make tests fail
// unsigned x = strlen(input_text);
// x *= uniqueWords;
// words[0].text[0] = '1';
// words[0].text[1] = '\0';
// words[0].count = 1;
return uniqueWords;
}
|
rileyweber13/exercism-progress
|
c/acronym/src/acronym.c
|
#include "acronym.h"
// taken from the FreeBSD source code
// http://fxr.watson.org/fxr/source/libkern/strlen.c?v=DFBSD<Paste>
// unsigned strlen(const char *str)
// {
// const char *s;
// for (s = str; *s; ++s);
// return(s - str);
// }
char* abbreviate(const char * phrase){
if(phrase == NULL || phrase[0] == '\0'){
return NULL;
}
size_t phrase_len = strlen(phrase);
char* result = malloc(1000);
result[0] = toupper(phrase[0]);
unsigned next_in_result = 1;
bool next_char_part_of_acronym = false;
for(size_t i = 1; i < phrase_len; i++){
if (next_char_part_of_acronym){
result[next_in_result] = toupper(phrase[i]);
next_char_part_of_acronym = false;
next_in_result++;
}
else if (phrase[i] == ' ' || phrase[i] == '-'){
next_char_part_of_acronym = true;
}
}
return result;
}
|
rileyweber13/exercism-progress
|
c/isogram/src/isogram.h
|
#ifndef ISOGRAM_H
#define ISOGRAM_H
#include <stdbool.h>
#include <stdlib.h>
#include <ctype.h>
bool is_isogram(const char phrase[]);
#endif
|
JumpLink/node-gtk
|
src/boxed.h
|
#pragma once
#include <nan.h>
#include <node.h>
#include <girepository.h>
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;
namespace GNodeJS {
class Boxed {
public:
void* data;
GType g_type;
GIBaseInfo * info;
unsigned long size;
Nan::Persistent<Object> *persistent;
static size_t GetSize (GIBaseInfo *boxed_info) ;
};
Local<Function> MakeBoxedClass (GIBaseInfo *info);
Local<FunctionTemplate> GetBoxedTemplate (GIBaseInfo *info, GType gtype);
Local<Value> WrapperFromBoxed (GIBaseInfo *info, void *data);
void * BoxedFromWrapper (Local<Value>);
};
|
JumpLink/node-gtk
|
src/macros.h
|
#pragma once
#define FILE_NAME (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
#ifdef __PRETTY_FUNCTION__
#define FUNCTION_NAME __PRETTY_FUNCTION__
#else
#define FUNCTION_NAME __func__
#endif
#define assert_printf(condition, ...) \
do { \
if (G_UNLIKELY(!(condition))) { \
printf("\x1b[1;91m%s: %s: %i: Assertion '%s' failed:\x1b[0m ", \
FILE_NAME, FUNCTION_NAME, __LINE__, #condition); \
printf(__VA_ARGS__); \
g_assert_not_reached (); \
} \
} while (0) \
/*
* V8 Macros
*/
#define UTF8(s) Nan::New<v8::String> (s).ToLocalChecked()
#define RETURN(s) info.GetReturnValue().Set(s)
#define TO_OBJECT(v) Nan::To<Object> (v).ToLocalChecked()
#define TO_STRING(v) Nan::To<String> (v).ToLocalChecked()
#define TO_LONG(v) Nan::To<int64_t> (v).ToChecked()
|
xiaogou56/WiOSDemo
|
WiOSDemo/WThirdVC.h
|
<reponame>xiaogou56/WiOSDemo<gh_stars>0
//
// WThirdVC.h
// WiOSDemo
//
// Created by xiaowei.li on 16/2/20.
// Copyright © 2016年 Wayne. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface WThirdVC : UITableViewController
@end
|
xiaogou56/WiOSDemo
|
DesignPattern/builder/ChasingGameDirector.h
|
//
// ChasingGameDirector.h
// WiOSDemo
//
// Created by Wayne on 16/3/22.
// Copyright © 2016年 Wayne. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Character.h"
#import "AbstructCharacterBuilder.h"
@interface ChasingGameDirector : NSObject
// 同样的,我们还可以再添加一个创建Enemy的方法,另外我们也可以直接新增一个enemy的concrete builder来实现此功能,只不过在这里没有太大意义;
- (Character *)createPlayer:(AbstructCharacterBuilder *)builder;
@end
|
xiaogou56/WiOSDemo
|
3rd/TencentOpenApi_IOS_Bundle.bundle/QQSDKCall.h
|
//
// QQSDKCall.h
// WiOSDemo
//
// Created by Wayne on 16/2/22.
// Copyright © 2016年 Wayne. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface QQSDKCall : NSObject
@end
|
xiaogou56/WiOSDemo
|
chapter6/WBookActivity.h
|
//
// WBookActivity.h
// WiOSDemo
//
// Created by Wayne on 16/2/20.
// Copyright © 2016年 Wayne. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface WBookActivity : UIActivity
@end
|
xiaogou56/WiOSDemo
|
WiOSDemo/AppDelegate.h
|
<reponame>xiaogou56/WiOSDemo<gh_stars>0
//
// AppDelegate.h
// WiOSDemo
//
// Created by Wayne on 16/2/20.
// Copyright © 2016年 Wayne. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
xiaogou56/WiOSDemo
|
WiOSDemo/SecondViewController.h
|
<reponame>xiaogou56/WiOSDemo<gh_stars>0
//
// SecondViewController.h
// WiOSDemo
//
// Created by Wayne on 16/2/20.
// Copyright © 2016年 Wayne. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController
@end
|
xiaogou56/WiOSDemo
|
DesignPattern/builder/Character.h
|
<reponame>xiaogou56/WiOSDemo
//
// Character.h
// WiOSDemo
//
// Created by Wayne on 16/3/22.
// Copyright © 2016年 Wayne. All rights reserved.
//
#import <Foundation/Foundation.h>
/*
* Character就是客户最终想要的东西,东西就是东西,它只有几个属性,当然可以给上初始值
*/
@interface Character : NSObject
@property (nonatomic, assign) float protection;
@property (nonatomic, assign) float strength;
@end
|
xiaogou56/WiOSDemo
|
DesignPattern/builder/ConcreteCharacterBuilder.h
|
//
// StandardCharacterBuilder.h
// WiOSDemo
//
// Created by Wayne on 16/3/22.
// Copyright © 2016年 Wayne. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "AbstructCharacterBuilder.h"
/**
* 继承自CharacterBuilder类(其他语言中是个抽象类),给予各个方法以具体的实现;
*/
@interface ConcreteCharacterBuilder : AbstructCharacterBuilder
@end
|
xiaogou56/WiOSDemo
|
QQSDKDef.h
|
<gh_stars>0
//
// QQSDKDef.h
// WiOSDemo
//
// Created by Wayne on 16/2/22.
// Copyright © 2016年 Wayne. All rights reserved.
//
#ifndef QQSDKDef_h
#define QQSDKDef_h
//response
#define kCGIRequest @"kTencentCGIRequest"
#define kResponse @"kResponse"
#define kTencentOAuth @"oauth"
#define kUIViewController @"UIViewController"
#define kTencentRespObj @"kTencentRespObj"
//delagate
//login
#define kLoginSuccessed @"loginSuccessed"
#define kLoginFailed @"loginFailed"
#define kLoginCancelled @"loginCancelled"
//qzone
#define kGetUserInfoResponse @"getUserInfoResponse"
#define kAddShareResponse @"addShareResponse"
#define kUploadPicResponse @"uploadPicResponse"
#define kGetListAlbumResponse @"getListResponse"
#define kGetListPhotoResponse @"getListPhotoResponse"
#define kAddTopicResponse @"addTopicResponse"
#define kChangePageFansResponse @"changePageFansResponse"
#define kAddAlbumResponse @"kAddAlbumResponse"
#define kAddOneBlogResponse @"kAddOneBlogResponse"
#define kSetUserHeadPicResponse @"kSetUserHeadPicResponse"
#define kGetVipInfoResponse @"kGetVipInfoResponse"
#define kGetVipRichInfoResponse @"kGetVipRichInfoResponse"
#define kSendStoryResponse @"kSendStoryResponse"
#define kCheckPageFansResponse @"kCheckPageFansResponse"
//TCAPIRequest
#define kTencentCGIRequest @"kTencentCGIRequest"
//tencentApi
#define kTencentApiResp @"kTencentApiResp"
//????
#define kCloseWnd @"kCloseWnd"
//string
#endif /* QQSDKDef_h */
|
xiaogou56/WiOSDemo
|
DesignPattern/builder/AbstructCharacterBuilder.h
|
<filename>DesignPattern/builder/AbstructCharacterBuilder.h
//
// CharacterBuilder.h
// WiOSDemo
//
// Created by Wayne on 16/3/22.
// Copyright © 2016年 Wayne. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Character.h"
/**
* 在其他语言里面,这个类其实是个抽象类或者接口,只定义了一些抽象方法,没有实现,但iOS不支持这种特性,所以可以简单的赋值。
*/
@interface AbstructCharacterBuilder : NSObject
@property (nonatomic, readonly, strong) Character *character;
- (AbstructCharacterBuilder *)buildProtection:(float)pvalue;
- (AbstructCharacterBuilder *)buildStregth:(float)pvalue;
@end
|
xiaogou56/WiOSDemo
|
WiOSDemo/FirstViewController.h
|
//
// FirstViewController.h
// WiOSDemo
//
// Created by Wayne on 16/2/20.
// Copyright © 2016年 Wayne. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface FirstViewController : UITableViewController
@end
|
xiaogou56/WiOSDemo
|
3rd/QQSDKCall.h
|
<gh_stars>0
//
// QQSDKCall.h
// WiOSDemo
//
// Created by Wayne on 16/2/22.
// Copyright © 2016年 Wayne. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/TencentOAuthObject.h>
#import <TencentOpenAPI/TencentApiInterface.h>
@interface QQSDKCall : NSObject<TencentSessionDelegate, TCAPIRequestDelegate>
+ (QQSDKCall *)getInstance;
+ (void)resetSDK;
+ (void)showInvalidTokenOrOpenIDMessage;
@property (nonatomic, retain)TencentOAuth *oauth;
@end
|
xiaogou56/WiOSDemo
|
WDemoCellInfo.h
|
//
// WDemoCellInfo.h
// WiOSDemo
//
// Created by xiaowei.li on 16/2/22.
// Copyright © 2016年 Wayne. All rights reserved.
//
#import <Foundation/Foundation.h>
#define WDemoCellMapSelector(strTitle, strMethod) [WDemoCellInfo cellTitle:(strTitle) target:self sel:@selector(strMethod) userInfo:nil]
#define WDemoGetCellTitle(arrItem) ((WDemoCellInfo *)arrItem).title
#define WDemoDoCell(arrItem) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
{WDemoCellInfo *info = (WDemoCellInfo *)arrItem; \
[info.target performSelector:info.sel withObject:info.userInfo];} \
_Pragma("clang diagnostic pop")
@interface WDemoCellInfo : NSObject
@property (nonatomic, strong)NSString *title;
@property (nonatomic, assign)id target;
@property (nonatomic, assign)SEL sel;
@property (nonatomic, strong)id userInfo;
+ (WDemoCellInfo *)cellTitle:(NSString *)strTitle target:(id)target sel:(SEL)sel userInfo:(id) userInfo;
@end
|
dunneev/oboe
|
src/common/DataConversionFlowGraph.h
|
<gh_stars>1-10
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OBOE_OBOE_FLOW_GRAPH_H
#define OBOE_OBOE_FLOW_GRAPH_H
#include <memory>
#include <stdint.h>
#include <sys/types.h>
#include <flowgraph/ChannelCountConverter.h>
#include <flowgraph/MonoToMultiConverter.h>
#include <flowgraph/MultiToMonoConverter.h>
#include <flowgraph/SampleRateConverter.h>
#include <oboe/Definitions.h>
#include "AudioSourceCaller.h"
#include "FixedBlockWriter.h"
namespace oboe {
class AudioStream;
class AudioSourceCaller;
/**
* Convert PCM channels, format and sample rate for optimal latency.
*/
class DataConversionFlowGraph : public FixedBlockProcessor {
public:
DataConversionFlowGraph()
: mBlockWriter(*this) {}
void setSource(const void *buffer, int32_t numFrames);
/** Connect several modules together to convert from source to sink.
* This should only be called once for each instance.
*
* @param sourceFormat
* @param sourceChannelCount
* @param sinkFormat
* @param sinkChannelCount
* @return
*/
oboe::Result configure(oboe::AudioStream *sourceStream, oboe::AudioStream *sinkStream);
int32_t read(void *buffer, int32_t numFrames, int64_t timeoutNanos);
int32_t write(void *buffer, int32_t numFrames);
int32_t onProcessFixedBlock(uint8_t *buffer, int32_t numBytes) override;
DataCallbackResult getDataCallbackResult() {
return mCallbackResult;
}
private:
std::unique_ptr<flowgraph::FlowGraphSourceBuffered> mSource;
std::unique_ptr<AudioSourceCaller> mSourceCaller;
std::unique_ptr<flowgraph::MonoToMultiConverter> mMonoToMultiConverter;
std::unique_ptr<flowgraph::MultiToMonoConverter> mMultiToMonoConverter;
std::unique_ptr<flowgraph::ChannelCountConverter> mChannelCountConverter;
std::unique_ptr<resampler::MultiChannelResampler> mResampler;
std::unique_ptr<flowgraph::SampleRateConverter> mRateConverter;
std::unique_ptr<flowgraph::FlowGraphSink> mSink;
FixedBlockWriter mBlockWriter;
DataCallbackResult mCallbackResult = DataCallbackResult::Continue;
AudioStream *mFilterStream = nullptr;
std::unique_ptr<uint8_t[]> mAppBuffer;
int64_t mFramePosition = 0;
};
}
#endif //OBOE_OBOE_FLOW_GRAPH_H
|
Gmaurya/data-structure-and-algorithms
|
DynamicPrograming/Edit-Distance.c
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int minimum_of_two(int x,int y){
if (x > y)
return y;
else return x;
}
int minimum(int x, int y, int z){
return minimum_of_two(minimum_of_two(x, y), z);
}
int m;
int n;
int Convert(char * str1, char * str2){
int dp[m+1][n+1];
int i=0;
int j=0;
for (i=0; i<=m; i++){
for (j=0; j<=n; j++){
if (i == 0){
dp[i][j] = j;
}
else if (j==0){
dp[i][j] = i;
}
else if (str1[i-1] == str2[j-1]){
dp[i][j] = dp[i-1][j-1];
}
else
dp[i][j] = minimum(dp[i][j-1]+1, dp[i-1][j]+1, dp[i-1][j-1]+1);
}
}
i = m;
j = n;
while (i!=0 && j!=0) {
if (str1[i-1] == str2[j-1]){
i--;
j--;
}
else{
if (dp[i-1][j-1]+1==dp[i][j]){
printf( "Replace '%c' from position %d with '%c'.\n", str1[i-1],i,str2[j-1]);
i--;
j--;
}
else if (dp[i-1][j]+1==dp[i][j]){
printf("Remove '%c' from position %d. \n", str1[i-1],i);
i--;
}
else{
printf( "Insert '%c' at position %d. \n", str2[j-1],j );
j--;
}
}
}
while(j!=0){
printf( "Insert '%c' at position %d. \n" , str2[j-1],j);
j--;
}
while(i!=0){
printf( "Remove '%c' from position %d. \n", str1[i-1],i);
i--;
}
return dp[m][n];
}
int main(){
char *str1=(char *)malloc(sizeof(char));
char *str2=(char *)malloc(sizeof(char));
printf("Please enter the first string:\n");
scanf("%s",str1);
printf("Please enter the second string:\n");
scanf("%s",str2);
m=strlen(str1);
n=strlen(str2);
printf("\n\nThe set of required operations are:\n\n");
int minm=Convert(str1,str2);
printf("\nThe minimum cost incurred: %d\n",minm);
return 0;
}
/*
Test case :
sunday
saturday
Output: 3
Last three and first characters are same. We basically
need to convert "un" to "atur". This can be done using
below three operations.
Replace 'n' with 'r', insert t, insert a
*/
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/components/gpio_manager/relay_board.h
|
<gh_stars>1-10
#ifndef PROVISIONING_ESP32_SMART_DESK_COMPONENTS_GPIO_MANAGER_RELAY_BOARD_H_
#define PROVISIONING_ESP32_SMART_DESK_COMPONENTS_GPIO_MANAGER_RELAY_BOARD_H_
#include "driver/gpio.h"
struct Relay
{
gpio_num_t gpio_num;
gpio_mode_t gpio_mode;
gpio_pull_mode_t pull_mode;
uint32_t initial_level;
uint32_t active_level;
uint32_t inactive_level;
};
esp_err_t init_relays(uint8_t relay_pins[], size_t relay_num, struct Relay **relays_p);
esp_err_t turn_relay_on(struct Relay *relay);
esp_err_t turn_relay_off(struct Relay *relay);
#endif // PROVISIONING_ESP32_SMART_DESK_COMPONENTS_GPIO_MANAGER_RELAY_BOARD_H_
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/components/debug_utils/board_info.h
|
#ifndef PROVISIONING_ESP32_SMART_DESK_COMPONENTS_DEBUG_UTILS_BOARD_INFO_H_
#define PROVISIONING_ESP32_SMART_DESK_COMPONENTS_DEBUG_UTILS_BOARD_INFO_H_
#include "esp_system.h"
void get_board_info(esp_chip_info_t chip_info, int flash_chip_size, int free_heap_size);
#endif // PROVISIONING_ESP32_SMART_DESK_COMPONENTS_DEBUG_UTILS_BOARD_INFO_H_
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/components/debug_utils/app_info.h
|
<gh_stars>1-10
#ifndef PROVISIONING_ESP32_SMART_DESK_COMPONENTS_DEBUG_UTILS_APP_INFO_H_
#define PROVISIONING_ESP32_SMART_DESK_COMPONENTS_DEBUG_UTILS_APP_INFO_H_
void get_app_info();
void get_tasks_info();
#endif // PROVISIONING_ESP32_SMART_DESK_COMPONENTS_DEBUG_UTILS_APP_INFO_H_
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/main/smart_desk_main.c
|
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include "esp_event.h"
#include "esp_log.h"
#include "esp_spi_flash.h"
#include "esp_system.h"
#include "esp_task_wdt.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "sdkconfig.h"
#include "app_info.h"
#include "board_info.h"
#include "hd_44780.h"
#include "i2c_utils.h"
#include "relay_board.h"
#include "rsa_utils.h"
#include "ultrasonic.h"
#include "actuators_controller.h"
#include "ip_address_manager.h"
#include "nvs_manager.h"
#include "provisioning_manager.h"
#include "wifi_connection_manager.h"
#define SDA_PIN 23
#define SCL_PIN 22
// The PCF8574 has a 100 kHz I2C interface
#define I2C_MASTER_CLOCK_FREQUENCY_HZ 100000
#define LCD_ADDR 0x27
#define LCD_COLS 20
#define LCD_ROWS 4
#define ULTRASONIC_MAX_DISTANCE_CM 400 // 4m max
#define ULTRASONIC_MIN_DISTANCE_CM 2 // 2cm min
#define ULTRASONIC_TRIGGER_GPIO GPIO_NUM_27
#define ULTRASONIC_ECHO_GPIO GPIO_NUM_15
#define RELAY_COUNT 4
#define RELAY_1_GPIO GPIO_NUM_33
#define RELAY_2_GPIO GPIO_NUM_32
#define RELAY_3_GPIO GPIO_NUM_14
#define RELAY_4_GPIO GPIO_NUM_12
#define RSA_KEY_GEN_STACK_SIZE 25000
#define RSA_KEY_GEN_TASK_PRIORITY 2
#define RSA_KEY_SIZE DEFAULT_RSA_KEY_SIZE
#define RSA_KEY_STORAGE_NAMESPACE DEFAULT_RSA_KEY_STORAGE_NAMESPACE
#define ACTUATORS_COUNT 2
// The controller is on the floor, enclosed in a box,
// and the distance sensor is on one side of the box.
//
// 110 cm --------- Desk top (@ max extension)
//
// 75 cm --------- Desk top
// | |
// 16 cm | ^ | distance sensor
// | | | |
// 0 cm --------- Floor
#define MAX_ACTUATORS_EXTENSION_CM 35 // Maximum actuators extension
#define MIN_DESK_HEIGHT_CM 70 // Minimum distance between the floor and (bottom of) the desk top
#define MAX_DESK_HEIGHT_CM MIN_DESK_HEIGHT_CM + MAX_ACTUATORS_EXTENSION_CM // Moximum distance between the floor and the (bottom of) desk top
#define CONTROLLER_ENCLOSURE_HEIGHT_CM 16 // Distance between the distance sensor and the floor
#define MIN_DISTANCE_CM MIN_DESK_HEIGHT_CM - CONTROLLER_ENCLOSURE_HEIGHT_CM // Minimum distance between the distance sensor and the desk top
#define MAX_DISTANCE_CM MIN_DISTANCE_CM + MAX_ACTUATORS_EXTENSION_CM // Maximum distance between the distance sensor and the desk top
#define TOLERANCE_EXTENSION_CM 2
static const char *TAG = "smart_desk";
// Need this in both CPU tasks
static ultrasonic_sensor_t ultrasonic_sensor = {
.trigger_pin = ULTRASONIC_TRIGGER_GPIO,
.echo_pin = ULTRASONIC_ECHO_GPIO,
.min_distance = ULTRASONIC_MIN_DISTANCE_CM,
.max_distance = ULTRASONIC_MAX_DISTANCE_CM};
void vCpu1Task(void *pvParameters)
{
struct RsaKeyGenerationOptions *rsa_key_gen_parameters = (struct RsaKeyGenerationOptions *)pvParameters;
const char *rsa_storage_namespace = rsa_key_gen_parameters->storage_namespace;
const char *rsa_public_key_filename = rsa_key_gen_parameters->public_key_filename;
if (!blob_exists(rsa_storage_namespace, rsa_public_key_filename) || !blob_exists(rsa_storage_namespace, rsa_key_gen_parameters->private_key_filename))
{
ESP_LOGI(TAG, "Generating RSA keypair...");
generate_rsa_keypair(*rsa_key_gen_parameters);
}
size_t public_key_length = 0;
ESP_ERROR_CHECK(get_blob_length(rsa_storage_namespace, rsa_public_key_filename, &public_key_length));
char *rsa_public_key = malloc(public_key_length + 1);
ESP_ERROR_CHECK(load_blob(rsa_storage_namespace, rsa_public_key_filename, (void *)rsa_public_key, public_key_length));
ESP_LOGI(TAG, "RSA Public key (length: %u):\n%s", public_key_length, rsa_public_key);
free(rsa_public_key);
esp_task_wdt_add(xTaskGetIdleTaskHandleForCPU(1));
ESP_LOGI(TAG, "Starting to measure distance...");
// FreeRTOS tasks must not terminate
while (true)
{
uint32_t distance;
esp_err_t res = ultrasonic_measure_cm(&ultrasonic_sensor, &distance);
if (res == ESP_OK)
ESP_LOGD(TAG, "Measured distance: %d cm", distance);
vTaskDelay(100 / portTICK_PERIOD_MS);
}
}
void app_main(void)
{
ESP_ERROR_CHECK(i2c_master_driver_initialize(SDA_PIN, SCL_PIN, I2C_MASTER_CLOCK_FREQUENCY_HZ));
esp_err_t ret;
char err_msg[20];
do
{
if ((ret = i2c_detect_device(LCD_ADDR)) != ESP_OK)
{
ESP_LOGE(TAG, "%s during I2C device detection at address 0x%02x. Retrying...", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)), LCD_ADDR);
}
} while (ret != ESP_OK);
do
{
// i2c expander - LCD Pin mappings
// P0 -> RS
// P1 -> RW
// P2 -> E
// P3 -> Backlight (b)
// P4 -> D4
// P5 -> D5
// P6 -> D6
// P7 -> D7
if ((ret = LCD_init(LCD_ADDR, LCD_COLS, LCD_ROWS, 2, 1, 0, 4, 5, 6, 7, 3, LCD_FUNCTION_SET_4_BIT)) != ESP_OK)
{
ESP_LOGE(TAG, "%s during LCD (I2C address 0x%02x) initialization. Retrying...", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)), LCD_ADDR);
}
} while (ret == ESP_FAIL || ret == ESP_ERR_TIMEOUT);
bool lcd_available = true;
if (ret == ESP_FAIL)
{
lcd_available = false;
ESP_LOGW(TAG, "The LCD (I2C address 0x%02x) is not available.", LCD_ADDR);
}
esp_chip_info_t chip_info;
esp_chip_info(&chip_info);
get_board_info(chip_info, spi_flash_get_chip_size(), esp_get_free_heap_size());
get_app_info();
ESP_LOGI(TAG, "Creating the default loop...");
ESP_ERROR_CHECK(esp_event_loop_create_default());
ESP_LOGI(TAG, "Initializing the non-volatile storage flash...");
ESP_ERROR_CHECK(initialize_nvs_flash());
if (lcd_available)
{
ESP_LOGI(TAG, "Preparing the default LCD visualization...");
LCD_clearScreen();
LCD_home();
LCD_writeStr("IP: ");
LCD_setCursor(0, 1);
LCD_writeStr("Distance: cm");
}
ESP_LOGI(TAG, "Registering event handlers...");
register_wifi_manager_event_handlers();
register_ip_address_manager_event_handlers();
register_provisioning_manager_event_handlers();
if (lcd_available)
{
ESP_LOGI(TAG, "Registering LCD event handlers...");
ESP_ERROR_CHECK(register_lcd_events());
}
get_tasks_info();
ESP_LOGI(TAG, "Initializing the distance sensor...");
ultrasonic_init(&ultrasonic_sensor);
struct RsaKeyGenerationOptions rsa_key_generation_options = {
RSA_KEY_SIZE,
DEFAULT_RSA_PRIVATE_KEY_FILENAME,
DEFAULT_RSA_PUBLIC_KEY_FILENAME,
RSA_KEY_STORAGE_NAMESPACE};
xTaskCreatePinnedToCore(vCpu1Task, "cpu1_heavy", RSA_KEY_GEN_STACK_SIZE, &rsa_key_generation_options, RSA_KEY_GEN_TASK_PRIORITY, NULL, 1);
start_wifi_provisioning();
size_t relays_num = RELAY_COUNT;
struct Relay *relays;
uint8_t relay_pins[] = {RELAY_1_GPIO, RELAY_2_GPIO, RELAY_3_GPIO, RELAY_4_GPIO};
ESP_ERROR_CHECK(init_relays(relay_pins, relays_num, &relays));
ESP_LOGI(TAG, "Completed relays initialization. Pointer to relays array: %p", relays);
struct Actuator **actuators;
size_t actuators_num = relays_num / 2;
ESP_ERROR_CHECK(init_actuators(relays, relays_num, &actuators, actuators_num));
ESP_LOGI(TAG, "Completed actuators initialization. Pointer to actuators pointers array: %p", actuators);
ESP_ERROR_CHECK(register_actuators_events(actuators, actuators_num));
uint32_t distance;
ESP_ERROR_CHECK(ultrasonic_measure_cm(&ultrasonic_sensor, &distance));
ESP_LOGI(TAG, "Max reachable distance: %u cm, min reachable distance: %u cm, current distance: %u cm", MAX_DISTANCE_CM, MIN_DISTANCE_CM, distance);
if (distance <= MIN_DISTANCE_CM)
{
ESP_ERROR_CHECK(start_actuators_extension(MAX_DISTANCE_CM));
}
else
{
ESP_ERROR_CHECK(start_actuators_retraction(MIN_DISTANCE_CM - TOLERANCE_EXTENSION_CM));
}
}
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/components/debug_utils/app_info.c
|
<filename>provisioning/esp32/smart_desk/components/debug_utils/app_info.c<gh_stars>1-10
#include <stdio.h>
#include <string.h>
#include "esp_log.h"
#include "esp_ota_ops.h"
#include "app_info.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
static const char *TAG = "app_info";
void get_app_info()
{
const esp_app_desc_t *app_description = esp_ota_get_app_description();
const int sha256_hex_len = 64;
const int kSha256ElfHashSize = sha256_hex_len + 1;
char ref_sha256[kSha256ElfHashSize];
for (int i = 0; i < sizeof(ref_sha256) / 2; ++i)
{
snprintf(ref_sha256 + 2 * i, 3, "%02x", app_description->app_elf_sha256[i]); // NOLINT
}
ref_sha256[sha256_hex_len] = 0;
ESP_LOGI(TAG, "Application version: %s. IDF version: %s. Compile time and date: %s %s. SHA256 of the ELF: %s\n", app_description->version, app_description->idf_ver, app_description->time, app_description->date, ref_sha256);
}
void get_tasks_info()
{
const size_t bytes_per_task = 40; /* see vTaskList description */
const size_t task_list_buffer_size = uxTaskGetNumberOfTasks() * bytes_per_task;
char *task_list_buffer = malloc(task_list_buffer_size);
vTaskList(task_list_buffer);
ESP_LOGI(TAG, "\nTask Name\tStatus\tPrio\tHWM\tTask#\tAffinity\n%s", task_list_buffer);
free(task_list_buffer);
}
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/components/i2c_manager/hd_44780.h
|
<reponame>ferrarimarco/home-lab<gh_stars>1-10
#ifndef PROVISIONING_ESP32_SMART_DESK_COMPONENTS_I2C_MANAGER_HD_44780_H_
#define PROVISIONING_ESP32_SMART_DESK_COMPONENTS_I2C_MANAGER_HD_44780_H_
#include "esp_err.h"
// LCD display positions
#define LCD_LINEONE 0x00 // Start of line 1
#define LCD_LINETWO 0x40 // Start of line 2
#define LCD_LINETHREE 0x14 // Start of line 3
#define LCD_LINEFOUR 0x54 // Start of line 4
// Register select (instruction or data, RS bit)
#define LCD_INSTRUCTION_REGISTER 0
#define LCD_DATA_REGISTER 1
#define LCD_SEND_4_BITS 0
#define LCD_SEND_8_BITS 1
// Command mode (read or write, R/W bit)
#define LCD_WRITE_MODE 0x00 // Write data to the LCD display (I2C master -> I2C slave)
#define LCD_READ_MODE 0x02 // Read data from the LCD display (I2C slave -> I2C master) - binary: 10
// LCD Backlight bits
#define LCD_BACKLIGHT_ON_MASK 0xFF // Backlight mask used when backlight is ON
#define LCD_BACKLIGHT_OFF_MASK 0x00 // Backlight mask used when backlight is OFF
#define BACKLIGHT_OFF 0 // Used in combination with the setBacklight to switch the LCD backlight OFF
#define BACKLIGHT_ON 255 // Used in combination with the setBacklight to switch the LCD backlight ON
// LCD commands
#define LCD_CLEAR_DISPLAY 0x01 // Replace all characters with ASCII SP (space, code 32, 0x20) - binary: 1
#define LCD_RETURN_HOME 0x02 // Return cursor to first position on first line - binary: 10
#define LCD_ENTRY_MODE_SET 0x04 // Set the direction of the cursor movement and display shift - binary: 100
#define LCD_DISPLAY_ON_OFF 0x08 // Turn on or off the display, show or hide the cursor, turn on or off cursor blinking - binary: 1000
#define LCD_CURSOR_OR_DISPLAY_SHIFT 0x10 // Shift cursor or display position (useful to search or to correct data)
#define LCD_FUNCTION_SET 0x20 // Set 8-bit or 4-bit command mode, set 1-line or 2-line display mode, set 5x8 or 5x11 font mode - binary: 100000
#define LCD_SET_CGRAM_ADDRESS 0x40 // Set CGRAM address
#define LCD_SET_DDRAM_ADDRESS 0x80 // Set DDRAM address (cursor position) - binary: 10000000
// LCD reset command
#define LCD_FUNCTION_RESET 0x03 // Reset the LCD controller when in 4-bits mode
#define LCD_FUNCTION_SET_4_BITS_RESET 0x02 // Set 4-bits mode during initialization when in 4-bits mode
// LCD entry mode command parameters
#define LCD_ENTRY_MODE_SET_INCREMENT_DDRAM_ADDRESS 0x02 // Cursor moves to right and DDRAM address is increased by 1
#define LCD_ENTRY_MODE_SET_DECREMENT_DDRAM_ADDRESS 0x00 // Cursor moves to left and DDRAM address is decreased by 1
#define LCD_ENTRY_MODE_SET_SHIFT_DISPLAY 0x01 // When reading from DDRAM, or reading from or writing to CGRAM, shift the entire display according to increment or decrement
#define LCD_ENTRY_MODE_SET_NO_SHIFT_DISPLAY 0x00 // When reading from DDRAM, or reading from or writing to CGRAM, don't shift the entire display according to increment or decrement
// LCD display on/off command parameters
#define LCD_DISPLAY_ON_OFF_DISPLAY_ON 0x04 // Turn the entire display on - binary: 100
#define LCD_DISPLAY_ON_OFF_DISPLAY_OFF 0x00 // Turn the entire display off, but data remains in DDRAM
#define LCD_DISPLAY_ON_OFF_CURSOR_ON 0x02 // Show the cursor - binary: 10
#define LCD_DISPLAY_ON_OFF_CURSOR_OFF 0x00 // Hide the cursor, but the cursor position register preserves data
#define LCD_DISPLAY_ON_OFF_BLINK_ON 0x01 // Enable cursor blinking
#define LCD_DISPLAY_ON_OFF_BLINK_OFF 0x00 // Disable cursor blinking
// LCD shift command parameters
#define LCD_CURSOR_OR_DISPLAY_SHIFT_CURSOR_LEFT_DECREASE_AC 0x00 // Shift cursor to the left, AC is decreased by 1
#define LCD_CURSOR_OR_DISPLAY_SHIFT_CURSOR_RIGHT_INCREASE_AC 0x01 // Shift cursor to the right, AC is increased by 1
#define LCD_CURSOR_OR_DISPLAY_SHIFT_SHIFT_DISPLAY_LEFT 0x02 // Shift all the display to the left, Cursor moves according to the display
#define LCD_CURSOR_OR_DISPLAY_SHIFT_SHIFT_DISPLAY_RIGHT 0x03 // Shift all the display to the right, cursor moves according to the display
// LCD function parameters
#define LCD_FUNCTION_SET_8_BIT 0x10 // Enable 8-bit bus mode
#define LCD_FUNCTION_SET_4_BIT 0x00 // Enable 4-bit bus mode
#define LCD_FUNCTION_SET_1_LINE 0x00 // Enable 1-line display mode
#define LCD_FUNCTION_SET_2_LINES 0x08 // Enable 2-lines display mode - binary: 1000
#define LCD_FUNCTION_SET_5X8 0x00 // Enable 5x8 font mode
#define LCD_FUNCTION_SET_5X11 0x04 // Enable 5x11 font mode
esp_err_t LCD_init(uint8_t addr, uint8_t cols, uint8_t rows, uint8_t En, uint8_t Rw, uint8_t Rs, uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7, uint8_t backlighPin, uint8_t interface_bit_mode);
void LCD_setCursor(uint8_t col, uint8_t row);
void LCD_home(void);
void LCD_clearScreen(void);
void LCD_switchBacklightOff(void);
void LCD_switchBacklightOn(void);
void LCD_turnDisplayOff(void);
void LCD_turnDisplayOn(void);
void LCD_writeChar(char c);
void LCD_writeStr(const char *str);
void LCD_Demo();
esp_err_t register_lcd_events();
#endif // PROVISIONING_ESP32_SMART_DESK_COMPONENTS_I2C_MANAGER_HD_44780_H_
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/components/debug_utils/board_info.c
|
<reponame>ferrarimarco/home-lab<gh_stars>1-10
#include <stdio.h>
#include <string.h>
#include "esp_log.h"
#include "sdkconfig.h"
#include "board_info.h"
static const char *TAG = "board_info";
void get_board_info(esp_chip_info_t chip_info, int flash_chip_size, int free_heap_size)
{
ESP_LOGI(TAG, "This is a %s CPU (%s IDF target) with %d CPU cores, WiFi%s%s, silicon revision %d, %dB %s flash, Free heap: %d\n",
(chip_info.model == CHIP_ESP32) ? "ESP32" : "N/A",
CONFIG_IDF_TARGET,
chip_info.cores,
(chip_info.features & CHIP_FEATURE_BT) ? "/BT" : "",
(chip_info.features & CHIP_FEATURE_BLE) ? "/BLE" : "",
chip_info.revision,
flash_chip_size,
(chip_info.features & CHIP_FEATURE_EMB_FLASH) ? "embedded" : "external",
free_heap_size);
}
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/components/provisioning_manager/provisioning_manager.h
|
#ifndef PROVISIONING_ESP32_SMART_DESK_COMPONENTS_PROVISIONING_MANAGER_PROVISIONING_MANAGER_H_
#define PROVISIONING_ESP32_SMART_DESK_COMPONENTS_PROVISIONING_MANAGER_PROVISIONING_MANAGER_H_
ESP_EVENT_DECLARE_BASE(PROVISIONING_MANAGER_EVENTS);
enum
{
PROVISIONING_MANAGER_INIT, // raised when the wifi provisioning manager needs to be initialized
};
void register_provisioning_manager_event_handlers();
void start_wifi_provisioning();
#endif // PROVISIONING_ESP32_SMART_DESK_COMPONENTS_PROVISIONING_MANAGER_PROVISIONING_MANAGER_H_
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/components/smart_desk_manager/actuators_controller.h
|
<gh_stars>1-10
#ifndef PROVISIONING_ESP32_SMART_DESK_COMPONENTS_SMART_DESK_MANAGER_ACTUATORS_CONTROLLER_H_
#define PROVISIONING_ESP32_SMART_DESK_COMPONENTS_SMART_DESK_MANAGER_ACTUATORS_CONTROLLER_H_
#include "esp_event.h"
#include "relay_board.h"
struct Actuator
{
struct Relay *relay_1;
struct Relay *relay_2;
size_t relays_num;
};
struct ActuatorsEventMessage
{
size_t actuators_num;
struct Actuator **actuators;
};
esp_err_t init_actuators(struct Relay *relays, size_t relays_num, struct Actuator ***actuators_p, size_t actuators_num);
esp_err_t register_actuators_events(struct Actuator **actuators, size_t actuators_num);
esp_err_t start_actuators_extension(uint8_t target_height);
esp_err_t start_actuators_retraction(uint8_t target_height);
ESP_EVENT_DECLARE_BASE(ACTUATOR_EVENT);
enum
{ // declaration of the specific events under the actuator events family
EXTEND_ACTUATORS_EVENT, // raised when there's a request to extend the actuators
RETRACT_ACTUATORS_EVENT, // raised when there's a request to retract the actuators
SHUTDOWN_ACTUATORS_EVENT // raised when there's a request to stop the actuators
};
#endif // PROVISIONING_ESP32_SMART_DESK_COMPONENTS_SMART_DESK_MANAGER_ACTUATORS_CONTROLLER_H_
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/components/i2c_manager/i2c_utils.c
|
<reponame>ferrarimarco/home-lab
#include "i2c_utils.h"
#include <stdbool.h>
#include <stdio.h>
#include "driver/i2c.h"
#include "driver/periph_ctrl.h"
#include "esp_log.h"
#include "print_utils.h"
static const char *TAG = "i2c_utils";
i2c_port_t i2c_port = I2C_NUM_0;
esp_err_t i2c_reset()
{
esp_err_t ret;
char err_msg[20];
if ((ret = i2c_reset_tx_fifo(i2c_port)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while resetting the I2C TX buffers.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
if ((ret = i2c_reset_rx_fifo(i2c_port)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while resetting the I2C RX buffers.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
periph_module_disable(PERIPH_I2C0_MODULE);
periph_module_enable(PERIPH_I2C0_MODULE);
if ((ret = i2c_driver_delete(i2c_port)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while deleting the I2C driver.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
return ret;
}
esp_err_t i2c_master_driver_initialize(uint8_t sda_pin, uint8_t scl_pin, uint32_t master_clock_frequency)
{
ESP_LOGI(TAG, "Installing the I2C driver with SDA pin: %u, SCL pin: %u, I2C master clock frequency: %u Hz...", sda_pin, scl_pin, master_clock_frequency);
i2c_config_t conf = {
.mode = I2C_MODE_MASTER,
.sda_io_num = sda_pin,
.sda_pullup_en = GPIO_PULLUP_ENABLE,
.scl_io_num = scl_pin,
.scl_pullup_en = GPIO_PULLUP_ENABLE,
.master.clk_speed = master_clock_frequency};
esp_err_t ret;
char err_msg[20];
if ((ret = i2c_param_config(i2c_port, &conf)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while initializing I2C parameters.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
if (ret == ESP_OK && (ret = i2c_driver_install(i2c_port, I2C_MODE_MASTER, 0, 0, 0)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while installing the I2C driver.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
return ret;
}
esp_err_t i2c_master_write_byte_to_client_ack(uint8_t client_address, uint8_t data, bool detect_only_mode, bool enable_ack)
{
ESP_LOGD(TAG, "Writing to client 0x%02x. Sending byte: " BYTE_TO_BINARY_PATTERN, client_address, BYTE_TO_BINARY(data));
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
esp_err_t ret;
char err_msg[20];
if ((ret = i2c_master_start(cmd)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while generating the command start for 0x%02x.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)), client_address);
}
if (ret == ESP_OK && (ret = i2c_master_write_byte(cmd, (client_address << 1) | I2C_MASTER_WRITE, enable_ack)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while writing the address to send data to 0x%02x.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)), client_address);
}
if (ret == ESP_OK && !detect_only_mode && (ret = i2c_master_write_byte(cmd, data, enable_ack)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while writing a byte of data to send to 0x%02x.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)), client_address);
}
if (ret == ESP_OK && (ret = i2c_master_stop(cmd)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while generating the command stop for 0x%02x.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)), client_address);
}
if (ret == ESP_OK)
{
do
{
// ticks_to_wait is a timeout value.
// If the queue is full for that amount of ticks, the call aborts instead of waiting longer.
ret = i2c_master_cmd_begin(i2c_port, cmd, 1000 / portTICK_PERIOD_MS);
if (ret == ESP_OK)
ESP_LOGD(TAG, "I2C command sent to 0x%02x.", client_address);
else if (ret == ESP_ERR_TIMEOUT)
ESP_LOGE(TAG, "%s while sending queued commands to 0x%02x. Retrying...", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)), client_address);
else
ESP_LOGE(TAG, "%s while sending queued commands to 0x%02x.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)), client_address);
} while (ret == ESP_ERR_TIMEOUT);
}
i2c_cmd_link_delete(cmd);
return ret;
}
esp_err_t i2c_detect_device(uint8_t client_address)
{
ESP_LOGI(TAG, "Checking if there's an I2C client device at 0x%02x...", client_address);
esp_err_t ret;
char err_msg[20];
if ((ret = i2c_master_write_byte_to_client_ack(client_address, 0, true, ACK_ON)) == ESP_OK)
{
ESP_LOGI(TAG, "The I2C device at 0x%02x replied with an ACK.", client_address);
}
else
{
ESP_LOGE(TAG, "%s while detecting I2C devices at 0x%02x.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)), client_address);
}
return ret;
}
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/components/provisioning_manager/provisioning_manager.c
|
<filename>provisioning/esp32/smart_desk/components/provisioning_manager/provisioning_manager.c
#include "esp_event.h"
#include "esp_log.h"
#include "esp_wifi.h"
#include "wifi_provisioning/manager.h"
#include "wifi_provisioning/scheme_ble.h"
#include "provisioning_manager.h"
#include "wifi_connection_manager.h"
static const char *TAG = "provisioning_manager";
ESP_EVENT_DEFINE_BASE(PROVISIONING_MANAGER_EVENTS);
void handle_prov_manager_init_event(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
ESP_LOGI(TAG, "Initializing provisioning manager...");
initialize_wifi_station();
wifi_prov_mgr_config_t wifi_provisioning_manager_config = {
.scheme = wifi_prov_scheme_ble,
.scheme_event_handler = WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM,
};
ESP_ERROR_CHECK(wifi_prov_mgr_init(wifi_provisioning_manager_config));
}
void handle_wifi_prov_init_event(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
ESP_LOGI(TAG, "WiFi provisioning manager initialization completed.");
ESP_LOGD(TAG, "Checking if WiFi is already provisioned...");
bool provisioned = false;
ESP_ERROR_CHECK(wifi_prov_mgr_is_provisioned(&provisioned));
if (!provisioned)
{
ESP_LOGI(TAG, "Starting WiFi provisioning...");
char service_name[12];
uint8_t eth_mac[6];
const char *ssid_prefix = "PROV_";
ESP_ERROR_CHECK(esp_wifi_get_mac(WIFI_IF_STA, eth_mac));
snprintf(service_name, sizeof(service_name), "%s%02X%02X%02X", ssid_prefix, eth_mac[3], eth_mac[4], eth_mac[5]);
ESP_LOGI(TAG, "Setting service name to %s...", service_name);
wifi_prov_security_t security = WIFI_PROV_SECURITY_1;
const char *pop = "abcd1234";
uint8_t custom_service_uuid[] = {
/* LSB <---------------------------------------
* ---------------------------------------> MSB */
0xb4,
0xdf,
0x5a,
0x1c,
0x3f,
0x6b,
0xf4,
0xbf,
0xea,
0x4a,
0x82,
0x03,
0x04,
0x90,
0x1a,
0x02,
};
ESP_ERROR_CHECK(wifi_prov_scheme_ble_set_service_uuid(custom_service_uuid));
ESP_ERROR_CHECK(wifi_prov_mgr_start_provisioning(security, pop, service_name, NULL));
}
else
{
ESP_LOGI(TAG, "The WiFi is already provisioned. Completing the provisioning process...");
ESP_ERROR_CHECK(esp_event_post(WIFI_PROV_EVENT, WIFI_PROV_END, NULL, 0, portMAX_DELAY));
}
}
void handle_wifi_prov_start_event(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
ESP_LOGD(TAG, "Provisioning started");
}
void handle_wifi_prov_cred_recv_event(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
wifi_sta_config_t *wifi_sta_cfg = (wifi_sta_config_t *)event_data;
ESP_LOGD(TAG, "Received Wi-Fi credentials. SSID: %s. Password : %s", (const char *)wifi_sta_cfg->ssid, (const char *)wifi_sta_cfg->password);
}
void handle_wifi_prov_cred_fail_event(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
wifi_prov_sta_fail_reason_t *reason = (wifi_prov_sta_fail_reason_t *)event_data;
ESP_LOGE(TAG, "Provisioning failed! Reason : %s. Please reset to factory and retry provisioning", (*reason == WIFI_PROV_STA_AUTH_ERROR) ? "Wi-Fi station authentication failed" : "Wi-Fi access-point not found");
}
void handle_wifi_prov_cred_success_event(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
ESP_LOGD(TAG, "Provisioning successful");
}
void handle_wifi_prov_end_event(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
ESP_LOGD(TAG, "WiFi provisioning completed. De-initializing the WiFi provisioning manager...");
wifi_prov_mgr_deinit();
}
void handle_wifi_prov_deinit_event(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
ESP_LOGD(TAG, "WiFi provisioning manager de-initialization completed. Initializing WiFi station mode...");
ESP_ERROR_CHECK(esp_event_post(WIFI_CONNECTION_MANAGER_EVENTS, WIFI_CONNECTION_MANAGER_EVENT_STA_MODE_INIT, NULL, 0, portMAX_DELAY));
}
void register_provisioning_manager_event_handlers()
{
ESP_LOGI(TAG, "Registering provisioning manager events...");
ESP_LOGD(TAG, "Registering the handler for PROVISIONING_MANAGER_INIT event...");
ESP_ERROR_CHECK(esp_event_handler_instance_register(PROVISIONING_MANAGER_EVENTS, PROVISIONING_MANAGER_INIT, handle_prov_manager_init_event, NULL, NULL));
ESP_LOGD(TAG, "Registering the handler for WIFI_PROV_INIT event...");
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_PROV_EVENT, WIFI_PROV_INIT, handle_wifi_prov_init_event, NULL, NULL));
ESP_LOGD(TAG, "Registering the handler for WIFI_PROV_START event...");
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_PROV_EVENT, WIFI_PROV_START, handle_wifi_prov_start_event, NULL, NULL));
ESP_LOGD(TAG, "Registering the handler for WIFI_PROV_CRED_RECV event...");
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_PROV_EVENT, WIFI_PROV_CRED_RECV, handle_wifi_prov_cred_recv_event, NULL, NULL));
ESP_LOGD(TAG, "Registering the handler for WIFI_PROV_CRED_FAIL event...");
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_PROV_EVENT, WIFI_PROV_CRED_FAIL, handle_wifi_prov_cred_fail_event, NULL, NULL));
ESP_LOGD(TAG, "Registering the handler for WIFI_PROV_CRED_SUCCESS event...");
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_PROV_EVENT, WIFI_PROV_CRED_SUCCESS, handle_wifi_prov_cred_success_event, NULL, NULL));
ESP_LOGD(TAG, "Registering the handler for WIFI_PROV_END event...");
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_PROV_EVENT, WIFI_PROV_END, handle_wifi_prov_end_event, NULL, NULL));
ESP_LOGD(TAG, "Registering the handler for WIFI_PROV_DEINIT event...");
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_PROV_EVENT, WIFI_PROV_DEINIT, handle_wifi_prov_deinit_event, NULL, NULL));
}
void start_wifi_provisioning()
{
ESP_LOGI(TAG, "Starting WiFi provisioning...");
ESP_ERROR_CHECK(esp_event_post(PROVISIONING_MANAGER_EVENTS, PROVISIONING_MANAGER_INIT, NULL, 0, portMAX_DELAY));
}
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/components/i2c_manager/hd_44780.c
|
#include "hd_44780.h"
#include <stdio.h>
#include "driver/i2c.h"
#include "esp32/rom/ets_sys.h"
#include "esp_event.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "sdkconfig.h"
#include "i2c_utils.h"
#include "print_utils.h"
#include "ultrasonic.h"
static const char *TAG = "hd_44780";
static uint8_t LCD_addr;
static uint8_t LCD_cols;
static uint8_t LCD_rows;
static uint8_t _backlightPinMask; // Backlight IO pin mask
static uint8_t _backlightStatusMask; // Backlight status mask
static uint8_t _En; // LCD expander word for enable pin
static uint8_t _Rw; // LCD expander word for R/W pin
static uint8_t _Rs; // LCD expander word for Register Select pin
// LCD data lines
static uint8_t _d4;
static uint8_t _d5;
static uint8_t _d6;
static uint8_t _d7;
static uint8_t _displayfunction;
static esp_err_t
LCD_write_4_bits(uint8_t nibble, uint8_t reg, bool enable_ack)
{
ESP_LOGD(TAG, "Preparing 4 bits to send to the LCD: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(nibble));
uint8_t data = 0;
// convert the value to an i/o expander port value
// based on pin mappings
if (nibble & (1 << 0))
data |= _d4;
if (nibble & (1 << 1))
data |= _d5;
if (nibble & (1 << 2))
data |= _d6;
if (nibble & (1 << 3))
data |= _d7;
ESP_LOGD(TAG, "Mapped the data to send to LCD data pins: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(data));
// Is it a command (instruction register) or data (data register)
// -----------------------
if (reg == LCD_DATA_REGISTER)
{
reg = _Rs;
}
data |= reg | _backlightStatusMask;
ESP_LOGD(TAG, "Mapped the data to send to backlight, and RS pins: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(data));
// Clock data into LCD
uint8_t data_enable = data | _En;
ESP_LOGD(TAG, "Mapped the data to send to Enable pin: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(data_enable));
uint8_t data_not_enable = data & ~_En;
ESP_LOGD(TAG, "Mapped the data to send to NOT Enable pin: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(data_not_enable));
esp_err_t ret;
char err_msg[20];
if ((ret = i2c_master_write_byte_to_client_ack(LCD_addr, data_enable, false, enable_ack)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while sending bits (data bit on).", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
if (ret == ESP_OK && (ret = i2c_master_write_byte_to_client_ack(LCD_addr, data_not_enable, false, enable_ack)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while sending bits (data bit off).", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
ets_delay_us(500);
return ret;
}
static esp_err_t send(uint8_t value, uint8_t mode, uint8_t reg, bool enable_ack)
{
// ensure that previous LCD instruction finished.
// There is a 45us offset since there will be at least 2 bytes
// (the i2c address and the i/o expander data) transmitted over i2c
// before the i/o expander i/o pins could be seen by the LCD.
// At 400Khz (max rate supported by the i/o expanders) 16 bits plus start
// and stop bits is 45us.
// So there is at least 45us of time overhead in the physical interface.
ets_delay_us(45);
// Wait a bit more because we're using internal pull-up resistors which
// are slower than what the i2c spec allows
vTaskDelay(10 / portTICK_RATE_MS);
esp_err_t ret;
char err_msg[20];
ESP_LOGD(TAG, "Sending the 4 most significant bits of: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(value));
if ((ret = LCD_write_4_bits((value >> 4), reg, enable_ack)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while sending the 4 most significant bits.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
if (ret == ESP_OK && mode == LCD_SEND_8_BITS)
{
ESP_LOGD(TAG, "Sending the 4 least significant bits of: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(value));
if ((ret = LCD_write_4_bits((value & 0x0F), reg, enable_ack)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while sending the 4 least significant bits.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
}
return ret;
}
static void setBacklight(uint8_t value)
{
// Check if backlight is available
// ----------------------------------------------------
if (_backlightPinMask != 0x0)
{
if (value > 0)
{
_backlightStatusMask = _backlightPinMask & LCD_BACKLIGHT_ON_MASK;
}
else
{
_backlightStatusMask = _backlightPinMask & LCD_BACKLIGHT_OFF_MASK;
}
i2c_master_write_byte_to_client_ack(LCD_addr, _backlightStatusMask, false, ACK_ON);
ets_delay_us(80);
}
}
esp_err_t LCD_init(uint8_t addr, uint8_t cols, uint8_t rows, uint8_t En, uint8_t Rw, uint8_t Rs, uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7, uint8_t backligh_pin, uint8_t interface_bit_mode)
{
ESP_LOGI(TAG, "Initializing the LCD screen (I2C address: 0x%02x, rows: %d, columns: %d)...", addr, rows, cols);
LCD_addr = addr;
LCD_cols = cols;
LCD_rows = rows;
_backlightPinMask = 0;
_backlightStatusMask = LCD_BACKLIGHT_OFF_MASK;
ESP_LOGI(TAG, "Initializing pin mappings...");
_En = (1 << En);
_Rw = (1 << Rw);
_Rs = (1 << Rs);
_d4 = (1 << d4);
_d5 = (1 << d5);
_d6 = (1 << d6);
_d7 = (1 << d7);
_backlightPinMask = (1 << backligh_pin);
ESP_LOGD(TAG, "RS pin mask: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(_Rs));
ESP_LOGD(TAG, "R/W pin mask: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(_Rw));
ESP_LOGD(TAG, "E pin mask: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(_En));
ESP_LOGD(TAG, "Backlight pin mask: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(_backlightPinMask));
ESP_LOGD(TAG, "D4 pin mask: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(_d4));
ESP_LOGD(TAG, "D5 pin mask: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(_d5));
ESP_LOGD(TAG, "D6 pin mask: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(_d6));
ESP_LOGD(TAG, "D7 pin mask: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(_d7));
// SEE PAGE 45/46 of the Hitachi HD44780 datasheet FOR INITIALIZATION SPECIFICATION!
// according to datasheet, we need at least 40ms after power rises above 2.7V
// before sending commands.
ESP_LOGD(TAG, "Waiting for the Vcc to raise to 4.5V (this needs at least 40 ms)...");
vTaskDelay(100 / portTICK_RATE_MS);
esp_err_t ret;
char err_msg[20];
// There's no way to know if the HD44780 is in 4-bit mode or 8-bit mode.
// This initialization sequence reliably sets it in 8-bit mode
ESP_LOGD(TAG, "Beginning the initialization sequence to set the interface to 8-bits mode...");
ESP_LOGD(TAG, "Sending the first command of the initialization sequence....");
if ((ret = send(LCD_FUNCTION_SET | LCD_FUNCTION_SET_8_BIT, LCD_SEND_4_BITS, LCD_INSTRUCTION_REGISTER, ACK_ON)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while sending the first LCD initialization command.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
// Return immediately because the LCD didn't ACK the data transfer
return ret;
}
vTaskDelay(5 / portTICK_RATE_MS);
ESP_LOGD(TAG, "Sending the second command of the initialization sequence....");
if ((ret = send(LCD_FUNCTION_SET | LCD_FUNCTION_SET_8_BIT, LCD_SEND_4_BITS, LCD_INSTRUCTION_REGISTER, ACK_ON)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while sending the second LCD initialization command.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
// Return immediately because the LCD didn't ACK the data transfer
return ret;
}
vTaskDelay(1 / portTICK_RATE_MS);
ESP_LOGD(TAG, "Sending the third command of the initialization sequence....");
if ((ret = send(LCD_FUNCTION_SET | LCD_FUNCTION_SET_8_BIT, LCD_SEND_4_BITS, LCD_INSTRUCTION_REGISTER, ACK_ON)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while sending the third LCD initialization command.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
// Return immediately because the LCD didn't ACK the data transfer
return ret;
}
vTaskDelay(1 / portTICK_RATE_MS);
ESP_LOGI(TAG, "Initialization sequence completed.");
ESP_LOGD(TAG, "Initializing the display function...");
_displayfunction = LCD_FUNCTION_SET;
if (!(interface_bit_mode & LCD_FUNCTION_SET_8_BIT))
{
ESP_LOGD(TAG, "Setting interface to 4-bits mode...");
ret = send(LCD_FUNCTION_SET | LCD_FUNCTION_SET_4_BIT, LCD_SEND_4_BITS, LCD_INSTRUCTION_REGISTER, ACK_ON);
_displayfunction |= LCD_FUNCTION_SET_4_BIT;
}
else
{
ESP_LOGD(TAG, "Leaving the interface in 8-bits mode...");
_displayfunction |= LCD_FUNCTION_SET_8_BIT;
}
if (rows > 1)
{
ESP_LOGD(TAG, "Enabling 2-lines mode...");
_displayfunction |= LCD_FUNCTION_SET_2_LINES;
}
ESP_LOGD(TAG, "Enabling 5x8 font...");
_displayfunction |= LCD_FUNCTION_SET_5X8;
ESP_LOGD(TAG, "Display function value: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(_displayfunction));
ESP_LOGD(TAG, "Sending the Function Set command...");
ret = send(_displayfunction, LCD_SEND_8_BITS, LCD_INSTRUCTION_REGISTER, ACK_ON);
ets_delay_us(80);
LCD_turnDisplayOff();
LCD_clearScreen();
ESP_LOGD(TAG, "Setting LCD entry mode...");
ret = send(LCD_ENTRY_MODE_SET | LCD_ENTRY_MODE_SET_INCREMENT_DDRAM_ADDRESS, LCD_SEND_8_BITS, LCD_INSTRUCTION_REGISTER, ACK_ON);
ets_delay_us(80);
LCD_home();
LCD_turnDisplayOn();
LCD_switchBacklightOn();
return ret;
}
void LCD_setCursor(uint8_t col, uint8_t row)
{
ESP_LOGD(TAG, "Set cursor to col %d, row %d", col, row);
if (row > LCD_rows - 1)
{
ESP_LOGE(TAG, "Cannot write to row %d. Please select a row in the range (0, %d)", row, LCD_rows - 1);
row = LCD_rows - 1;
}
uint8_t row_offsets[] = {LCD_LINEONE, LCD_LINETWO, LCD_LINETHREE, LCD_LINEFOUR};
send(LCD_SET_DDRAM_ADDRESS | (col + row_offsets[row]), LCD_SEND_8_BITS, LCD_INSTRUCTION_REGISTER, ACK_ON);
ets_delay_us(80);
}
void LCD_writeChar(char c)
{
ESP_LOGD(TAG, "Write char: %c", c);
send(c, LCD_SEND_8_BITS, LCD_DATA_REGISTER, ACK_ON);
ets_delay_us(80);
}
void LCD_writeStr(const char *str)
{
ESP_LOGD(TAG, "Write string: %s", str);
while (*str)
{
LCD_writeChar(*str++);
}
}
void LCD_switchBacklightOff(void)
{
ESP_LOGI(TAG, "Turning backlight off...");
setBacklight(BACKLIGHT_OFF);
ets_delay_us(80);
}
void LCD_switchBacklightOn(void)
{
ESP_LOGI(TAG, "Turning backlight on...");
setBacklight(BACKLIGHT_ON);
ets_delay_us(80);
}
void LCD_home(void)
{
ESP_LOGI(TAG, "Returning the cursor home...");
send(LCD_RETURN_HOME, LCD_SEND_8_BITS, LCD_INSTRUCTION_REGISTER, ACK_ON);
vTaskDelay(2 / portTICK_RATE_MS); // This command takes a while to complete
}
void LCD_clearScreen(void)
{
ESP_LOGI(TAG, "Clearing the LCD...");
send(LCD_CLEAR_DISPLAY, LCD_SEND_8_BITS, LCD_INSTRUCTION_REGISTER, ACK_ON);
vTaskDelay(3 / portTICK_RATE_MS);
}
void LCD_turnDisplayOff(void)
{
ESP_LOGI(TAG, "Turning the Display OFF...");
send(LCD_DISPLAY_ON_OFF | LCD_DISPLAY_ON_OFF_DISPLAY_OFF, LCD_SEND_8_BITS, LCD_INSTRUCTION_REGISTER, ACK_ON);
ets_delay_us(80);
}
void LCD_turnDisplayOn(void)
{
ESP_LOGI(TAG, "Turning the Display ON...");
send(LCD_DISPLAY_ON_OFF | LCD_DISPLAY_ON_OFF_DISPLAY_ON | LCD_DISPLAY_ON_OFF_CURSOR_OFF | LCD_DISPLAY_ON_OFF_BLINK_OFF, LCD_SEND_8_BITS, LCD_INSTRUCTION_REGISTER, ACK_ON);
ets_delay_us(80);
}
static void sta_got_ip_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
ESP_LOGI(TAG, "%s: %u sta_got_ip_event_handler", event_base, event_id);
ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
esp_ip4_addr_t ip_address = event->ip_info.ip;
char txtBuf[16];
sprintf(txtBuf, IPSTR, IP2STR(&ip_address)); // NOLINT
ESP_LOGI(TAG, "Got IP address: %s", txtBuf);
LCD_setCursor(4, 0);
LCD_writeStr(txtBuf);
}
static void ultrasonic_sensor_measure_available_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
ESP_LOGD(TAG, "%s: %u ultrasonic_sensor_measure_available_handler", event_base, event_id);
struct DistanceMeasure distance_measure = *((struct DistanceMeasure *)event_data);
char txtBuf[11];
if (distance_measure.return_code == ESP_OK)
sprintf(txtBuf, "%03u", distance_measure.distance); // NOLINT
else
sprintf(txtBuf, "N/A"); // NOLINT
LCD_setCursor(10, 1);
LCD_writeStr(txtBuf);
}
esp_err_t register_lcd_events()
{
esp_err_t ret = ESP_OK;
char err_msg[20];
ESP_LOGI(TAG, "Registering the handler for IP_EVENT_STA_GOT_IP event...");
if ((ret = esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, sta_got_ip_event_handler, NULL, NULL)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while registering the handler for the IP_EVENT_STA_GOT_IP event.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
ESP_LOGI(TAG, "Registering the handler for ULTRASONIC_EVENT_MEASURE_AVAILABLE event...");
if ((ret = esp_event_handler_instance_register(ULTRASONIC_EVENTS, ULTRASONIC_EVENT_MEASURE_AVAILABLE, ultrasonic_sensor_measure_available_handler, NULL, NULL)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while registering the handler for the ULTRASONIC_EVENT_MEASURE_AVAILABLE event.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
return ret;
}
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/components/network_manager/wifi_connection_manager.h
|
<reponame>ferrarimarco/home-lab
#ifndef PROVISIONING_ESP32_SMART_DESK_COMPONENTS_NETWORK_MANAGER_WIFI_CONNECTION_MANAGER_H_
#define PROVISIONING_ESP32_SMART_DESK_COMPONENTS_NETWORK_MANAGER_WIFI_CONNECTION_MANAGER_H_
ESP_EVENT_DECLARE_BASE(WIFI_CONNECTION_MANAGER_EVENTS);
enum
{
WIFI_CONNECTION_MANAGER_EVENT_STA_INIT, // raised when the wifi station manager needs to be initialized
WIFI_CONNECTION_MANAGER_EVENT_STA_MODE_INIT // raised when the wifi station manager needs to be enabled
};
void initialize_wifi_station();
void register_wifi_manager_event_handlers();
#endif // PROVISIONING_ESP32_SMART_DESK_COMPONENTS_NETWORK_MANAGER_WIFI_CONNECTION_MANAGER_H_
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/components/i2c_manager/i2c_utils.h
|
<reponame>ferrarimarco/home-lab
#ifndef PROVISIONING_ESP32_SMART_DESK_COMPONENTS_I2C_MANAGER_I2C_UTILS_H_
#define PROVISIONING_ESP32_SMART_DESK_COMPONENTS_I2C_MANAGER_I2C_UTILS_H_
#include <stdbool.h>
#include "esp_err.h"
#define ACK_OFF 0
#define ACK_ON 1
esp_err_t i2c_detect_device(uint8_t client_address);
esp_err_t i2c_master_driver_initialize(uint8_t sda_pin, uint8_t scl_pin, uint32_t master_clock_frequency);
esp_err_t i2c_master_write_byte_to_client_ack(uint8_t client_address, uint8_t data, bool detect_only_mode, bool enable_ack);
esp_err_t i2c_reset();
esp_err_t do_i2cdetect();
#endif // PROVISIONING_ESP32_SMART_DESK_COMPONENTS_I2C_MANAGER_I2C_UTILS_H_
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/components/storage_manager/nvs_manager.c
|
<filename>provisioning/esp32/smart_desk/components/storage_manager/nvs_manager.c
#include "esp_log.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "nvs_manager.h"
static const char *TAG = "smart_desk";
static esp_err_t open_nvs_handle(const char *namespace, nvs_handle_t *nvs_handle)
{
esp_err_t err;
ESP_LOGI(TAG, "Opening %s NVS namespace...", namespace);
err = nvs_open(namespace, NVS_READWRITE, nvs_handle);
return err;
}
bool blob_exists(const char *namespace, const char *key)
{
ESP_LOGI(TAG, "Checking if a blob with %s key exists in %s namespace...", key, namespace);
nvs_handle_t nvs_handle;
esp_err_t err;
bool result = false;
ESP_ERROR_CHECK(open_nvs_handle(namespace, &nvs_handle));
ESP_LOGI(TAG, "Checking if the %s namespace contains %s key...", namespace, key);
size_t required_size = 0;
err = nvs_get_blob(nvs_handle, key, NULL, &required_size);
if (err == ESP_ERR_NVS_NOT_FOUND)
{
result = false;
ESP_LOGI(TAG, "%s key not found in %s namespace.", key, namespace);
}
else if (err == ESP_OK)
{
result = true;
ESP_LOGI(TAG, "Found %s key in %s namespace. Value size: %u.", key, namespace, required_size);
}
else
ESP_ERROR_CHECK(err);
ESP_LOGI(TAG, "Closing the NVS storage handle...");
nvs_close(nvs_handle);
return result;
}
esp_err_t initialize_nvs_flash()
{
ESP_LOGI(TAG, "Initializing the NVS flash...");
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
{
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
return ret;
}
esp_err_t get_blob_length(const char *namespace, const char *key, size_t *length)
{
ESP_LOGI(TAG, "Loading blob size from namespace: %s, key: %s...", namespace, key);
nvs_handle_t nvs_handle;
esp_err_t err;
ESP_ERROR_CHECK(open_nvs_handle(namespace, &nvs_handle));
err = nvs_get_blob(nvs_handle, key, NULL, length);
if (err != ESP_OK && err != ESP_ERR_NVS_NOT_FOUND)
return err;
nvs_close(nvs_handle);
return ESP_OK;
}
esp_err_t load_blob(const char *namespace, const char *key, void *blob_output, size_t blob_length)
{
ESP_LOGI(TAG, "Loading blob from namespace: %s, key: %s...", namespace, key);
nvs_handle_t nvs_handle;
esp_err_t err;
ESP_ERROR_CHECK(open_nvs_handle(namespace, &nvs_handle));
err = nvs_get_blob(nvs_handle, key, blob_output, &blob_length);
if (err != ESP_OK)
{
free(blob_output);
return err;
}
nvs_close(nvs_handle);
return ESP_OK;
}
esp_err_t save_blob(const char *namespace, const char *key, const void *value, size_t value_size)
{
ESP_LOGI(TAG, "Writing blob in namespace: %s, key: %s...", namespace, key);
nvs_handle_t nvs_handle;
esp_err_t err;
ESP_ERROR_CHECK(open_nvs_handle(namespace, &nvs_handle));
ESP_LOGI(TAG, "Writing %s key in %s namespace...", key, namespace);
err = nvs_set_blob(nvs_handle, key, value, value_size);
if (err != ESP_OK)
return err;
ESP_LOGI(TAG, "Committing NVS changes...");
err = nvs_commit(nvs_handle);
if (err != ESP_OK)
return err;
ESP_LOGI(TAG, "Closing the NVS storage handle...");
nvs_close(nvs_handle);
return ESP_OK;
}
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/components/crypto_utils/rsa_utils.h
|
#ifndef PROVISIONING_ESP32_SMART_DESK_COMPONENTS_CRYPTO_UTILS_RSA_UTILS_H_
#define PROVISIONING_ESP32_SMART_DESK_COMPONENTS_CRYPTO_UTILS_RSA_UTILS_H_
struct RsaKeyGenerationOptions
{
int key_size; /* length of key in bits */
const char *private_key_filename; /* filename of the key file */
const char *public_key_filename; /* filename of the key file */
const char *storage_namespace; /* namespace of the NVS storage where keys have to be stored */
};
#define DEFAULT_RSA_KEY_SIZE 4096
#define DEFAULT_RSA_PRIVATE_KEY_FILENAME "private_key.pem"
#define DEFAULT_RSA_PUBLIC_KEY_FILENAME "public_key.pem"
#define DEFAULT_RSA_KEY_STORAGE_NAMESPACE "rsa_keys"
int generate_rsa_keypair(struct RsaKeyGenerationOptions rsa_key_generation_options);
#endif // PROVISIONING_ESP32_SMART_DESK_COMPONENTS_CRYPTO_UTILS_RSA_UTILS_H_
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/components/smart_desk_manager/actuators_controller.c
|
#include <string.h>
#include "esp_log.h"
#include "esp_timer.h"
#include "actuators_controller.h"
#include "ultrasonic.h"
// First attempt: 1 minute (to tune)
#define ACTUATORS_SAFETY_TIMEOUT_US 60000000
ESP_EVENT_DEFINE_BASE(ACTUATOR_EVENT);
static const char *TAG = "smart_desk_manager";
esp_timer_handle_t safety_timer;
static esp_err_t register_distance_sensor_events(uint8_t target_height);
static esp_err_t unregister_distance_sensor_events();
static esp_err_t actuators_event_post(int32_t event_id, void *event_data, size_t event_data_size)
{
ESP_LOGD(TAG, "Posting the %u actuator event...", event_id);
esp_err_t ret = ESP_OK;
char err_msg[20];
if ((ret = esp_event_post(ACTUATOR_EVENT, event_id, event_data, event_data_size, portMAX_DELAY)) != ESP_OK)
ESP_LOGE(TAG, "%s while sending the EXTEND_ACTUATORS_EVENT event.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
return ret;
}
esp_err_t start_actuators_extension(uint8_t target_height)
{
ESP_LOGI(TAG, "Extending the actuators to %u cm...", target_height);
esp_err_t ret = register_distance_sensor_events(target_height);
if (ret == ESP_OK)
ret = actuators_event_post(EXTEND_ACTUATORS_EVENT, &target_height, sizeof(target_height));
return ret;
}
esp_err_t start_actuators_retraction(uint8_t target_height)
{
ESP_LOGI(TAG, "Retracting the actuators to %u cm...", target_height);
register_distance_sensor_events(target_height);
return actuators_event_post(RETRACT_ACTUATORS_EVENT, &target_height, sizeof(target_height));
}
static esp_err_t start_actuators_shutdown()
{
ESP_LOGI(TAG, "Shutting down the actuators...");
unregister_distance_sensor_events();
return actuators_event_post(SHUTDOWN_ACTUATORS_EVENT, NULL, 0);
}
static void operate_actuators(void *event_handler_arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
ESP_LOGD(TAG, "Operating the actuators...");
esp_err_t ret = ESP_OK;
char err_msg[20];
// Init the timer if needed
if (event_id == SHUTDOWN_ACTUATORS_EVENT)
{
// Stop the safety timer because the actuators stopped moving
ret = esp_timer_stop(safety_timer);
if (ret != ESP_OK)
{
ESP_LOGE(TAG, "%s while stopping the safety timer.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
if (ret == ESP_ERR_INVALID_STATE)
{
ESP_LOGE(TAG, "The safety timer wasn't running, so cannot be stopped.");
}
}
}
else if (event_id == EXTEND_ACTUATORS_EVENT || event_id == RETRACT_ACTUATORS_EVENT)
{
if ((ret = esp_timer_start_once(safety_timer, ACTUATORS_SAFETY_TIMEOUT_US)) != ESP_OK)
ESP_LOGE(TAG, "%s while starting the safety timer event.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
if (ret == ESP_ERR_INVALID_STATE)
{
ESP_LOGE(TAG, "The safety timer is already running. This is likely due to the fact that the actuators may be in movement.");
}
}
// When requesting a shutdown, do that regardless of the error code because it might be
// an emergency shutdown
if (ret == ESP_OK || event_id == SHUTDOWN_ACTUATORS_EVENT)
{
struct ActuatorsEventMessage *actuators_event_message = (struct ActuatorsEventMessage *)event_handler_arg;
ESP_LOGD(TAG, "event_handler_arg pointer: %p, actuators_event_message pointer: %p...", event_handler_arg, actuators_event_message);
struct Actuator **actuators = actuators_event_message->actuators;
size_t actuators_size = actuators_event_message->actuators_num;
int i;
for (i = 0; i < actuators_size; i++)
{
struct Actuator *actuator = actuators[i];
ESP_LOGI(TAG, "Operating actuator %u (pointer: %p)...", i, actuator);
struct Relay *relay_1 = actuator->relay_1;
struct Relay *relay_2 = actuator->relay_2;
ESP_LOGI(TAG, "Operating actuator %u (pointer: %p) via relays (pointers: %p, %p)...", i, actuator, relay_1, relay_2);
if (event_id == EXTEND_ACTUATORS_EVENT)
{
ESP_LOGI(TAG, "Extending actuator %u (pointer: %p) via relays (pointers: %p, %p)...", i, actuator, relay_1, relay_2);
turn_relay_on(relay_1);
turn_relay_off(relay_2);
}
else if (event_id == RETRACT_ACTUATORS_EVENT)
{
ESP_LOGI(TAG, "Retracting actuator %u (pointer: %p) via relays (pointers: %p, %p)...", i, actuator, relay_1, relay_2);
turn_relay_off(relay_1);
turn_relay_on(relay_2);
}
else if (event_id == SHUTDOWN_ACTUATORS_EVENT)
{
ESP_LOGI(TAG, "Shutting down actuator %u (pointer: %p) via relays (pointers: %p, %p)...", i, actuator, relay_1, relay_2);
turn_relay_off(relay_1);
turn_relay_off(relay_2);
}
else
{
ret = ESP_ERR_INVALID_ARG;
// Safety measure
ESP_LOGE(TAG, "%d event type is not supported. Shutting the actuators down...", event_id);
start_actuators_shutdown();
}
}
}
}
// Callback that will be executed when the timer period lapses.
static void actuators_safety_timer_callback(void *arg)
{
ESP_LOGI(TAG, "Safety timer triggered. Stopping the actuators to prevent damage...");
start_actuators_shutdown();
}
static void ultrasonic_sensor_measure_available_handler(void *event_handler_arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
ESP_LOGD(TAG, "%s: %u ultrasonic_sensor_measure_available_handler", event_base, event_id);
struct DistanceMeasure distance_measure = *((struct DistanceMeasure *)event_data);
uint32_t measured_distance = distance_measure.distance;
uint8_t target_distance = *((uint8_t *)event_handler_arg);
if (distance_measure.return_code == ESP_OK && (measured_distance == target_distance))
{
ESP_LOGI(TAG, "Reached target distance: %u cm. Measured distance: %u cm. Stopping actuators...", target_distance, measured_distance);
start_actuators_shutdown();
}
}
static esp_err_t register_distance_sensor_events(uint8_t target_height)
{
esp_err_t ret = ESP_OK;
char err_msg[20];
uint8_t *target_distance_p = &target_height;
size_t target_distance_size = sizeof(uint8_t);
if ((target_distance_p = calloc(1, target_distance_size)) == NULL)
{
ret = ESP_ERR_NO_MEM;
ESP_LOGE(TAG, "%s while allocating memory for the target distance.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
return ret;
}
memcpy(target_distance_p, &target_height, target_distance_size);
ESP_LOGD(TAG, "Registering the handler for ULTRASONIC_EVENT_MEASURE_AVAILABLE event...");
if ((ret = esp_event_handler_instance_register(ULTRASONIC_EVENTS, ULTRASONIC_EVENT_MEASURE_AVAILABLE, ultrasonic_sensor_measure_available_handler, target_distance_p, NULL)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while registering the handler for the ULTRASONIC_EVENT_MEASURE_AVAILABLE event.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
return ret;
}
static esp_err_t unregister_distance_sensor_events()
{
esp_err_t ret = ESP_OK;
char err_msg[20];
ESP_LOGD(TAG, "Unregistering the handler for ULTRASONIC_EVENT_MEASURE_AVAILABLE event...");
if ((ret = esp_event_handler_unregister(ULTRASONIC_EVENTS, ULTRASONIC_EVENT_MEASURE_AVAILABLE, ultrasonic_sensor_measure_available_handler)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while unregistering the handler for the ULTRASONIC_EVENT_MEASURE_AVAILABLE event.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
return ret;
}
esp_err_t init_actuators(struct Relay *relays, size_t relays_num, struct Actuator ***actuators_p, size_t actuators_num)
{
esp_err_t ret = ESP_OK;
char err_msg[20];
ESP_LOGI(TAG, "Initializing %u actuators (%u relays, relays pointer: %p)...", actuators_num, relays_num, relays);
if ((*actuators_p = (struct Actuator **)calloc(actuators_num, sizeof(struct Actuator *))) == NULL)
{
ret = ESP_ERR_NO_MEM;
ESP_LOGE(TAG, "%s while allocating memory for the actuators.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
return ret;
}
ESP_LOGI(TAG, "Actuator pointers array initialized at %p...", *actuators_p);
if (ret == ESP_OK)
{
int i;
for (i = 0; i < actuators_num; i++)
{
size_t actuator_size = sizeof(struct Actuator);
struct Actuator *actuator;
if ((actuator = (struct Actuator *)calloc(1, actuator_size)) == NULL)
{
ret = ESP_ERR_NO_MEM;
ESP_LOGE(TAG, "%s while allocating memory for the actuator.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
return ret;
}
// Here we want:
// i = 0: r1 = 0, r2 = 1
// i = 1: r1 = 2, r2 = 3
// i = 2: r1 = 4, r2 = 5
// i = 3: r1 = 6, r2 = 7
// ...
// This initialization assumes that we control each actuator via two
// relays.
struct Actuator a = {
.relay_1 = &(relays[i * 2]),
.relay_2 = &(relays[i * 2 + 1]),
.relays_num = relays_num};
memcpy(actuator, &a, actuator_size);
(*actuators_p)[i] = actuator;
ESP_LOGI(TAG, "Iniitialized actuator %u (pointer to actuator: %p)", i, actuator);
}
}
else
{
ESP_LOGE(TAG, "%s while initializing the actuators.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
ESP_LOGI(TAG, "Completed actuators initialization (pointer to pointer to actuators pointers array: %p, pointer to actuators pointer array: %p)", actuators_p, *actuators_p);
return ret;
}
esp_err_t
register_actuators_events(struct Actuator **actuators, size_t actuators_num)
{
ESP_LOGI(TAG, "Registering events for %u actuators (actuators pointer: %p)...", actuators_num, actuators);
esp_err_t ret = ESP_OK;
char err_msg[20];
struct ActuatorsEventMessage *actuators_event_message_p = NULL;
size_t actuators_event_message_size = sizeof(struct ActuatorsEventMessage);
if ((actuators_event_message_p = calloc(1, actuators_event_message_size)) == NULL)
{
ret = ESP_ERR_NO_MEM;
ESP_LOGE(TAG, "%s while allocating memory for the actuators event message.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
return ret;
}
struct ActuatorsEventMessage actuators_event_message =
{
.actuators = actuators,
.actuators_num = actuators_num};
memcpy(actuators_event_message_p, &actuators_event_message, actuators_event_message_size);
ESP_LOGI(TAG, "Loaded the pointer to actuators in the actuators event message: %p...", actuators);
ESP_LOGI(TAG, "Registering the handler for EXTEND_ACTUATORS_EVENT event (event_handler_arg pointer: %p)...", actuators_event_message_p);
if ((ret = esp_event_handler_instance_register(ACTUATOR_EVENT, EXTEND_ACTUATORS_EVENT, operate_actuators, actuators_event_message_p, NULL)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while registering the handler for the EXTEND_ACTUATORS_EVENT event.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
ESP_LOGI(TAG, "Registering the handler for RETRACT_ACTUATORS_EVENT event (event_handler_arg pointer: %p)...", actuators_event_message_p);
if ((ret = esp_event_handler_instance_register(ACTUATOR_EVENT, RETRACT_ACTUATORS_EVENT, operate_actuators, actuators_event_message_p, NULL)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while registering the handler for the RETRACT_ACTUATORS_EVENT event.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
ESP_LOGI(TAG, "Registering the handler for SHUTDOWN_ACTUATORS_EVENT event (event_handler_arg pointer: %p)...", actuators_event_message_p);
if ((ret = esp_event_handler_instance_register(ACTUATOR_EVENT, SHUTDOWN_ACTUATORS_EVENT, operate_actuators, actuators_event_message_p, NULL)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while registering the handler for the SHUTDOWN_ACTUATORS_EVENT event.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
// Create and start the event sources for the safety timer
esp_timer_create_args_t timer_args = {
.callback = &actuators_safety_timer_callback};
ESP_LOGD(TAG, "Registering the handler for the safety timer...");
if ((ret = esp_timer_create(&timer_args, &safety_timer)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while registering the handler for the safety timer.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
return ret;
}
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/components/gpio_manager/ultrasonic.c
|
<filename>provisioning/esp32/smart_desk/components/gpio_manager/ultrasonic.c
#include "ultrasonic.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#define TRIGGER_LOW_DELAY 4
#define TRIGGER_HIGH_DELAY 10
#define PING_TIMEOUT 6000
#define ROUNDTRIP 58
static portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
#define timeout_expired(start, len) ((esp_timer_get_time() - (start)) >= (len))
#define CHECK_ARG(VAL) \
do \
{ \
if (!(VAL)) \
return ESP_ERR_INVALID_ARG; \
} while (0)
#define CHECK(x) \
do \
{ \
esp_err_t __; \
if ((__ = x) != ESP_OK) \
return __; \
} while (0)
static const char *TAG = "ultrasonic";
ESP_EVENT_DEFINE_BASE(ULTRASONIC_EVENTS);
esp_err_t ultrasonic_init(const ultrasonic_sensor_t *dev)
{
CHECK_ARG(dev);
CHECK(gpio_set_direction(dev->trigger_pin, GPIO_MODE_OUTPUT));
CHECK(gpio_set_direction(dev->echo_pin, GPIO_MODE_INPUT));
return gpio_set_level(dev->trigger_pin, 0);
}
esp_err_t ultrasonic_measure_cm(const ultrasonic_sensor_t *dev, uint32_t *distance)
{
CHECK_ARG(dev && distance);
portENTER_CRITICAL(&mux);
esp_err_t ret = ESP_OK;
char err_msg[20];
// Ping: Low for 2..4 us, then high 10 us
CHECK(gpio_set_level(dev->trigger_pin, 0));
ets_delay_us(TRIGGER_LOW_DELAY);
CHECK(gpio_set_level(dev->trigger_pin, 1));
ets_delay_us(TRIGGER_HIGH_DELAY);
CHECK(gpio_set_level(dev->trigger_pin, 0));
// Previous ping isn't ended
if (gpio_get_level(dev->echo_pin))
{
ret = ESP_ERR_ULTRASONIC_PING;
ESP_LOGE(TAG, "%s: cannot ping the distance sensor: device is in invalid state.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
// Wait for echo
int64_t start = esp_timer_get_time();
while (ret == ESP_OK && !gpio_get_level(dev->echo_pin))
{
if (timeout_expired(start, PING_TIMEOUT))
{
ret = ESP_ERR_ULTRASONIC_PING_TIMEOUT;
ESP_LOGE(TAG, "%s: distance sensor ping timeout: (likely) no device found.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
break;
}
}
int64_t echo_start = esp_timer_get_time();
int64_t time = echo_start;
int64_t meas_timeout = echo_start + dev->max_distance * ROUNDTRIP;
if (ret == ESP_OK)
{
// got echo, measuring
while (ret == ESP_OK && gpio_get_level(dev->echo_pin))
{
time = esp_timer_get_time();
if (timeout_expired(echo_start, meas_timeout))
{
ret = ESP_ERR_ULTRASONIC_ECHO_TIMEOUT;
ESP_LOGE(TAG, "%s: distance sensor echo timeout: (likely) distance is too big to measure.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
break;
}
}
}
portEXIT_CRITICAL(&mux);
if (ret == ESP_OK)
{
*distance = (time - echo_start) / ROUNDTRIP;
ESP_LOGD(TAG, "Measured distance: %d cm", *distance);
if (*distance < dev->min_distance || *distance > dev->max_distance)
{
ret = ESP_ERR_ULTRASONIC_DISTANCE_OUT_OF_RANGE;
ESP_LOGW(TAG, "%s: Measured distance (%d) is out of the validity range.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)), *distance);
}
struct DistanceMeasure distance_measure = {
*distance,
dev->min_distance,
dev->max_distance,
ret};
if ((ret = esp_event_post(ULTRASONIC_EVENTS, ULTRASONIC_EVENT_MEASURE_AVAILABLE, &distance_measure, sizeof(distance_measure), portMAX_DELAY)) != ESP_OK)
ESP_LOGE(TAG, "%s while sending the ULTRASONIC_EVENT_MEASURE_AVAILABLE event.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
return ret;
}
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/components/gpio_manager/relay_board.c
|
<reponame>ferrarimarco/home-lab<gh_stars>1-10
#include <string.h>
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "relay_board.h"
static const char *TAG = "relay_board";
esp_err_t init_relays(uint8_t relay_pins[], size_t relay_num, struct Relay **relays_p)
{
ESP_LOGI(TAG, "Initializing %u relays...", relay_num);
esp_err_t ret = ESP_OK;
char err_msg[20];
if ((*relays_p = (struct Relay *)calloc(relay_num, sizeof(struct Relay))) == NULL)
{
ret = ESP_ERR_NO_MEM;
ESP_LOGE(TAG, "%s while allocating memory for the relays.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
return ret;
}
gpio_num_t gpio_num = GPIO_NUM_NC;
int i;
for (i = 0; i < relay_num && ret == ESP_OK; i++)
{
size_t relay_size = sizeof(struct Relay);
struct Relay *relay;
if ((relay = (struct Relay *)calloc(1, relay_size)) == NULL)
ret = ESP_ERR_NO_MEM;
if (ret == ESP_OK)
{
struct Relay r = {relay_pins[i], GPIO_MODE_OUTPUT, GPIO_PULLUP_ONLY, 1, 0, 1};
memcpy(relay, &r, relay_size);
(*relays_p)[i] = *relay;
gpio_num = relay->gpio_num;
ESP_LOGI(TAG, "Initializing relay connected to GPIO PIN no. %u (pointer to relay: %p)", gpio_num, relay);
}
if (ret == ESP_OK && (ret = gpio_reset_pin(gpio_num)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while resetting GPIO pin.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
if (ret == ESP_OK && (ret = gpio_set_direction(gpio_num, relay->gpio_mode)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while setting GPIO direction.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
if (ret == ESP_OK && (ret = gpio_set_pull_mode(gpio_num, relay->pull_mode)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while setting GPIO pull mode.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
if (ret == ESP_OK && (ret = gpio_set_level(gpio_num, relay->initial_level)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while setting GPIO level.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
}
ESP_LOGI(TAG, "Completed relays initialization (pointer to pointer to relays array: %p, pointer to relays array: %p)", relays_p, *relays_p);
return ret;
}
esp_err_t turn_relay_on(struct Relay *relay)
{
ESP_LOGI(TAG, "Turning relay ON (pointer: %p)", relay);
gpio_num_t gpio_num = relay->gpio_num;
ESP_LOGI(TAG, "Turning the relay connected to GPIO PIN no. %u ON...", gpio_num);
esp_err_t ret = ESP_OK;
char err_msg[20];
if ((ret = gpio_set_level(gpio_num, relay->active_level)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while setting GPIO level.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
return ret;
}
esp_err_t turn_relay_off(struct Relay *relay)
{
ESP_LOGI(TAG, "Turning relay OFF (pointer: %p)", relay);
gpio_num_t gpio_num = relay->gpio_num;
ESP_LOGI(TAG, "Turning the relay connected to GPIO PIN no. %u OFF...", gpio_num);
esp_err_t ret = ESP_OK;
char err_msg[20];
if ((ret = gpio_set_level(gpio_num, relay->inactive_level)) != ESP_OK)
{
ESP_LOGE(TAG, "%s while setting GPIO level.", esp_err_to_name_r(ret, err_msg, sizeof(err_msg)));
}
return ret;
}
|
ferrarimarco/home-lab
|
provisioning/esp32/smart_desk/components/network_manager/ip_address_manager.h
|
<filename>provisioning/esp32/smart_desk/components/network_manager/ip_address_manager.h
#ifndef PROVISIONING_ESP32_SMART_DESK_COMPONENTS_NETWORK_MANAGER_IP_ADDRESS_MANAGER_H_
#define PROVISIONING_ESP32_SMART_DESK_COMPONENTS_NETWORK_MANAGER_IP_ADDRESS_MANAGER_H_
#include "esp_event.h"
void register_ip_address_manager_event_handlers();
#endif // PROVISIONING_ESP32_SMART_DESK_COMPONENTS_NETWORK_MANAGER_IP_ADDRESS_MANAGER_H_
|
954818696/Game-Kaleidoscope
|
UE4Case/BatteryCollector/Source/BatteryCollector/BatteryCollector.h
|
<gh_stars>0
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#ifndef __BATTERYCOLLECTOR_H__
#define __BATTERYCOLLECTOR_H__
#include "Engine.h"
#endif
|
954818696/Game-Kaleidoscope
|
UE4Case/BatteryCollector/Source/BatteryCollector/Private/BatteryPickup.h
|
<reponame>954818696/Game-Kaleidoscope
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Pickup.h"
#include "BatteryPickup.generated.h"
/**
*
*/
UCLASS()
class ABatteryPickup : public APickup
{
GENERATED_BODY()
public:
ABatteryPickup();
void WasCollected_Implementation() override;
float GetPower();
protected:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Power, Meta = (BlueprintProtected = "true"))
float BatteryPower;
};
|
954818696/Game-Kaleidoscope
|
UE4Case/BatteryCollector/Source/BatteryCollector/Private/SpawnVolume.h
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/Actor.h"
#include "SpawnVolume.generated.h"
UCLASS()
class ASpawnVolume : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ASpawnVolume();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called every frame
virtual void Tick( float DeltaSeconds ) override;
FORCEINLINE class UBoxComponent* GetWhereToSpawn() const { return WhereToSpawn; }
UFUNCTION(BlueprintPure, Category = Spawning)
FVector GetRandomPointVolume();
UFUNCTION(BlueprintCallable, Category = Spawning)
void SetSpawningActive(bool bShouldSpawn);
protected:
UPROPERTY(EditAnywhere, Category = Spawning)
TSubclassOf<class APickup> WhatToSpawn;
FTimerHandle SpawnTimer;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Spawning)
float SpawnDelayRangeLow;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Spawning)
float SpawnDelayRangeHigh;
private:
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Spawning, meta = (AllowPrivateAccess = "true"))
class UBoxComponent* WhereToSpawn;
void SpawnPickup();
float SpawnDelay;
};
|
954818696/Game-Kaleidoscope
|
UE4Case/BatteryCollector/Source/BatteryCollector/BatteryCollectorGameMode.h
|
<reponame>954818696/Game-Kaleidoscope
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "GameFramework/GameMode.h"
#include "BatteryCollectorGameMode.generated.h"
UENUM(BlueprintType)
enum class EBatteryPlayState
{
EPlaying,
EGameOver,
EWon,
EUnknown,
};
UCLASS(minimalapi)
class ABatteryCollectorGameMode : public AGameMode
{
GENERATED_BODY()
public:
ABatteryCollectorGameMode();
virtual void Tick(float DeltaTime) override;
virtual void BeginPlay() override;
UFUNCTION(BlueprintPure, Category = Power)
float GetPowerToWin() const;
UFUNCTION(BlueprintPure, Category = Power)
EBatteryPlayState GetCurrentState() const;
void SetCurrentState(EBatteryPlayState NewState);
protected:
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = Power, Meta = (BlueprintProtected = "true"))
float DecayRate;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = Power, Meta = (BlueprintProtected = "true"))
float PowerToWin;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = Power, Meta = (BlueprintProtected = "true"))
TSubclassOf<class UUserWidget> HUDWidgetClass;
UPROPERTY()
class UUserWidget* CurrentWidget;
private:
EBatteryPlayState CurrentState;
TArray<class ASpawnVolume*> SpawnVolumeActors;
void HandleNewState(EBatteryPlayState NewState);
};
|
ianayl/ship
|
src/parser/tokens.h
|
<filename>src/parser/tokens.h
#ifndef TOKENS_H
#define TOKENS_H
/* Types for tokens */
/* TODO document crap better */
enum tk_type
{
NULL_TYPE, /* This is so that a type of 0 represents null */
/* The following needs to be processed again depending on type */
TOKEN, /* Generic token type, before distinguishing token types */
EXP_PARAM, /* Parameter expansion (variables basically) */
EXP_ARITH, /* Arithmetic expansion (math) */
SUB_CMD, /* Command substitution (subshell) */
/* The following are specified token types */
WORD,
ASSIGNMENT_WORD,
NAME,
/* Misc. types */
NEWLINE,
IO_NUMBER,
/* Operators */
OP_ANDIF, /* &&, AND logic */
OP_AMPERSAND, /* &, asynchronous execution */
OP_ANDOR, /* ||, OR logic */
OP_PIPE, /* |, and uh... it's a pipe, idk what else to tell you */
OP_DSEMI, /* ;;, I think it's only for case conditional constructs */
OP_SEMICOLON, /* ;, do something, wait til its done, do next thing */
OP_DLESSDASH, /* <<- */
OP_DLESS, /* << */
OP_LESSAND, /* <& */
OP_LESSGREAT, /* <> */
OP_LESS, /* < */
OP_CLOBBER, /* >| */
OP_DGREAT, /* >> */
OP_GREATAND, /* >& */
OP_GREAT /* > */
} tk_type;
/* Stores a single token and it's type */
struct token
{
char* val;
enum tk_type type;
} token;
/* An array of tokens */
struct tk_arr
{
struct token* arr;
unsigned len;
/*
* Was the lexer in quotes before the end of the input?
*
* in_quotes can be either:
* - The value 0, indicating that the lexer is currently not in quotes
* - The ascii value of the quotes that the lexer is currently in
* - eg. 34 for '\"', 44 for '\''
*/
unsigned short in_quotes;
/* Was there a line continuation? */
unsigned short in_line_cont;
/*
* Was the lexer in command substitution before the end of the input?
*
* in_sub_cmd can be either:
* - The value of, indicating that the lexer is currently not in command
* substitution
* - The ascii value of the beginning sequence that started the command
* substitution
* - eg. 36 for '$', 96 for '`'
*/
unsigned short in_sub_cmd;
/* Was the lexer in arithmetic expansion before the end of input? */
unsigned short in_exp_arith;
/* Was the lexer in parameter expansion before the end of input? */
unsigned short in_exp_param;
} tk_arr;
/* Initializes new tk_arr */
struct tk_arr ta_new ();
/* Pushes a new token onto dest */
void ta_push (struct tk_arr *dest, char* val, enum tk_type type);
/* Sets the status variables for dest. tk_arr */
void ta_set_status (struct tk_arr *dest,
unsigned short is_in_quotes);
/* Gets the token struct at index */
struct token ta_get_token (struct tk_arr *src, unsigned index);
/* Gets the string value of the token at index */
char* ta_get_val (struct tk_arr *src, unsigned index);
/* Gets the tk_type of the token at index */
enum tk_type ta_get_type (struct tk_arr *src, unsigned index);
/* Properly destroys and cleans up a tk_arr */
void ta_destroy (struct tk_arr *dest);
#endif
|
pzmarzly/foundationdb
|
fdbrpc/genericactors.actor.h
|
/*
* genericactors.actor.h
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// When actually compiled (NO_INTELLISENSE), include the generated version of this file. In intellisense use the source version.
#if defined(NO_INTELLISENSE) && !defined(FDBRPC_GENERICACTORS_ACTOR_G_H)
#define FDBRPC_GENERICACTORS_ACTOR_G_H
#include "genericactors.actor.g.h"
#elif !defined(RPCGENERICACTORS_ACTOR_H)
#define RPCGENERICACTORS_ACTOR_H
#include "flow/genericactors.actor.h"
#include "fdbrpc.h"
ACTOR template <class Req>
Future<REPLY_TYPE(Req)> retryBrokenPromise( RequestStream<Req> to, Req request ) {
// Like to.getReply(request), except that a broken_promise exception results in retrying request immediately.
// Suitable for use with well known endpoints, which are likely to return to existence after the other process restarts.
// Not normally useful for ordinary endpoints, which conventionally are permanently destroyed after replying with broken_promise.
loop {
try {
REPLY_TYPE(Req) reply = wait( to.getReply( request ) );
return reply;
} catch( Error& e ) {
if (e.code() != error_code_broken_promise)
throw;
resetReply( request );
Void _ = wait( delayJittered(FLOW_KNOBS->PREVENT_FAST_SPIN_DELAY) );
TEST(true); // retryBrokenPromise
}
}
}
ACTOR template <class Req>
Future<REPLY_TYPE(Req)> retryBrokenPromise( RequestStream<Req> to, Req request, int taskID ) {
// Like to.getReply(request), except that a broken_promise exception results in retrying request immediately.
// Suitable for use with well known endpoints, which are likely to return to existence after the other process restarts.
// Not normally useful for ordinary endpoints, which conventionally are permanently destroyed after replying with broken_promise.
loop {
try {
REPLY_TYPE(Req) reply = wait( to.getReply( request, taskID ) );
return reply;
} catch( Error& e ) {
if (e.code() != error_code_broken_promise)
throw;
resetReply( request );
Void _ = wait( delayJittered(FLOW_KNOBS->PREVENT_FAST_SPIN_DELAY, taskID) );
TEST(true); // retryBrokenPromise
}
}
}
ACTOR template <class T>
Future<T> timeoutWarning( Future<T> what, double time, PromiseStream<Void> output ) {
state double start = now();
state Future<Void> end = delay( time );
loop choose {
when ( T t = wait( what ) ) { return t; }
when ( Void _ = wait( end ) ) {
output.send( Void() );
end = delay( time );
}
}
}
ACTOR template <class T>
void networkSender( Future<T> input, Endpoint endpoint ) {
try {
T value = wait( input );
FlowTransport::transport().sendUnreliable( SerializeBoolAnd<T>(true, value), endpoint, false );
} catch (Error& err) {
//if (err.code() == error_code_broken_promise) return;
ASSERT( err.code() != error_code_actor_cancelled );
FlowTransport::transport().sendUnreliable( SerializeBoolAnd<Error>(false, err), endpoint, false );
}
}
ACTOR template <class T>
void forwardPromise( Promise<T> output, Future<T> input ) {
try {
T value = wait(input);
output.send(value);
} catch (Error& err) {
output.sendError(err);
}
}
ACTOR template <class T>
void forwardPromise(ReplyPromise<T> output, Future<T> input) {
try {
T value = wait(input);
output.send(value);
}
catch (Error& err) {
output.sendError(err);
}
}
ACTOR template <class T>
void forwardPromise( PromiseStream<T> output, Future<T> input ) {
try{
T value = wait(input);
output.send(value);
} catch (Error& e) {
output.sendError(e);
}
}
ACTOR template <class T> Future<Void> broadcast(Future<T> input, std::vector<Promise<T>> output) {
T value = wait(input);
for (int i = 0; i<output.size(); i++)
output[i].send(value);
return Void();
}
ACTOR template <class T> Future<Void> broadcast( Future<T> input, std::vector<ReplyPromise<T>> output ) {
T value = wait( input );
for(int i=0; i<output.size(); i++)
output[i].send(value);
return Void();
}
// Needed for the call to endpointNotFound()
#include "FailureMonitor.h"
// Implements tryGetReply, getReplyUnlessFailedFor
ACTOR template <class X>
Future<ErrorOr<X>> waitValueOrSignal( Future<X> value, Future<Void> signal, Endpoint endpoint, ReplyPromise<X> holdme = ReplyPromise<X>() ) {
loop {
try {
choose {
when ( X x = wait(value) ) {
return x;
}
when ( Void _ = wait(signal) ) {
return ErrorOr<X>(request_maybe_delivered());
}
}
} catch (Error& e) {
if (signal.isError()) {
TraceEvent(SevError, "WaitValueOrSignalError").error(signal.getError());
return ErrorOr<X>(internal_error());
}
if( e.code() == error_code_actor_cancelled )
throw e;
// broken_promise error normally means an endpoint failure, which in tryGetReply has the same semantics as receiving the failure signal
if (e.code() != error_code_broken_promise || signal.isError())
return ErrorOr<X>(e);
IFailureMonitor::failureMonitor().endpointNotFound( endpoint );
value = Never();
}
}
}
ACTOR template <class T>
Future<T> sendCanceler( ReplyPromise<T> reply, PacketID send, Endpoint endpoint ) {
try {
T t = wait( reply.getFuture() );
FlowTransport::transport().cancelReliable(send);
return t;
} catch (Error& e) {
FlowTransport::transport().cancelReliable(send);
if (e.code() == error_code_broken_promise) {
IFailureMonitor::failureMonitor().endpointNotFound( endpoint );
}
throw;
}
}
ACTOR template <class X>
Future<X> reportEndpointFailure( Future<X> value, Endpoint endpoint ) {
try {
X x = wait(value);
return x;
} catch (Error& e) {
if (e.code() == error_code_broken_promise) {
IFailureMonitor::failureMonitor().endpointNotFound( endpoint );
}
throw;
}
}
Future<Void> disableConnectionFailuresAfter( double const& time, std::string const& context );
#endif
|
asterics/IRTrans-Server
|
xbmc.c
|
<reponame>asterics/IRTrans-Server
/*
* Copyright (c) 2007, IRTrans GmbH
* 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.
* * Neither the name of IRTrans GmbH nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY IRTrans GmbH ``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 IRTrans GmbH 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.
*/
#ifdef WIN32
#define _WIN32_WINNT 0x501
#ifndef VC6
#include "winsock2.h"
#endif
#include <windows.h>
#include <winuser.h>
#include <io.h>
#include <direct.h>
#include <stdio.h>
#include <sys/timeb.h>
#include <tlhelp32.h>
#endif
#include <stdio.h>
#ifdef LINUX
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdint.h>
typedef int DWORD;
#define closesocket close
#endif
#include "remote.h"
#include "global.h"
#include "network.h"
#include "lowlevel.h"
#include "dbstruct.h"
#define BTN_USE_NAME 0x01
#define BTN_DOWN 0x02
#define BTN_UP 0x04
#define BTN_USE_AMOUNT 0x08
#define BTN_QUEUE 0x10
#define BTN_NO_REPEAT 0x20
#define BTN_VKEY 0x40
#define BTN_AXIS 0x80
#define PT_HELO 0x01
#define PT_BYE 0x02
#define PT_BUTTON 0x03
#define PT_MOUSE 0x04
#define PT_PING 0x05
#define PT_BROADCAST 0x06
#define PT_NOTIFICATION 0x07
#define PT_BLOB 0x08
#define PT_LOG 0x09
#define PT_ACTION 0x0A
#define PT_DEBUG 0xFF
#define ICON_NONE 0x00
#define ICON_JPEG 0x01
#define ICON_PNG 0x02
#define ICON_GIF 0x03
#define MAX_PACKET_SIZE 1024
#define HEADER_SIZE 32
#define MAX_PAYLOAD_SIZE (MAX_PACKET_SIZE - HEADER_SIZE)
#define MAJOR_VERSION 2
#define MINOR_VERSION 0
extern byte xbmc_mode;
#define ACTION_EXECBUILTIN 1
#define ACTION_BUTTON 2
DWORD xbmc_pid;
unsigned int xbmc_uid;
unsigned int xbmc_seq;
unsigned long XBMC_last_ping;
int xbmc_remote;
byte xbmc_init;
SOCKET xbmc_socket;
void XBMC_SendBye ()
{
int res;
byte data[1024];
if (!xbmc_init) return;
res = BuildXBMCHeader (data,PT_BYE,0);
send (xbmc_socket,(const char *)data,res,0);
}
void XBMC_SendPing ()
{
int res;
byte data[1024];
if (!xbmc_init) return;
res = BuildXBMCHeader (data,PT_PING,0);
send (xbmc_socket,(const char *)data,res,0);
XBMC_last_ping = time (0);
}
void StartXBMC (APP *app)
{
int i;
char *progdir;
char prog[1024],appname[1024];
if (!xbmc_mode) return;
if (xbmc_init) closesocket (xbmc_socket);
xbmc_init = 0;
xbmc_pid = 0;
#ifdef WIN32
if (app->appname[0] == '%') {
strcpy (appname,app->appname);
i = 1;
while (appname[i] && appname[i] != '%') i++;
appname[i++] = 0;
progdir = getenv (appname + 1);
if (!progdir) progdir = getenv ("ProgramFiles");
if (!progdir) return;
sprintf (prog,"%s%s",progdir,appname+i);
}
else strcpy (prog,app->appname);
WinExec (prog,SW_SHOWMAXIMIZED);
#endif
#ifdef LINUX
system (app->appname);
#endif
}
#ifdef WIN32
byte XBMC_CheckRunning (void)
{
HANDLE pHandle;
pHandle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, xbmc_pid);
if (pHandle == NULL) {
xbmc_pid = 0;
return (0);
}
CloseHandle(pHandle);
return (1);
}
DWORD XBMC_GetPID (void)
{
HANDLE hProcessSnap;
PROCESSENTRY32 peStruct;
xbmc_pid = 0;
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(hProcessSnap == INVALID_HANDLE_VALUE) return (0);
peStruct.dwSize = sizeof(PROCESSENTRY32);
if(Process32First(hProcessSnap, &peStruct) == FALSE){
CloseHandle(hProcessSnap);
return (0);
}
do {
if (!strcmp (peStruct.szExeFile,"xbmc.exe") || !strcmp (peStruct.szExeFile,"XBMC.exe") || !strcmp (peStruct.szExeFile,"XBMC.EXE")) {
xbmc_pid = peStruct.th32ProcessID;
break;
}
}
while(Process32Next(hProcessSnap, &peStruct));
CloseHandle(hProcessSnap);
return xbmc_pid;
}
#endif
#ifdef LINUX
byte XBMC_CheckRunning (void)
{
if (kill (xbmc_pid,0)) {
xbmc_pid = 0;
return (0);
}
return (1);
}
DWORD XBMC_GetPID (void)
{
int i;
char ln[200];
FILE *fp;
xbmc_pid = 0;
fp = popen( "ps aux|grep -v grep|grep -i xbmc.bin", "r");
fgets (ln,sizeof (ln),fp);
pclose (fp);
i = 0;
while (ln[i] && ln[i] != ' ' && ln[i] != '\t') i++;
if (!ln[i]) return;
while (ln[i] == ' ' || ln[i] == '\t') i++;
if (!ln[i]) return;
xbmc_pid = atoi (ln + i);
printf ("PID: %d\n",xbmc_pid);
return xbmc_pid;
}
#endif
void SendXBMC (APPCOMMAND *appcom)
{
int res;
byte data[1024];
if (!xbmc_mode) return;
if (!xbmc_init || !XBMC_CheckRunning ()) {
res = InitXBMC ();
if (res) return;
}
res = 0;
if (appcom->type[0] == TYPE_STR || appcom->type[0] == TYPE_XBMC_BUTTON) {
res = BuildXBMCKey (data,appcom->function.name);
}
else if (appcom->type[0] == TYPE_XBMC_ACTION) {
res = BuildXBMCAction (data,ACTION_BUTTON,appcom->function.name);
}
else if (appcom->type[0] == TYPE_XBMC_ACTION_BUILTIN) {
res = BuildXBMCAction (data,ACTION_EXECBUILTIN,appcom->function.name);
}
if (!res) return;
send (xbmc_socket,(const char *)data,res,0);
XBMC_last_ping = time (0);
}
int InitXBMC (void)
{
int res;
byte data[1024];
struct sockaddr_in serv_addr;
if (!xbmc_mode) return (1);
if (!XBMC_GetPID ()) return (1);
xbmc_socket = socket (PF_INET,SOCK_DGRAM,0);
if (xbmc_socket < 0) return (1);
memset (&serv_addr,0,sizeof (serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr ("127.0.0.1");
serv_addr.sin_port = htons ((word)9777);
res = connect (xbmc_socket,(struct sockaddr *)&serv_addr,sizeof (serv_addr));
if (res) return (res);
xbmc_uid = time (0);
res = BuildXBMCHelo (data,"IRTrans Server");
send (xbmc_socket,(const char *)data,res,0);
xbmc_init = 1;
XBMC_last_ping = time (0);
return (0);
}
int BuildXBMCHeader (byte *data,short type,int payload_len)
{
unsigned short u16;
unsigned int u32;
memset (data,0,HEADER_SIZE + payload_len);
memcpy (data + 0,"XBMC",4); // Signature
data[4] = MAJOR_VERSION; // Major Version
data[5] = MINOR_VERSION; // Minor Version
u16 = htons (type);
memcpy (data + 6,&u16,2); // Packet Type
u32 = htonl (xbmc_seq++);
memcpy (data + 8,&u32,4); // SEQ Number
u32 = htonl (1);
memcpy (data + 12,&u32,4); // Number of packets
u16 = htons ((word)payload_len);
memcpy (data + 16,&u16,2); // LEN of Payload
u32 = htonl (xbmc_uid);
memcpy (data + 18,&u32,4); // UID
return (payload_len + HEADER_SIZE);
}
int BuildXBMCHelo (byte *data,char *name)
{
int len;
len = BuildXBMCHeader (data,PT_HELO,strlen (name) + 12);
strcpy ((char *)data + HEADER_SIZE,name);
return (len);
}
int BuildXBMCAction (byte *data,byte type,char *action)
{
int len;
unsigned short u16;
len = BuildXBMCHeader (data,PT_ACTION,strlen (action) + 2);
data[HEADER_SIZE] = type;
strcpy ((char *)data + HEADER_SIZE + 1,action);
return (len);
}
int BuildXBMCKey (byte *data,char *button)
{
int len;
unsigned short u16;
len = BuildXBMCHeader (data,PT_BUTTON,strlen (button) + 10);
u16 = htons (0);
memcpy (data + HEADER_SIZE + 0,&u16,2); // Button Code
u16 = htons (0x2b);
memcpy (data + HEADER_SIZE + 2,&u16,2); // Flags
u16 = htons (0);
memcpy (data + HEADER_SIZE + 4,&u16,2); // Amount
strcpy ((char *)data + HEADER_SIZE + 6,"R1"); // Device Map
strcpy ((char *)data + HEADER_SIZE + 9,button); // Button Name
return (len);
}
|
asterics/IRTrans-Server
|
linuxserio.c
|
<reponame>asterics/IRTrans-Server<gh_stars>1-10
/*
* Copyright (c) 2007, IRTrans GmbH
* 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.
* * Neither the name of IRTrans GmbH nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY IRTrans GmbH ``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 IRTrans GmbH 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.
*/
#ifdef LINUX
#include <sys/time.h>
#include <sys/types.h>
#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <termios.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include "remote.h"
#include "errcode.h"
#include "network.h"
#include "lowlevel.h"
#include "serio.h"
#include "global.h"
#define BAUDRATE B38400
char SerialDevice[256];
extern char baudrate[10];
int hCom;
void msSleep (int time)
{
struct timeval tv;
tv.tv_sec = time / 1000;
tv.tv_usec = (time % 1000) * 1000;
select (0,NULL,NULL,NULL,&tv);
}
void WriteSerialString (byte pnt[],int len)
{
int res,stat;
res = write (hCom,pnt,len);
if (res != len) {
log_print ("IRTrans Connection lost. Aborting ...\n",LOG_FATAL);
exit (-1);
}
}
int ReadSerialString (byte pnt[],int len,word timeout)
{
int bytes,total = 0;
struct timeval tv;
fd_set fs;
while (total < len) {
FD_ZERO (&fs);
FD_SET (hCom,&fs);
tv.tv_sec = timeout / 1000;
tv.tv_usec = (timeout % 1000) * 1000;
bytes = select (hCom+1,&fs,NULL,NULL,&tv);
if (!bytes) return (total);
bytes = read (hCom,pnt+total,len-total);
total += bytes;
}
return (total);
}
int WriteSerialStringEx (DEVICEINFO *dev,byte pnt[],int len)
{
int res,stat = 1;
res = write (dev->io.comport,pnt,len);
if (res != len) {
if (dev->io.if_type == IF_USB && !(mode_flag & NO_RECONNECT)) {
close (dev->io.comport);
while (stat) {
stat = OpenSerialPortEx (dev->io.node,&dev->io.comport,0);
if (stat) sleep (10);
}
}
else {
log_print ("IRTrans Connection lost. Aborting ...\n",LOG_FATAL);
exit (-1);
}
return (ERR_TIMEOUT);
}
return (0);
}
int ReadSerialStringEx (DEVICEINFO *dev,byte pnt[],int len,word timeout)
{
char st[80];
int bytes,total = 0;
struct timeval tv;
fd_set fs;
while (total < len) {
FD_ZERO (&fs);
FD_SET (dev->io.comport,&fs);
tv.tv_sec = timeout / 1000;
tv.tv_usec = (timeout % 1000) * 1000;
bytes = select (dev->io.comport+1,&fs,NULL,NULL,&tv);
if (!bytes) return (total);
bytes = read (dev->io.comport,pnt+total,len-total);
if (!bytes) return (total);
total += bytes;
}
return (total);
}
void FlushCom ()
{
}
void FlushComEx(HANDLE fp)
{
int bytes;
struct timeval tv;
fd_set fs;
char dummy[256];
FD_ZERO (&fs);
FD_SET (fp,&fs);
tv.tv_sec = 0;
tv.tv_usec = 10000;
bytes = select (fp+1,&fs,NULL,NULL,&tv);
if (!bytes) return;
bytes = read (fp,dummy,256);
}
int WritePort (DEVICEINFO *dev,byte pnt[],int len)
{
int res;
res = write (dev->virtual_comport,pnt,len);
if (res != len) return (ERR_TIMEOUT);
else return (0);
}
int OpenVirtualComport (char Pname[],int *port)
{
if ((*port = open(Pname, O_RDWR | O_NOCTTY)) < 0) return (ERR_OPEN);
return (0);
}
int OpenSerialPort(char Pname[])
{
int parnum = 0,res,flg;
struct termios portterm;
strcpy (SerialDevice,Pname);
if ((hCom = open(Pname, O_RDWR | O_NOCTTY)) < 0) return (ERR_OPEN);
if (!isatty(hCom)) {
close(hCom);
return (ERR_OPEN);
}
#ifndef DBOX
if (flock(hCom, LOCK_EX | LOCK_NB) < 0) {
close(hCom);
return (ERR_FLOCK);
}
#endif
portterm.c_cflag = CS8 | CREAD | CLOCAL;
portterm.c_cc[VMIN] = 1;
portterm.c_cc[VTIME] = 0;
cfsetispeed(&portterm, BAUDRATE);
cfsetospeed(&portterm, BAUDRATE);
portterm.c_lflag = 0;
portterm.c_iflag = IGNBRK;
portterm.c_oflag = 0;
tcflush(hCom, TCIOFLUSH);
if (tcsetattr(hCom, TCSANOW, &portterm) < 0) {
close(hCom);
return (ERR_STTY);
}
msSleep (1000);
tcflush(hCom, TCIOFLUSH);
return (0);
}
int OpenSerialPortEx (char Pname[],int *port,int wait)
{
int res,flg;
struct termios portterm;
if ((*port = open(Pname, O_RDWR | O_NOCTTY)) < 0) return (ERR_OPEN);
if (!isatty(*port)) {
close(*port);
return (ERR_OPEN);
}
#ifndef DBOX
if (flock(*port, LOCK_EX | LOCK_NB) < 0) {
close(*port);
return (ERR_FLOCK);
}
#endif
portterm.c_cflag = CS8 | CREAD | CLOCAL;
portterm.c_cc[VMIN] = 1;
portterm.c_cc[VTIME] = 0;
if (!strcmp (baudrate,"4800")) {
cfsetispeed(&portterm, B4800);
cfsetospeed(&portterm, B4800);
}
else if (!strcmp (baudrate,"9600")) {
cfsetispeed(&portterm, B9600);
cfsetospeed(&portterm, B9600);
}
else if (!strcmp (baudrate,"19200")) {
cfsetispeed(&portterm, B19200);
cfsetospeed(&portterm, B19200);
}
else if (!strcmp (baudrate,"57600")) {
cfsetispeed(&portterm, B57600);
cfsetospeed(&portterm, B57600);
}
else if (!strcmp (baudrate,"115200")) {
cfsetispeed(&portterm, B115200);
cfsetospeed(&portterm, B115200);
portterm.c_cflag = CS8 | CREAD | CLOCAL | CSTOPB;
}
else {
cfsetispeed(&portterm, BAUDRATE);
cfsetospeed(&portterm, BAUDRATE);
}
portterm.c_lflag = 0;
portterm.c_iflag = IGNBRK;
portterm.c_oflag = 0;
tcflush(*port, TCIOFLUSH);
if (tcsetattr(*port, TCSANOW, &portterm) < 0) {
close(*port);
return (ERR_STTY);
}
msSleep (1000);
tcflush(*port, TCIOFLUSH);
return (0);
}
#ifdef DBOX
tcflush (int fd,int mode)
{
char st[1024];
do {
} while (ReadSerialString (st,1000,10) == 1000);
}
#endif
#endif
|
asterics/IRTrans-Server
|
pictures.h
|
/*
* Copyright (c) 2007, IRTrans GmbH
* 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.
* * Neither the name of IRTrans GmbH nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY IRTrans GmbH ``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 IRTrans GmbH 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.
*/
unsigned char irtrans_logo[] = {
0x47,0x49,0x46,0x38,0x39,0x61,0xa1,0x00,0x64,0x00,0xf7,0x00,0x00,0x00,0x00,0x00
,0x33,0x00,0x00,0x66,0x00,0x00,0x99,0x00,0x00,0xcc,0x00,0x00,0xff,0x00,0x00,0x00
,0x33,0x00,0x33,0x33,0x00,0x66,0x33,0x00,0x99,0x33,0x00,0xcc,0x33,0x00,0xff,0x33
,0x00,0x00,0x66,0x00,0x33,0x66,0x00,0x66,0x66,0x00,0x99,0x66,0x00,0xcc,0x66,0x00
,0xff,0x66,0x00,0x00,0x99,0x00,0x33,0x99,0x00,0x66,0x99,0x00,0x99,0x99,0x00,0xcc
,0x99,0x00,0xff,0x99,0x00,0x00,0xcc,0x00,0x33,0xcc,0x00,0x66,0xcc,0x00,0x99,0xcc
,0x00,0xcc,0xcc,0x00,0xff,0xcc,0x00,0x00,0xff,0x00,0x33,0xff,0x00,0x66,0xff,0x00
,0x99,0xff,0x00,0xcc,0xff,0x00,0xff,0xff,0x00,0x00,0x00,0x33,0x33,0x00,0x33,0x66
,0x00,0x33,0x99,0x00,0x33,0xcc,0x00,0x33,0xff,0x00,0x33,0x00,0x33,0x33,0x33,0x33
,0x33,0x66,0x33,0x33,0x99,0x33,0x33,0xcc,0x33,0x33,0xff,0x33,0x33,0x00,0x66,0x33
,0x33,0x66,0x33,0x66,0x66,0x33,0x99,0x66,0x33,0xcc,0x66,0x33,0xff,0x66,0x33,0x00
,0x99,0x33,0x33,0x99,0x33,0x66,0x99,0x33,0x99,0x99,0x33,0xcc,0x99,0x33,0xff,0x99
,0x33,0x00,0xcc,0x33,0x33,0xcc,0x33,0x66,0xcc,0x33,0x99,0xcc,0x33,0xcc,0xcc,0x33
,0xff,0xcc,0x33,0x00,0xff,0x33,0x33,0xff,0x33,0x66,0xff,0x33,0x99,0xff,0x33,0xcc
,0xff,0x33,0xff,0xff,0x33,0x00,0x00,0x66,0x33,0x00,0x66,0x66,0x00,0x66,0x99,0x00
,0x66,0xcc,0x00,0x66,0xff,0x00,0x66,0x00,0x33,0x66,0x33,0x33,0x66,0x66,0x33,0x66
,0x99,0x33,0x66,0xcc,0x33,0x66,0xff,0x33,0x66,0x00,0x66,0x66,0x33,0x66,0x66,0x66
,0x66,0x66,0x99,0x66,0x66,0xcc,0x66,0x66,0xff,0x66,0x66,0x00,0x99,0x66,0x33,0x99
,0x66,0x66,0x99,0x66,0x99,0x99,0x66,0xcc,0x99,0x66,0xff,0x99,0x66,0x00,0xcc,0x66
,0x33,0xcc,0x66,0x66,0xcc,0x66,0x99,0xcc,0x66,0xcc,0xcc,0x66,0xff,0xcc,0x66,0x00
,0xff,0x66,0x33,0xff,0x66,0x66,0xff,0x66,0x99,0xff,0x66,0xcc,0xff,0x66,0xff,0xff
,0x66,0x00,0x00,0x99,0x33,0x00,0x99,0x66,0x00,0x99,0x99,0x00,0x99,0xcc,0x00,0x99
,0xff,0x00,0x99,0x00,0x33,0x99,0x33,0x33,0x99,0x66,0x33,0x99,0x99,0x33,0x99,0xcc
,0x33,0x99,0xff,0x33,0x99,0x00,0x66,0x99,0x33,0x66,0x99,0x66,0x66,0x99,0x99,0x66
,0x99,0xcc,0x66,0x99,0xff,0x66,0x99,0x00,0x99,0x99,0x33,0x99,0x99,0x66,0x99,0x99
,0x99,0x99,0x99,0xcc,0x99,0x99,0xff,0x99,0x99,0x00,0xcc,0x99,0x33,0xcc,0x99,0x66
,0xcc,0x99,0x99,0xcc,0x99,0xcc,0xcc,0x99,0xff,0xcc,0x99,0x00,0xff,0x99,0x33,0xff
,0x99,0x66,0xff,0x99,0x99,0xff,0x99,0xcc,0xff,0x99,0xff,0xff,0x99,0x00,0x00,0xcc
,0x33,0x00,0xcc,0x66,0x00,0xcc,0x99,0x00,0xcc,0xcc,0x00,0xcc,0xff,0x00,0xcc,0x00
,0x33,0xcc,0x33,0x33,0xcc,0x66,0x33,0xcc,0x99,0x33,0xcc,0xcc,0x33,0xcc,0xff,0x33
,0xcc,0x00,0x66,0xcc,0x33,0x66,0xcc,0x66,0x66,0xcc,0x99,0x66,0xcc,0xcc,0x66,0xcc
,0xff,0x66,0xcc,0x00,0x99,0xcc,0x33,0x99,0xcc,0x66,0x99,0xcc,0x99,0x99,0xcc,0xcc
,0x99,0xcc,0xff,0x99,0xcc,0x00,0xcc,0xcc,0x33,0xcc,0xcc,0x66,0xcc,0xcc,0x99,0xcc
,0xcc,0xc0,0xc0,0xc0,0xff,0xcc,0xcc,0x00,0xff,0xcc,0x33,0xff,0xcc,0x66,0xff,0xcc
,0x99,0xff,0xcc,0xcc,0xff,0xcc,0xff,0xff,0xcc,0x00,0x00,0xff,0x33,0x00,0xff,0x66
,0x00,0xff,0x99,0x00,0xff,0xcc,0x00,0xff,0xff,0x00,0xff,0x00,0x33,0xff,0x33,0x33
,0xff,0x66,0x33,0xff,0x99,0x33,0xff,0xcc,0x33,0xff,0xff,0x33,0xff,0x00,0x66,0xff
,0x33,0x66,0xff,0x66,0x66,0xff,0x99,0x66,0xff,0xcc,0x66,0xff,0xff,0x66,0xff,0x00
,0x99,0xff,0x33,0x99,0xff,0x66,0x99,0xff,0x99,0x99,0xff,0xcc,0x99,0xff,0xff,0x99
,0xff,0x00,0xcc,0xff,0x33,0xcc,0xff,0x66,0xcc,0xff,0x99,0xcc,0xff,0xcc,0xcc,0xff
,0xff,0xcc,0xff,0x00,0xff,0xff,0x33,0xff,0xff,0x66,0xff,0xff,0x99,0xff,0xff,0xcc
,0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x2c,0x00,0x00
,0x00,0x00,0xa1,0x00,0x64,0x00,0x00,0x08,0xfe,0x00,0x59,0x09,0x1c,0x48,0xb0,0xa0
,0xc1,0x83,0x08,0x13,0x2a,0x5c,0xc8,0xb0,0xa1,0xc3,0x87,0x10,0x23,0x4a,0x9c,0x48
,0xb1,0xa2,0xc5,0x8b,0x18,0x33,0x6a,0xdc,0xc8,0xb1,0xa3,0xc7,0x8f,0x20,0x43,0x8a
,0x1c,0x49,0xb2,0xa4,0xc9,0x93,0x28,0x4d,0x0a,0xc2,0x92,0xb2,0xa5,0x4b,0x90,0x58
,0x08,0x10,0x10,0xf4,0xb2,0xa6,0x4d,0x8b,0x82,0x64,0xba,0xb8,0xc9,0xb3,0xa7,0x43
,0x17,0x32,0x59,0xfa,0x1c,0xda,0x13,0x0b,0xcd,0x81,0x39,0x65,0x12,0x5d,0x5a,0x33
,0xe6,0x4e,0x82,0x31,0x09,0x08,0x65,0x4a,0x55,0x65,0xd0,0x82,0x32,0x09,0x54,0xdd
,0x5a,0x32,0x6a,0xc1,0xa8,0x53,0xb9,0x8a,0xbd,0x68,0x94,0x60,0xd2,0xb0,0x49,0x9f
,0x8e,0x5d,0x3b,0x11,0xa8,0x5a,0x81,0x4e,0x0b,0x02,0x9d,0xc9,0xb6,0x2e,0x44,0xb0
,0x66,0xaf,0x22,0xd5,0x6b,0xb7,0xef,0xc2,0xac,0x72,0x09,0xbc,0x65,0xa5,0xd3,0xaf
,0x61,0xa4,0x5f,0xf9,0xb2,0x4a,0x7a,0x54,0xe0,0xdc,0xc6,0x87,0xd9,0xe6,0x1c,0x4c
,0x58,0x29,0x41,0xa0,0x61,0xf1,0x46,0xae,0x3b,0x37,0x2c,0xab,0xa8,0x90,0xe3,0xee
,0x15,0xbc,0xb9,0x6e,0x52,0xad,0x79,0x49,0x8f,0x0e,0x8c,0xba,0xf4,0xda,0xce,0xac
,0xb1,0xd2,0x1d,0xf8,0xd8,0x35,0xd3,0x98,0x90,0xd3,0x26,0x9e,0xed,0x58,0x2a,0x54
,0x99,0x90,0x6d,0x77,0x75,0x41,0xdc,0x45,0xf0,0xa8,0x83,0xb3,0xe6,0x56,0x2c,0x5a
,0xe0,0x59,0xe1,0x56,0xb3,0x66,0x35,0x7e,0x19,0xf8,0x6f,0xdf,0x04,0x0b,0x0f,0x6c
,0xbe,0x58,0x31,0x74,0x90,0xa7,0xa5,0xfe,0x6b,0x87,0xab,0xf8,0x79,0xf5,0xb7,0x49
,0x65,0x53,0xfe,0xde,0x51,0xbc,0xfb,0xa9,0xba,0x47,0x0f,0x9e,0x9b,0x5a,0x3d,0xfb
,0x90,0x51,0xdd,0x4b,0x6f,0x4c,0x3f,0xbb,0xe5,0xed,0xff,0x75,0xc7,0x5b,0x65,0xeb
,0xdd,0x97,0xd1,0x5c,0xfa,0x29,0x47,0x9b,0x75,0x03,0x01,0x76,0x5d,0x63,0x8c,0xf9
,0x57,0xa0,0x81,0x17,0x21,0x98,0x20,0x76,0x9f,0x31,0xd8,0x5b,0x6b,0xe4,0x0d,0xa8
,0x21,0x2b,0x6e,0x51,0xe8,0x91,0x85,0x09,0x4e,0x55,0xdb,0x82,0x1c,0x66,0xe8,0xe1
,0x80,0x21,0x8a,0xc8,0x51,0x7e,0x17,0xf2,0x17,0x60,0x65,0x29,0x7a,0x35,0x1a,0x64
,0xe3,0xb9,0x98,0x51,0x78,0xfa,0xbd,0x95,0x63,0x7c,0x28,0xd6,0x27,0xa1,0x8e,0x2f
,0x5e,0xc8,0x9b,0x79,0xce,0xe5,0x08,0xa2,0x6a,0x49,0xa6,0xa8,0x24,0x91,0x15,0x96
,0x58,0xdd,0x80,0x9a,0x35,0xc8,0x64,0x86,0xe8,0x79,0x07,0x25,0x59,0x16,0x52,0x07
,0xe0,0x95,0x4b,0x0e,0x88,0x24,0x96,0xa9,0x79,0xb6,0x25,0x46,0x82,0xa4,0x19,0x9c
,0x8a,0xcb,0x81,0x09,0x5a,0x75,0x99,0x7d,0x78,0xe6,0x48,0x2b,0xb1,0xe6,0x59,0x7f
,0x56,0x86,0x26,0xe7,0x9c,0x27,0x9d,0x16,0xdc,0x8f,0x33,0xe2,0xc9,0x67,0x4a,0xb0
,0x5d,0x17,0x67,0x72,0x60,0x0e,0xfa,0x10,0x89,0xe2,0x99,0x99,0xda,0x80,0x61,0x06
,0x86,0x96,0x96,0x8a,0x32,0xc4,0xe3,0x7b,0x0c,0x61,0xe1,0xd9,0x98,0x11,0x7e,0xb9
,0x66,0xa5,0x0b,0x5d,0x2a,0xde,0xa7,0x0c,0x9d,0x48,0xde,0x7c,0x33,0x82,0x9a,0xa9
,0x91,0x29,0x3a,0x54,0xa5,0x80,0xfe,0x93,0x62,0xa8,0x6a,0x43,0x8c,0x4a,0x37,0x61
,0x42,0x7e,0x5e,0xb7,0x1b,0xa9,0xb3,0x1e,0xc4,0xaa,0xa3,0xab,0xc6,0xea,0xd9,0x93
,0xbd,0x22,0x24,0xea,0x7e,0x14,0x1d,0x37,0xe3,0xab,0xc5,0x26,0x04,0xa3,0x7e,0xbc
,0x42,0x34,0x66,0x98,0xd1,0x36,0xdb,0xe1,0x85,0x1a,0xb5,0xf8,0x25,0xb0,0xd6,0x4e
,0x99,0xe0,0xad,0xd2,0x7a,0x69,0x25,0xa4,0xdd,0x1a,0xf4,0x2b,0x7e,0x94,0x96,0x3b
,0x5a,0x8c,0xe0,0x29,0xa8,0x2e,0x42,0xcf,0xba,0x17,0x52,0xa1,0xef,0x1e,0x54,0xeb
,0x74,0x21,0x09,0x42,0x5c,0xbd,0x09,0xdd,0x9b,0xee,0x46,0xd5,0x96,0x7b,0x6c,0x56
,0xdc,0xf2,0x2b,0xd2,0xc0,0x7b,0x1a,0x4c,0x52,0xbc,0xe2,0x29,0xdc,0x92,0xbf,0x89
,0x3a,0x3c,0xd2,0xb9,0x12,0x47,0xc7,0x6e,0xc5,0x5d,0xb1,0x7a,0x14,0xc3,0xac,0x8a
,0xe7,0x42,0x59,0x18,0x1f,0xc4,0xb1,0x83,0x2a,0x76,0xdc,0xb1,0xb8,0x21,0x6f,0xf8
,0x2d,0x8a,0x26,0x9b,0x1c,0x70,0xbd,0x14,0xd3,0xd8,0xb2,0xcb,0x29,0x0b,0x78,0x31
,0xc2,0x33,0x7b,0x5c,0xf3,0xc8,0xff,0xf1,0x9c,0xf3,0xa8,0x29,0x43,0xac,0x16,0xc4
,0x3f,0xdb,0x1a,0xb4,0x91,0x43,0x23,0xad,0xe9,0xd2,0x9a,0x12,0xd7,0x71,0xc8,0x38
,0x0b,0x85,0x33,0xaf,0x3e,0x43,0xad,0x71,0x93,0x17,0x23,0x04,0xf1,0xcb,0xcd,0x56
,0x7d,0x6d,0x82,0x0b,0x6d,0x8d,0xb1,0xd0,0x2c,0xf7,0x18,0xb6,0x91,0x21,0xc7,0x1c
,0xf3,0x41,0x08,0x3f,0xa5,0x6f,0x71,0x70,0xc7,0x2d,0x77,0x71,0x05,0x43,0x37,0x35
,0xd6,0x09,0xf2,0x1a,0xf5,0xfe,0xd7,0x45,0xd7,0x2d,0x9c,0xcf,0x47,0xdd,0x8d,0x54
,0x9a,0x58,0x10,0x3d,0x9b,0xcf,0x6b,0x8b,0xe8,0x75,0xc9,0x45,0xb3,0xaa,0x16,0xe2
,0x46,0xfa,0x3d,0xa7,0xe1,0x8d,0xf3,0x06,0xf9,0x85,0x92,0x9f,0x59,0x79,0xc7,0x7a
,0x6e,0x9e,0x39,0x94,0x38,0x57,0x1e,0x9c,0x9a,0xa4,0xeb,0x0b,0x6d,0xe9,0x69,0x2a
,0x44,0x3a,0xae,0xa8,0x57,0xb4,0xba,0xa5,0xad,0x93,0xb5,0x79,0x89,0x5c,0x33,0x3a
,0xa1,0xdc,0x2c,0xc1,0x88,0x5e,0xe1,0x17,0x7e,0x6c,0xd0,0xdb,0x70,0xd3,0x64,0xba
,0xad,0xa4,0xf2,0xde,0xe3,0xe7,0xf6,0xce,0x6e,0x2b,0xc8,0x3f,0xb9,0x77,0x7b,0xa3
,0xcf,0xaa,0x15,0xba,0x4e,0x6d,0xee,0x37,0xf2,0xe8,0x86,0xa3,0x0c,0x11,0xe5,0xbf
,0x72,0xcd,0x9a,0xd1,0x5a,0x7b,0x8c,0xa9,0xcd,0x26,0x67,0xd9,0x28,0xd2,0xdf,0x3b
,0x4e,0xd1,0xd5,0x2b,0x5d,0x2d,0x91,0xed,0xfd,0x3e,0xad,0xb2,0xad,0x4e,0xbb,0x07
,0x61,0xd1,0xf7,0x37,0x9a,0x26,0xa3,0xc8,0xe3,0x0d,0x6d,0xd9,0xce,0x6b,0x4b,0x00
,0xc3,0x17,0x39,0xff,0x09,0x26,0x7f,0xd2,0x81,0x4f,0xdf,0xbe,0x44,0xb0,0xf3,0x10
,0x47,0x53,0x12,0x59,0x1c,0xf9,0xf4,0xd3,0xbf,0x30,0x81,0x2f,0x79,0x03,0x4c,0x9d
,0x73,0x56,0x52,0x38,0xed,0x0d,0x70,0x82,0xd4,0x5b,0x0c,0xfc,0xe6,0x77,0x40,0x8e
,0x90,0xed,0x3a,0x59,0x6b,0x9e,0xce,0x08,0x78,0x41,0x87,0xac,0x64,0x84,0x20,0x3c
,0xd2,0x07,0x39,0xf6,0x40,0x0d,0xae,0xaf,0x80,0x8f,0x5a,0xd9,0xf6,0x3e,0x68,0x10
,0xfe,0x35,0xe4,0x85,0xfb,0xfe,0x92,0x1e,0x0f,0x2f,0x25,0xc4,0x93,0x55,0x30,0x86
,0xc8,0xda,0x4d,0x0a,0x4b,0xc5,0xc3,0xf4,0x25,0x6c,0x3b,0xdc,0x2b,0x62,0x0b,0x65
,0x06,0xa8,0xf2,0x79,0xcf,0x80,0x0d,0xfb,0x9d,0xfa,0x16,0xd5,0x44,0x6f,0xb9,0x4b
,0x8b,0xbd,0xfb,0x20,0x11,0x65,0x33,0xc5,0xe1,0x6d,0xf1,0x21,0x3c,0x2b,0x10,0xd1
,0xbc,0x07,0xc3,0x1e,0xca,0x8b,0x6d,0xb4,0x13,0x88,0x18,0x9b,0xd8,0xc5,0xc5,0x74
,0xd0,0x48,0x57,0x3c,0x21,0x18,0x31,0xc7,0xc5,0x15,0x62,0x50,0x3a,0xf0,0x1a,0xdf
,0xb8,0xf0,0x65,0x40,0x44,0x4d,0x91,0x6d,0xc6,0x4b,0x20,0x44,0x12,0xe7,0x1f,0x3c
,0xaa,0xf0,0x90,0x00,0x6c,0x15,0x09,0x53,0x34,0xc6,0x42,0x92,0x91,0x90,0x8b,0x21
,0x9c,0xa6,0x82,0x43,0xa2,0xcf,0x09,0x4e,0x64,0x8c,0x64,0x21,0x26,0xdd,0x98,0x45
,0x52,0x26,0x31,0x86,0x52,0x1c,0x25,0x15,0x55,0x53,0x49,0x00,0x7a,0x4f,0x82,0x7b
,0xd4,0x21,0x13,0xfd,0x68,0x4a,0x92,0x39,0x31,0x28,0x89,0xf4,0x63,0x2b,0xe5,0xe8
,0x47,0xdb,0x2d,0x8d,0x51,0x77,0x41,0x9f,0x42,0xd6,0x48,0xab,0x3a,0x4e,0xd2,0x58
,0x45,0x4b,0xa5,0x92,0xe6,0x38,0xb3,0x3c,0xe2,0x10,0x57,0x67,0x1c,0xa6,0x31,0x2d
,0x68,0x4b,0x25,0x52,0xf0,0x52,0xeb,0x52,0xe5,0x10,0x5b,0x76,0xc5,0x55,0x36,0x6a
,0x96,0xd8,0x5a,0x15,0x2d,0x6f,0xa9,0x3a,0xdb,0x1d,0x85,0x44,0x81,0x13,0x24,0x2f
,0xcb,0x98,0xcb,0xe5,0x75,0x73,0x4b,0xa5,0x73,0x49,0xec,0x6a,0xc6,0x94,0x80,0x00
,0x00,0x3b};
unsigned char ok_button[] = {
0x47,0x49,0x46,0x38,0x39,0x61,0x46,0x00,0x18,0x00,0xf7,0x00,0x00,0x00,0x00,0x84,
0x40,0x40,0x40,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x21,0xf9,0x04,
0x01,0x00,0x00,0x01,0x00,0x2c,0x00,0x00,0x00,0x00,0x46,0x00,0x18,0x00,0x00,0x08,
0xba,0x00,0x03,0x08,0x1c,0x48,0x50,0x20,0x80,0x83,0x08,0x13,0x2a,0x5c,0xc8,0xb0,
0xa1,0xc3,0x83,0x05,0x23,0x4a,0x34,0xf8,0xb0,0xa2,0xc5,0x8b,0x0b,0x27,0x4a,0xc4,
0xc8,0xb1,0xa3,0x45,0x8d,0x03,0x3d,0x8a,0x1c,0xa9,0x10,0x24,0xc9,0x93,0x24,0x27,
0xa2,0x5c,0x29,0x72,0xe3,0x48,0x01,0x30,0x61,0x2e,0x8c,0x29,0x20,0x21,0xcd,0x94,
0x05,0x5f,0xd2,0xbc,0x89,0x90,0x27,0x00,0x9f,0x23,0x73,0x8a,0xbc,0x09,0x94,0x27,
0xd0,0xa0,0x04,0x87,0xc6,0xec,0xb9,0xf4,0x20,0xd1,0xa6,0x28,0x93,0x2a,0x95,0xe9,
0x14,0xea,0x4e,0xa8,0x2b,0x43,0x4e,0xad,0x59,0x95,0xea,0xcf,0xab,0x5e,0xa3,0x52,
0xf4,0xe8,0xb3,0x2c,0x58,0xae,0x59,0xc7,0x76,0x34,0xeb,0xd5,0x28,0x56,0x9c,0x6a,
0x31,0xb2,0x45,0x3b,0x57,0xac,0x56,0xb2,0x4b,0x8b,0x5a,0x7d,0xeb,0x51,0x28,0x5e,
0xb0,0x36,0xb1,0x1e,0xed,0x18,0x91,0xe4,0xce,0x99,0x82,0x07,0x5f,0x74,0xc9,0xb2,
0xf1,0x47,0xc6,0x8e,0x23,0x97,0xd4,0x28,0xb9,0x32,0x44,0x90,0x01,0x2c,0x47,0xc6,
0x2c,0x55,0x33,0x5c,0xce,0x7e,0x3d,0x3f,0xd6,0x18,0x10,0x00,0x3b};
unsigned char go_button[] = {
0x47,0x49,0x46,0x38,0x39,0x61,0x46,0x00,0x18,0x00,0xf7,0x00,0x00,0x00,0x00,0x84,
0x40,0x40,0x40,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x21,0xf9,0x04,
0x01,0x00,0x00,0x01,0x00,0x2c,0x00,0x00,0x00,0x00,0x46,0x00,0x18,0x00,0x00,0x08,
0xc0,0x00,0x03,0x08,0x1c,0x48,0x50,0x20,0x80,0x83,0x08,0x13,0x2a,0x5c,0xc8,0xb0,
0xa1,0xc3,0x83,0x05,0x23,0x4a,0x34,0xf8,0xb0,0xa2,0xc5,0x8b,0x0b,0x27,0x4a,0xc4,
0xc8,0xb1,0xa3,0x45,0x8d,0x03,0x3d,0x8a,0x1c,0xa9,0x10,0x24,0xc9,0x93,0x24,0x27,
0x8e,0x14,0xc0,0xb2,0xa5,0xc7,0x96,0x02,0x3c,0x6e,0xec,0x08,0xb3,0x26,0x4d,0x97,
0x1d,0x23,0x8a,0x84,0x09,0xc0,0x26,0x46,0x9e,0x32,0x09,0xbe,0xc4,0xd9,0x93,0xe5,
0xc2,0x9a,0x31,0x11,0x02,0xcd,0x29,0xf4,0xa6,0xd1,0x87,0x48,0x9f,0x16,0x95,0xca,
0xb1,0xa9,0xd3,0x98,0x48,0x95,0x46,0x7d,0xba,0x94,0x69,0x80,0x9d,0x2e,0xb3,0x1e,
0x04,0x4a,0x96,0xa8,0x57,0xb0,0x52,0x97,0x96,0xe5,0x6a,0xb6,0x2a,0xc5,0xab,0x5a,
0xd3,0xe2,0xec,0x7a,0xd2,0x2a,0x47,0x9e,0x3e,0xa7,0x46,0x1d,0xdb,0xf6,0x62,0x41,
0xb4,0x7b,0xe3,0xe6,0xa5,0xeb,0xd7,0xee,0x55,0xaa,0x82,0xa9,0x12,0xfe,0xf8,0x17,
0xa5,0xe3,0xa0,0x8d,0x1f,0x4b,0x66,0xac,0x73,0xb2,0x65,0x86,0x26,0x2f,0x6b,0x06,
0x00,0xf2,0xed,0xe6,0xc7,0x9d,0x0d,0x7f,0x86,0x1c,0x3a,0xf2,0x68,0xca,0x13,0x03,
0x02,0x00,0x3b};
unsigned char deutschland_logo[] = {
0xff,0xd8,0xff,0xe0,0x00,0x10,0x4a,0x46,0x49,0x46,0x00,0x01,0x01,0x01,0x00,0x48,
0x00,0x48,0x00,0x00,0xff,0xdb,0x00,0x43,0x00,0x05,0x03,0x04,0x04,0x04,0x03,0x05,
0x04,0x04,0x04,0x05,0x05,0x05,0x06,0x07,0x0c,0x08,0x07,0x07,0x07,0x07,0x0f,0x0b,
0x0b,0x09,0x0c,0x11,0x0f,0x12,0x12,0x11,0x0f,0x11,0x11,0x13,0x16,0x1c,0x17,0x13,
0x14,0x1a,0x15,0x11,0x11,0x18,0x21,0x18,0x1a,0x1d,0x1d,0x1f,0x1f,0x1f,0x13,0x17,
0x22,0x24,0x22,0x1e,0x24,0x1c,0x1e,0x1f,0x1e,0xff,0xdb,0x00,0x43,0x01,0x05,0x05,
0x05,0x07,0x06,0x07,0x0e,0x08,0x08,0x0e,0x1e,0x14,0x11,0x14,0x1e,0x1e,0x1e,0x1e,
0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,
0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,
0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0xff,0xc0,
0x00,0x11,0x08,0x00,0x1a,0x00,0x28,0x03,0x01,0x22,0x00,0x02,0x11,0x01,0x03,0x11,
0x01,0xff,0xc4,0x00,0x17,0x00,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x06,0x07,0x08,0xff,0xc4,0x00,0x21,0x10,0x00,
0x01,0x02,0x04,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x01,0x04,0x02,0x05,0x55,0xd1,0x06,0x12,0x15,0x16,0x51,0x91,0x93,0xff,0xc4,0x00,
0x17,0x01,0x01,0x00,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x05,0x07,0x08,0xff,0xc4,0x00,0x1e,0x11,0x00,0x01,0x04,0x02,0x03,
0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x04,0x53,0x91,
0x02,0x14,0x03,0x15,0x17,0x52,0xff,0xda,0x00,0x0c,0x03,0x01,0x00,0x02,0x11,0x03,
0x11,0x00,0x3f,0x00,0xe3,0x3c,0xab,0xc0,0xca,0xbc,0x1b,0xe6,0x8f,0x29,0xa5,0xb2,
0xf0,0x86,0xc3,0x47,0x94,0xd2,0xd9,0x78,0x43,0x62,0x0f,0xbc,0xe3,0xf9,0x2a,0xc4,
0xf3,0xc7,0x13,0x63,0x45,0x60,0x79,0x57,0x81,0x95,0x78,0x37,0xcd,0x1e,0x53,0x4b,
0x65,0xe1,0x0d,0x86,0x8f,0x29,0xa5,0xb2,0xf0,0x86,0xc3,0xbc,0xe3,0xf9,0x29,0xe7,
0x8e,0x26,0xc6,0x8a,0xc0,0xf2,0xaf,0x00,0xdf,0x34,0x79,0x4d,0x2d,0x97,0x84,0x36,
0x03,0xbc,0xe3,0xf9,0x29,0xe7,0x8e,0x26,0xc6,0x8a,0xe9,0x2d,0x97,0x85,0xa8,0x8d,
0x7a,0x5b,0x8d,0x97,0x85,0xa8,0x8d,0x7a,0x5b,0x94,0x00,0xcf,0x9b,0xee,0xa4,0xca,
0xca,0x6e,0x38,0x90,0xd9,0x53,0xfb,0x2f,0x0b,0x51,0x1a,0xf4,0xb7,0x1b,0x2f,0x0b,
0x51,0x1a,0xf4,0xb7,0x28,0x00,0xdf,0x75,0x26,0x56,0x53,0x71,0xc4,0x86,0xca,0x9f,
0xd9,0x78,0x5a,0x88,0xd7,0xa5,0xb8,0x28,0x00,0xdf,0x75,0x26,0x56,0x53,0x71,0xc4,
0x86,0xca,0xff,0xd9};
unsigned char england_logo[] = {
0xff,0xd8,0xff,0xe0,0x00,0x10,0x4a,0x46,0x49,0x46,0x00,0x01,0x01,0x01,0x00,0x48,
0x00,0x48,0x00,0x00,0xff,0xdb,0x00,0x43,0x00,0x05,0x03,0x04,0x04,0x04,0x03,0x05,
0x04,0x04,0x04,0x05,0x05,0x05,0x06,0x07,0x0c,0x08,0x07,0x07,0x07,0x07,0x0f,0x0b,
0x0b,0x09,0x0c,0x11,0x0f,0x12,0x12,0x11,0x0f,0x11,0x11,0x13,0x16,0x1c,0x17,0x13,
0x14,0x1a,0x15,0x11,0x11,0x18,0x21,0x18,0x1a,0x1d,0x1d,0x1f,0x1f,0x1f,0x13,0x17,
0x22,0x24,0x22,0x1e,0x24,0x1c,0x1e,0x1f,0x1e,0xff,0xdb,0x00,0x43,0x01,0x05,0x05,
0x05,0x07,0x06,0x07,0x0e,0x08,0x08,0x0e,0x1e,0x14,0x11,0x14,0x1e,0x1e,0x1e,0x1e,
0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,
0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,
0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0xff,0xc0,
0x00,0x11,0x08,0x00,0x1a,0x00,0x28,0x03,0x01,0x22,0x00,0x02,0x11,0x01,0x03,0x11,
0x01,0xff,0xc4,0x00,0x1a,0x00,0x00,0x03,0x01,0x00,0x03,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x05,0x06,0x08,0x01,0x04,0x07,0xff,0xc4,0x00,
0x34,0x10,0x00,0x01,0x03,0x03,0x03,0x02,0x04,0x03,0x05,0x09,0x00,0x00,0x00,0x00,
0x00,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x11,0x00,0x07,0x21,0x12,0x31,0x13,0x41,
0x51,0x61,0x23,0x32,0x52,0x08,0x14,0x15,0x16,0x92,0x34,0x37,0x62,0x63,0x73,0x76,
0xb5,0xd1,0xf0,0xff,0xc4,0x00,0x17,0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x06,0x05,0x03,0xff,0xc4,0x00,0x2a,
0x11,0x00,0x01,0x03,0x03,0x03,0x03,0x03,0x04,0x03,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x00,0x06,0x31,0x12,0x51,0x61,0x13,0x41,
0x71,0x14,0x23,0x24,0x42,0x81,0x91,0xf0,0xff,0xda,0x00,0x0c,0x03,0x01,0x00,0x02,
0x11,0x03,0x11,0x00,0x3f,0x00,0x69,0x62,0x6e,0x3d,0x3e,0xe1,0xa3,0x9b,0x76,0xa9,
0x0b,0xf3,0x15,0x2d,0x60,0x07,0x28,0xb3,0x96,0x15,0x31,0x8f,0x78,0xce,0xf1,0xe3,
0x01,0xe4,0x9e,0x16,0x3c,0xbb,0x13,0xa9,0x8b,0xdb,0x66,0x11,0x32,0x9c,0xed,0xc9,
0xb6,0x13,0x97,0x5e,0xa5,0xa4,0xe5,0xea,0x7a,0xbf,0x6c,0x8a,0x7e,0x92,0x9e,0xeb,
0xc7,0xa6,0x02,0xbd,0x95,0xdf,0x5d,0xc4,0xdd,0xf7,0x12,0x56,0x82,0x2c,0xdb,0x75,
0x2a,0xef,0x91,0x6e,0xb3,0x90,0x7f,0x46,0x99,0x47,0xdd,0x0d,0xc1,0x8f,0x2d,0xe9,
0xd1,0xa9,0x30,0x1a,0x96,0xef,0x0e,0x3c,0x8a,0x3a,0x42,0xdc,0x1e,0xea,0x09,0xc9,
0xd7,0x3a,0x7d,0xcc,0xdd,0x13,0xdd,0x54,0x61,0x41,0x07,0x94,0xa8,0x48,0xfe,0x0e,
0xab,0x6a,0x76,0x55,0x5d,0x73,0x5f,0x94,0x5b,0xf5,0x07,0xec,0x95,0x01,0x3f,0x22,
0x22,0x7c,0x88,0xf3,0x3c,0xeb,0x8a,0x8b,0x2e,0xab,0x76,0xa5,0x47,0x0d,0x2c,0xbe,
0x6d,0xc5,0xa0,0x36,0x12,0x7a,0xba,0xbf,0x06,0xc6,0x31,0xdf,0x39,0xe3,0x1a,0x89,
0xb0,0xf6,0xb2,0x74,0xfa,0x9b,0x71,0xea,0x30,0xdf,0x99,0x3c,0xe1,0x42,0x93,0x19,
0x61,0x2a,0x6c,0x7d,0x52,0x5d,0xec,0xca,0x7f,0x87,0x95,0x9e,0xd8,0x4f,0x07,0x4d,
0x0d,0xdf,0x73,0xab,0x71,0x4d,0xd8,0xa6,0xd0,0xaa,0xe1,0xee,0x93,0x1b,0x83,0xf0,
0x7c,0x3f,0x93,0x1f,0x47,0xfb,0xd5,0x1d,0x3f,0x74,0x37,0x06,0x9e,0xc2,0x9a,0xa7,
0xd2,0x60,0xc3,0x6d,0xc5,0x65,0x68,0x62,0x90,0x94,0x05,0x1f,0x52,0x02,0x79,0xd0,
0xa8,0x37,0x1a,0xe8,0xdb,0x79,0x0d,0x4a,0x7a,0xd4,0x4c,0xc4,0x91,0xe0,0x76,0x3a,
0xd6,0xba,0x6d,0x05,0xd5,0x2e,0x9d,0x6e,0x74,0xab,0xd3,0x6d,0x29,0x82,0xa8,0x04,
0x89,0xc9,0xc4,0x91,0xfd,0x4f,0x7d,0x34,0xb8,0xab,0x76,0x46,0xd7,0x21,0xb6,0x6a,
0xa2,0x1d,0xcb,0x71,0xc5,0xcf,0xdd,0x68,0xf0,0xc7,0x44,0x0a,0x6a,0x8f,0x9a,0x87,
0x39,0x57,0xaa,0x95,0x95,0x9c,0x0c,0xe3,0xbe,0x8d,0x4c,0xaa,0xee,0xb8,0x54,0xb5,
0x13,0x66,0xdb,0xa4,0x93,0x92,0x4d,0xba,0xc9,0x24,0xfe,0x8d,0x1a,0x7d,0x35,0xee,
0xce,0xda,0x21,0xc6,0x14,0xa5,0x7b,0x93,0xc9,0x3a,0xc5,0xa9,0xda,0x57,0xe7,0x95,
0x21,0xf6,0xd2,0x06,0x00,0x04,0x00,0x07,0x60,0x23,0x57,0x76,0x7c,0x4b,0xda,0xdd,
0x8b,0x1a,0xb9,0xba,0x77,0xf5,0x71,0xa5,0xbc,0x41,0x87,0x40,0x88,0xf9,0x54,0xa9,
0x2a,0xf2,0x4a,0xba,0x79,0x19,0xe3,0x81,0xeb,0xca,0x87,0x6d,0x26,0xdc,0xbd,0xf0,
0xa9,0x45,0xa8,0xe1,0x12,0x8c,0x77,0x5a,0x3f,0x0a,0x93,0x06,0x47,0xc8,0x7d,0x64,
0xbe,0x9f,0x3f,0xe5,0xa3,0x9f,0x22,0x52,0x46,0x91,0x5e,0x93,0x26,0x2a,0xdf,0xbf,
0xea,0xaa,0x94,0xf9,0x9e,0xdc,0xf6,0x98,0x44,0xa2,0xe1,0xf1,0x52,0xd1,0x52,0xc1,
0x40,0x5f,0x70,0x92,0x00,0x04,0x67,0x18,0xd7,0x82,0x1e,0xff,0x00,0xf7,0xb6,0xa8,
0xac,0xb4,0x69,0xbd,0xad,0x55,0x35,0x18,0x4a,0x49,0x01,0x20,0x40,0xc7,0x72,0x39,
0xff,0x00,0x4c,0xea,0x5e,0xec,0xe0,0xb1,0x04,0xd3,0xb0,0x3a,0x96,0xa4,0x82,0x56,
0xac,0x9c,0x8e,0x00,0xe0,0x7c,0xe7,0xc4,0x6b,0x4a,0x4d,0xac,0x4c,0x6b,0x7d,0x9f,
0xb8,0x52,0x5b,0x33,0x5b,0xa3,0x2a,0x6a,0x72,0x9c,0xa7,0xc4,0x14,0x9e,0xbe,0xde,
0x99,0xf2,0xd5,0x0d,0xa3,0xbb,0xb0,0xb7,0x1d,0xb8,0xb1,0x51,0x70,0x3d,0x67,0x5d,
0x8d,0x0e,0x96,0x9b,0x5b,0xbd,0x70,0x66,0x1f,0xa7,0x0a,0xe0,0x67,0xd0,0xe1,0x43,
0x3c,0x15,0x63,0x88,0xda,0x97,0xef,0x4a,0x5f,0xf6,0xd2,0xff,0x00,0xc2,0x9d,0x67,
0xd4,0xf7,0x1a,0x16,0xdd,0xb4,0xb1,0x5e,0xd5,0x52,0x17,0x82,0x16,0x60,0x8f,0x6d,
0x3f,0x74,0x5c,0x1d,0xa3,0x76,0x89,0x68,0xcf,0xd9,0x46,0x0e,0x41,0xe7,0xbe,0xb4,
0x8e,0xe1,0xbb,0xbb,0x14,0xda,0x92,0x98,0x8b,0x74,0x56,0x29,0x95,0x05,0x64,0xa2,
0x03,0xb2,0xca,0x98,0x91,0xef,0x19,0xe5,0x70,0xaf,0xe9,0xac,0x85,0x0e,0x06,0x54,
0x4e,0x34,0x6a,0xdf,0x6a,0xd4,0x6b,0x5f,0x65,0xb7,0x57,0x59,0x26,0xa4,0xa6,0xd8,
0x91,0xd0,0xa9,0x67,0xc5,0x29,0xe9,0x27,0xa7,0x1d,0x59,0xc6,0x3c,0xbd,0x34,0x68,
0x6e,0xdf,0xdc,0xb6,0x28,0xd3,0xa9,0xb4,0xb9,0x1e,0xe4,0x41,0x8f,0x31,0xa7,0x5b,
0x36,0xc5,0x3d,0xf1,0xaf,0xaa,0x42,0xcb,0x5d,0xc0,0xc8,0x9e,0xe2,0x78,0xf8,0xce,
0xbf,0xff,0xd9};
unsigned char back_button[] = {
0x47,0x49,0x46,0x38,0x39,0x61,0x46,0x00,0x18,0x00,0xf7,0x00,0x00,0x00,0x00,0x84,
0x40,0x40,0x40,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x21,0xf9,0x04,
0x01,0x00,0x00,0x01,0x00,0x2c,0x00,0x00,0x00,0x00,0x46,0x00,0x18,0x00,0x00,0x08,
0xdb,0x00,0x03,0x08,0x1c,0x48,0x50,0x20,0x80,0x83,0x08,0x13,0x2a,0x5c,0xc8,0xb0,
0xa1,0xc3,0x83,0x05,0x23,0x4a,0x34,0xf8,0xb0,0xa2,0xc5,0x8b,0x0b,0x27,0x4a,0xc4,
0xc8,0xb1,0xa3,0x45,0x8d,0x03,0x3d,0x8a,0x1c,0xa9,0x10,0x24,0xc9,0x93,0x24,0x27,
0x36,0x14,0xc0,0xb2,0xa5,0x00,0x94,0x2b,0x5b,0x62,0xdc,0xc8,0xd0,0xa5,0x4b,0x98,
0x0b,0x6f,0x5e,0x8c,0xe8,0xf0,0xa6,0x4e,0x9c,0x07,0x7f,0x7e,0x24,0xd8,0x53,0xa6,
0xd0,0xa0,0x36,0x5f,0x26,0x4c,0xba,0xd4,0xe8,0xd1,0x84,0x05,0x8b,0xb2,0x04,0x20,
0x53,0x61,0xd2,0xaa,0x54,0xaf,0x22,0xbc,0x3a,0xd5,0x21,0x51,0xa9,0x4f,0x75,0x8a,
0xf5,0x59,0x95,0xeb,0xd0,0x00,0x0f,0xb9,0x2a,0xcd,0x69,0x13,0x69,0x57,0xb6,0x4c,
0x2b,0x86,0x04,0xeb,0x76,0x6d,0x56,0xad,0x77,0xed,0x36,0x8d,0xfb,0x70,0x6e,0xcc,
0xae,0x3f,0xdb,0x8e,0x7d,0x6b,0xd5,0x6c,0x5f,0xbf,0x70,0x95,0x06,0x2e,0xcb,0xd8,
0x29,0x60,0xc7,0x84,0x4b,0x7e,0xad,0x69,0xb8,0x2e,0xdf,0xca,0x83,0xf5,0x42,0x9d,
0x9c,0xb8,0xed,0x5e,0xbe,0x79,0x09,0x67,0xd6,0x0c,0x31,0x2a,0xd0,0xd3,0x72,0x79,
0xa2,0x5e,0xcd,0x50,0x25,0xeb,0xd7,0x00,0x4c,0xc2,0x46,0x0d,0x92,0xe2,0x6c,0x98,
0xb5,0x39,0xdf,0xee,0x98,0xdb,0xf5,0xee,0xd4,0x1a,0x03,0x02,0x00,0x3b};
char irtrans_usage[] = {
0x55,0x73,0x61,0x67,0x65,0x3a,0x20,0x69,0x72,0x73,0x65,0x72,0x76,0x65,0x72,0x20,
0x5b,0x6f,0x70,0x74,0x69,0x6f,0x6e,0x73,0x5d,0x20,0x3c,0x64,0x65,0x76,0x69,0x63,
0x65,0x3e,0x0d,0x0a,0x0d,0x0a,0x54,0x68,0x65,0x20,0x6c,0x61,0x73,0x74,0x20,0x61,
0x72,0x67,0x75,0x6d,0x65,0x6e,0x74,0x20,0x66,0x6f,0x72,0x20,0x74,0x68,0x65,0x20,
0x69,0x72,0x73,0x65,0x72,0x76,0x65,0x72,0x20,0x69,0x73,0x20,0x61,0x6c,0x77,0x61,
0x79,0x73,0x20,0x74,0x68,0x65,0x20,0x64,0x65,0x76,0x69,0x63,0x65,0x3a,0x0d,0x0a,
0x57,0x69,0x6e,0x64,0x6f,0x77,0x73,0x20,0x44,0x65,0x76,0x69,0x63,0x65,0x73,0x3a,
0x20,0x43,0x4f,0x4d,0x31,0x20,0x2d,0x20,0x43,0x4f,0x4d,0x6e,0x20,0x6f,0x72,0x20,
0x55,0x53,0x42,0x20,0x66,0x6f,0x72,0x20,0x55,0x53,0x42,0x20,0x64,0x65,0x76,0x69,
0x63,0x65,0x73,0x0d,0x0a,0x0d,0x0a,0x4c,0x49,0x4e,0x55,0x58,0x20,0x44,0x65,0x76,
0x69,0x63,0x65,0x73,0x3a,0x20,0x2f,0x64,0x65,0x76,0x2f,0x74,0x74,0x79,0x53,0x30,
0x20,0x2d,0x20,0x2f,0x64,0x65,0x76,0x2f,0x74,0x74,0x79,0x53,0x6e,0x20,0x6f,0x72,
0x20,0x2f,0x64,0x65,0x76,0x2f,0x74,0x74,0x79,0x55,0x53,0x42,0x30,0x20,0x2d,0x20,
0x2f,0x64,0x65,0x76,0x2f,0x74,0x74,0x79,0x55,0x53,0x42,0x6e,0x20,0x66,0x6f,0x72,
0x20,0x55,0x53,0x42,0x20,0x64,0x65,0x76,0x69,0x63,0x65,0x73,0x0d,0x0a,0x2d,0x2d,
0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,
0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,
0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,
0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,
0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,
0x2d,0x2d,0x2d,0x0d,0x0a,0x0d,0x0a,0x44,0x65,0x73,0x63,0x72,0x69,0x70,0x74,0x69,
0x6f,0x6e,0x20,0x6f,0x66,0x20,0x74,0x68,0x65,0x20,0x6f,0x70,0x74,0x69,0x6f,0x6e,
0x73,0x3a,0x0d,0x0a,0x0d,0x0a,0x2d,0x62,0x61,0x75,0x64,0x72,0x61,0x74,0x65,0x20,
0x3c,0x62,0x64,0x3e,0x20,0x20,0x54,0x68,0x65,0x20,0x62,0x61,0x75,0x64,0x72,0x61,
0x74,0x65,0x20,0x74,0x6f,0x20,0x62,0x65,0x20,0x75,0x73,0x65,0x64,0x20,0x77,0x68,
0x65,0x6e,0x20,0x63,0x6f,0x6d,0x6d,0x75,0x6e,0x69,0x63,0x61,0x74,0x69,0x6e,0x67,
0x20,0x77,0x69,0x74,0x68,0x20,0x52,0x53,0x32,0x33,0x32,0x20,0x64,0x65,0x76,0x69,
0x63,0x65,0x73,0x2e,0x0d,0x0a,0x0d,0x0a,0x2d,0x6e,0x6f,0x5f,0x72,0x65,0x63,0x6f,
0x6e,0x6e,0x65,0x63,0x74,0x20,0x20,0x20,0x54,0x68,0x65,0x20,0x73,0x65,0x72,0x76,
0x65,0x72,0x20,0x77,0x69,0x6c,0x6c,0x20,0x6e,0x6f,0x74,0x20,0x74,0x72,0x79,0x20,
0x74,0x6f,0x20,0x72,0x65,0x63,0x6f,0x6e,0x6e,0x65,0x63,0x74,0x20,0x74,0x6f,0x20,
0x61,0x20,0x64,0x65,0x76,0x69,0x63,0x65,0x20,0x6f,0x6e,0x63,0x65,0x20,0x69,0x74,
0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x77,0x61,0x73,0x20,0x72,0x65,0x6d,0x6f,0x76,0x65,0x64,0x2e,0x20,0x53,
0x74,0x61,0x6e,0x64,0x61,0x72,0x64,0x20,0x69,0x73,0x20,0x74,0x68,0x61,0x74,0x20,
0x74,0x68,0x65,0x20,0x73,0x65,0x72,0x76,0x65,0x72,0x20,0x74,0x72,0x69,0x65,0x73,
0x20,0x74,0x6f,0x20,0x72,0x65,0x63,0x6f,0x6e,0x6e,0x65,0x63,0x74,0x0d,0x0a,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x77,
0x68,0x65,0x6e,0x20,0x74,0x68,0x65,0x20,0x64,0x65,0x76,0x69,0x63,0x65,0x20,0x77,
0x61,0x73,0x20,0x72,0x65,0x6d,0x6f,0x76,0x65,0x64,0x20,0x77,0x68,0x65,0x6e,0x20,
0x74,0x68,0x65,0x20,0x73,0x65,0x72,0x76,0x65,0x72,0x20,0x77,0x61,0x73,0x20,0x72,
0x75,0x6e,0x6e,0x69,0x6e,0x67,0x2e,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x28,0x55,0x53,0x42,0x20,0x6f,0x6e,
0x6c,0x79,0x29,0x0d,0x0a,0x0d,0x0a,0x2d,0x6e,0x6f,0x5f,0x6c,0x69,0x72,0x63,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x54,0x68,0x65,0x20,0x4c,0x49,0x52,0x43,0x20,
0x63,0x6f,0x6d,0x70,0x61,0x74,0x69,0x62,0x6c,0x65,0x20,0x53,0x65,0x72,0x76,0x65,
0x72,0x20,0x73,0x6f,0x63,0x6b,0x65,0x74,0x20,0x69,0x73,0x74,0x20,0x6e,0x6f,0x74,
0x20,0x73,0x74,0x61,0x72,0x74,0x65,0x64,0x2e,0x20,0x54,0x68,0x61,0x74,0x0d,0x0a,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x61,0x6c,0x6c,0x6f,0x77,0x73,0x20,0x74,0x6f,0x20,0x72,0x75,0x6e,0x20,0x4c,0x49,
0x52,0x43,0x20,0x6f,0x6e,0x20,0x74,0x68,0x65,0x20,0x73,0x61,0x6d,0x65,0x20,0x50,
0x43,0x2e,0x0d,0x0a,0x0d,0x0a,0x2d,0x64,0x65,0x62,0x75,0x67,0x5f,0x63,0x6f,0x64,
0x65,0x20,0x20,0x20,0x20,0x20,0x41,0x6c,0x6c,0x20,0x72,0x65,0x63,0x65,0x69,0x76,
0x65,0x64,0x20,0x49,0x52,0x20,0x63,0x6f,0x64,0x65,0x73,0x20,0x61,0x72,0x65,0x20,
0x70,0x72,0x69,0x6e,0x74,0x65,0x64,0x20,0x6f,0x6e,0x20,0x74,0x68,0x65,0x20,0x63,
0x6f,0x6e,0x73,0x6f,0x6c,0x65,0x2e,0x20,0x57,0x68,0x65,0x6e,0x20,0x74,0x68,0x65,
0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x63,0x6f,0x64,0x65,0x20,0x69,0x73,0x20,0x66,0x6f,0x75,0x6e,0x64,0x20,
0x69,0x6e,0x20,0x74,0x68,0x65,0x20,0x64,0x61,0x74,0x61,0x62,0x61,0x73,0x65,0x20,
0x74,0x68,0x65,0x20,0x52,0x65,0x6d,0x6f,0x74,0x65,0x2f,0x43,0x6f,0x6d,0x6d,0x61,
0x6e,0x64,0x20,0x69,0x73,0x20,0x70,0x72,0x69,0x6e,0x74,0x65,0x64,0x2c,0x0d,0x0a,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x74,0x6f,0x6f,0x2e,0x20,0x54,0x68,0x65,0x20,0x6c,0x6f,0x67,0x6c,0x65,0x76,0x65,
0x6c,0x20,0x34,0x20,0x68,0x61,0x73,0x20,0x74,0x6f,0x20,0x62,0x65,0x20,0x75,0x73,
0x65,0x64,0x20,0x74,0x6f,0x20,0x61,0x63,0x74,0x69,0x76,0x61,0x74,0x65,0x64,0x20,
0x74,0x68,0x61,0x74,0x20,0x6f,0x75,0x74,0x70,0x75,0x74,0x2e,0x0d,0x0a,0x0d,0x0a,
0x2d,0x74,0x69,0x6d,0x65,0x73,0x74,0x61,0x6d,0x70,0x20,0x20,0x20,0x20,0x20,0x20,
0x41,0x64,0x64,0x20,0x61,0x20,0x74,0x69,0x6d,0x65,0x73,0x74,0x61,0x6d,0x70,0x20,
0x74,0x6f,0x20,0x65,0x76,0x65,0x72,0x79,0x20,0x6c,0x6f,0x67,0x20,0x6d,0x65,0x73,
0x73,0x61,0x67,0x65,0x2e,0x0d,0x0a,0x0d,0x0a,0x2d,0x6d,0x65,0x64,0x69,0x61,0x6c,
0x6f,0x6e,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x4d,0x61,0x6b,0x65,0x20,0x61,0x20,
0x68,0x65,0x78,0x64,0x75,0x6d,0x70,0x20,0x6f,0x66,0x20,0x73,0x65,0x6e,0x74,0x20,
0x63,0x6f,0x6d,0x6d,0x61,0x6e,0x64,0x73,0x20,0x69,0x6e,0x20,0x61,0x20,0x66,0x6f,
0x72,0x6d,0x61,0x74,0x20,0x66,0x6f,0x72,0x20,0x74,0x68,0x65,0x20,0x4d,0x65,0x64,
0x69,0x61,0x6c,0x6f,0x6e,0x20,0x53,0x57,0x2e,0x0d,0x0a,0x0d,0x0a,0x2d,0x68,0x65,
0x78,0x64,0x75,0x6d,0x70,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x54,0x68,0x65,
0x20,0x73,0x65,0x72,0x76,0x65,0x72,0x20,0x70,0x72,0x69,0x6e,0x74,0x73,0x20,0x74,
0x68,0x65,0x20,0x63,0x6f,0x6d,0x70,0x6c,0x65,0x74,0x65,0x20,0x63,0x6f,0x6d,0x6d,
0x75,0x6e,0x69,0x63,0x61,0x74,0x69,0x6f,0x6e,0x20,0x62,0x65,0x74,0x77,0x65,0x65,
0x6e,0x20,0x63,0x6c,0x69,0x65,0x6e,0x74,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x61,0x6e,0x64,0x20,0x73,0x65,
0x72,0x76,0x65,0x72,0x2e,0x20,0x54,0x68,0x69,0x73,0x20,0x63,0x61,0x6e,0x20,0x62,
0x65,0x20,0x75,0x73,0x65,0x64,0x20,0x74,0x6f,0x20,0x64,0x65,0x62,0x75,0x67,0x20,
0x63,0x6f,0x64,0x65,0x73,0x20,0x6f,0x72,0x20,0x74,0x6f,0x20,0x72,0x65,0x63,0x6f,
0x72,0x64,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x74,0x68,0x65,0x20,0x63,0x6f,0x6d,0x6d,0x75,0x6e,0x69,0x63,
0x61,0x74,0x69,0x6f,0x6e,0x20,0x74,0x6f,0x20,0x75,0x73,0x65,0x20,0x74,0x68,0x65,
0x20,0x49,0x52,0x54,0x72,0x61,0x6e,0x73,0x20,0x77,0x69,0x74,0x68,0x20,0x6f,0x74,
0x68,0x65,0x72,0x20,0x73,0x79,0x73,0x74,0x65,0x6d,0x73,0x2e,0x0d,0x0a,0x09,0x09,
0x09,0x20,0x20,0x20,0x0d,0x0a,0x2d,0x78,0x61,0x70,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x53,0x74,0x61,0x72,0x74,0x20,0x74,0x68,0x65,0x20,
0x69,0x6e,0x74,0x65,0x67,0x72,0x61,0x74,0x65,0x64,0x20,0x78,0x61,0x70,0x20,0x69,
0x6e,0x74,0x65,0x72,0x66,0x61,0x63,0x65,0x2e,0x0d,0x0a,0x0d,0x0a,0x2d,0x69,0x70,
0x5f,0x72,0x65,0x6c,0x61,0x79,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x52,0x65,0x6c,
0x61,0x79,0x20,0x49,0x52,0x20,0x43,0x6f,0x64,0x65,0x73,0x20,0x72,0x65,0x63,0x65,
0x69,0x76,0x65,0x64,0x20,0x66,0x72,0x6f,0x6d,0x20,0x61,0x6e,0x20,0x45,0x74,0x68,
0x65,0x72,0x6e,0x65,0x74,0x20,0x6d,0x6f,0x64,0x75,0x6c,0x65,0x20,0x74,0x6f,0x20,
0x63,0x6f,0x6e,0x6e,0x65,0x63,0x74,0x65,0x64,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x55,0x53,0x42,0x2c,0x20,
0x52,0x53,0x32,0x33,0x32,0x20,0x6f,0x72,0x20,0x62,0x75,0x73,0x20,0x6d,0x6f,0x64,
0x75,0x6c,0x65,0x73,0x2e,0x0d,0x0a,0x0d,0x0a,0x2d,0x68,0x65,0x78,0x66,0x69,0x6c,
0x65,0x20,0x3c,0x66,0x69,0x6c,0x65,0x3e,0x20,0x54,0x68,0x65,0x20,0x73,0x65,0x72,
0x76,0x65,0x72,0x20,0x70,0x72,0x69,0x6e,0x74,0x73,0x20,0x74,0x68,0x65,0x20,0x63,
0x6f,0x6d,0x70,0x6c,0x65,0x74,0x65,0x20,0x63,0x6f,0x6d,0x6d,0x75,0x6e,0x69,0x63,
0x61,0x74,0x69,0x6f,0x6e,0x20,0x62,0x65,0x74,0x77,0x65,0x65,0x6e,0x20,0x63,0x6c,
0x69,0x65,0x6e,0x74,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x61,0x6e,0x64,0x20,0x73,0x65,0x72,0x76,0x65,0x72,
0x20,0x69,0x6e,0x74,0x6f,0x20,0x3c,0x66,0x69,0x6c,0x65,0x3e,0x2e,0x20,0x54,0x68,
0x69,0x73,0x20,0x63,0x61,0x6e,0x20,0x62,0x65,0x20,0x75,0x73,0x65,0x64,0x20,0x74,
0x6f,0x20,0x72,0x65,0x63,0x6f,0x72,0x64,0x20,0x74,0x68,0x65,0x20,0x0d,0x0a,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x63,
0x6f,0x6d,0x6d,0x75,0x6e,0x69,0x63,0x61,0x74,0x69,0x6f,0x6e,0x20,0x74,0x6f,0x20,
0x75,0x73,0x65,0x20,0x74,0x68,0x65,0x20,0x49,0x52,0x54,0x72,0x61,0x6e,0x73,0x20,
0x77,0x69,0x74,0x68,0x20,0x6f,0x74,0x68,0x65,0x72,0x20,0x73,0x79,0x73,0x74,0x65,
0x6d,0x73,0x2e,0x0d,0x0a,0x0d,0x0a,0x2d,0x63,0x6f,0x64,0x65,0x64,0x75,0x6d,0x70,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x54,0x68,0x65,0x20,0x49,0x52,0x20,0x44,0x61,
0x74,0x61,0x20,0x6f,0x66,0x20,0x61,0x6c,0x6c,0x20,0x63,0x6f,0x6d,0x6d,0x61,0x6e,
0x64,0x20,0x73,0x65,0x6e,0x74,0x20,0x69,0x73,0x20,0x70,0x72,0x69,0x6e,0x74,0x65,
0x64,0x20,0x74,0x6f,0x20,0x74,0x68,0x65,0x20,0x63,0x6f,0x6e,0x73,0x6f,0x6c,0x65,
0x2e,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x54,0x68,0x65,0x20,0x6c,0x6f,0x67,0x6c,0x65,0x76,0x65,0x6c,0x20,
0x34,0x20,0x68,0x61,0x73,0x20,0x74,0x6f,0x20,0x62,0x65,0x20,0x75,0x73,0x65,0x64,
0x20,0x74,0x6f,0x20,0x61,0x63,0x74,0x69,0x76,0x61,0x74,0x65,0x20,0x74,0x68,0x65,
0x20,0x6f,0x75,0x74,0x70,0x75,0x74,0x2e,0x0d,0x0a,0x0d,0x0a,0x2d,0x73,0x74,0x61,
0x74,0x5f,0x74,0x69,0x6d,0x65,0x6f,0x75,0x74,0x09,0x53,0x65,0x74,0x73,0x20,0x74,
0x68,0x65,0x20,0x74,0x69,0x6d,0x65,0x6f,0x75,0x74,0x20,0x28,0x69,0x6e,0x20,0x73,
0x29,0x20,0x61,0x66,0x74,0x65,0x72,0x20,0x74,0x68,0x61,0x74,0x20,0x74,0x68,0x65,
0x20,0x43,0x61,0x63,0x68,0x65,0x20,0x66,0x6f,0x72,0x20,0x74,0x68,0x65,0x20,0x64,
0x65,0x76,0x69,0x63,0x65,0x20,0x73,0x74,0x61,0x74,0x75,0x73,0x0d,0x0a,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x73,
0x20,0x72,0x65,0x72,0x65,0x61,0x64,0x20,0x66,0x72,0x6f,0x6d,0x20,0x74,0x68,0x65,
0x20,0x64,0x65,0x76,0x69,0x63,0x65,0x73,0x2e,0x0d,0x0a,0x0d,0x0a,0x2d,0x6c,0x65,
0x61,0x72,0x6e,0x65,0x64,0x5f,0x6f,0x6e,0x6c,0x79,0x20,0x20,0x20,0x4f,0x6e,0x6c,
0x79,0x20,0x43,0x6f,0x64,0x65,0x73,0x20,0x74,0x68,0x61,0x74,0x20,0x68,0x61,0x76,
0x65,0x20,0x62,0x65,0x65,0x6e,0x20,0x6c,0x65,0x61,0x72,0x6e,0x65,0x64,0x20,0x61,
0x72,0x65,0x20,0x74,0x72,0x61,0x6e,0x73,0x6d,0x69,0x74,0x74,0x65,0x64,0x20,0x74,
0x6f,0x20,0x74,0x68,0x65,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x4e,0x65,0x74,0x77,0x6f,0x72,0x6b,0x20,0x63,
0x6c,0x69,0x65,0x6e,0x74,0x73,0x2e,0x20,0x4e,0x4f,0x54,0x45,0x3a,0x20,0x54,0x68,
0x69,0x73,0x20,0x6f,0x70,0x74,0x69,0x6f,0x6e,0x20,0x77,0x69,0x6c,0x6c,0x20,0x62,
0x65,0x63,0x6f,0x6d,0x65,0x20,0x64,0x65,0x66,0x61,0x75,0x6c,0x74,0x0d,0x0a,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,
0x6e,0x20,0x6c,0x61,0x74,0x65,0x72,0x20,0x76,0x65,0x72,0x73,0x69,0x6f,0x6e,0x73,
0x20,0x6f,0x66,0x20,0x74,0x68,0x65,0x20,0x69,0x72,0x73,0x65,0x72,0x76,0x65,0x72,
0x2e,0x0d,0x0a,0x0d,0x0a,0x2d,0x6c,0x6f,0x67,0x66,0x69,0x6c,0x65,0x20,0x3c,0x66,
0x69,0x6c,0x65,0x3e,0x20,0x52,0x65,0x64,0x69,0x72,0x65,0x63,0x74,0x20,0x74,0x68,
0x65,0x20,0x63,0x6f,0x6e,0x73,0x6f,0x6c,0x65,0x2f,0x6c,0x6f,0x67,0x20,0x6f,0x75,
0x74,0x70,0x75,0x74,0x20,0x74,0x6f,0x20,0x61,0x20,0x73,0x70,0x65,0x63,0x69,0x66,
0x69,0x65,0x64,0x20,0x66,0x69,0x6c,0x65,0x2e,0x0d,0x0a,0x0d,0x0a,0x2d,0x6c,0x6f,
0x67,0x6c,0x65,0x76,0x65,0x6c,0x20,0x3c,0x78,0x3e,0x20,0x20,0x20,0x43,0x6f,0x6e,
0x74,0x72,0x6f,0x6c,0x73,0x20,0x77,0x68,0x69,0x63,0x68,0x20,0x69,0x6e,0x66,0x6f,
0x72,0x6d,0x61,0x74,0x69,0x6f,0x6e,0x20,0x69,0x73,0x20,0x6c,0x6f,0x67,0x67,0x65,
0x64,0x2e,0x20,0x53,0x74,0x61,0x6e,0x64,0x61,0x72,0x64,0x20,0x69,0x73,0x20,0x6c,
0x6f,0x67,0x6c,0x65,0x76,0x65,0x6c,0x20,0x31,0x2e,0x0d,0x0a,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x50,0x6f,0x73,0x73,
0x69,0x62,0x6c,0x65,0x20,0x76,0x61,0x6c,0x75,0x65,0x73,0x20,0x61,0x72,0x65,0x20,
0x30,0x2d,0x34,0x2e,0x20,0x30,0x3d,0x4e,0x6f,0x74,0x68,0x69,0x6e,0x67,0x20,0x69,
0x73,0x20,0x6c,0x6f,0x67,0x67,0x65,0x64,0x2e,0x20,0x34,0x3d,0x64,0x65,0x62,0x75,
0x67,0x20,0x6f,0x75,0x74,0x70,0x75,0x74,0x2e,0x0d,0x0a,0x0d,0x0a,0x2d,0x6e,0x65,
0x74,0x6d,0x61,0x73,0x6b,0x20,0x3c,0x6d,0x61,0x73,0x6b,0x3e,0x20,0x41,0x63,0x63,
0x65,0x73,0x73,0x20,0x63,0x6f,0x6e,0x74,0x72,0x6f,0x6c,0x20,0x66,0x6f,0x72,0x20,
0x6e,0x65,0x74,0x77,0x6f,0x72,0x6b,0x65,0x64,0x20,0x63,0x6c,0x69,0x65,0x6e,0x74,
0x73,0x2e,0x20,0x57,0x68,0x65,0x6e,0x20,0x74,0x68,0x69,0x73,0x20,0x6f,0x70,0x74,
0x69,0x6f,0x6e,0x20,0x69,0x73,0x20,0x75,0x73,0x65,0x64,0x0d,0x0a,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x61,0x74,0x20,
0x6c,0x65,0x61,0x73,0x74,0x20,0x6f,0x6e,0x63,0x65,0x2c,0x20,0x6f,0x6e,0x6c,0x79,
0x20,0x63,0x6c,0x69,0x65,0x6e,0x74,0x73,0x20,0x77,0x69,0x74,0x68,0x69,0x6e,0x20,
0x74,0x68,0x65,0x20,0x73,0x70,0x65,0x63,0x69,0x66,0x69,0x65,0x64,0x20,0x6e,0x65,
0x74,0x6d,0x61,0x73,0x6b,0x20,0x61,0x72,0x65,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x61,0x6c,0x6c,0x6f,0x77,
0x65,0x64,0x20,0x74,0x6f,0x20,0x61,0x63,0x63,0x65,0x73,0x73,0x20,0x74,0x68,0x65,
0x20,0x53,0x65,0x72,0x76,0x65,0x72,0x2e,0x20,0x54,0x68,0x65,0x20,0x66,0x6f,0x72,
0x6d,0x61,0x74,0x20,0x69,0x73,0x20,0x69,0x70,0x2f,0x62,0x69,0x74,0x73,0x2e,0x20,
0x54,0x68,0x61,0x74,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x6d,0x65,0x61,0x6e,0x73,0x20,0x31,0x39,0x32,0x2e,
0x31,0x36,0x38,0x2e,0x31,0x32,0x2e,0x30,0x2f,0x32,0x34,0x20,0x64,0x65,0x66,0x69,
0x6e,0x65,0x73,0x20,0x61,0x20,0x73,0x74,0x61,0x6e,0x64,0x61,0x72,0x64,0x20,0x63,
0x6c,0x61,0x73,0x73,0x20,0x43,0x20,0x6e,0x65,0x74,0x77,0x6f,0x72,0x6b,0x2e,0x0d,
0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x54,0x68,0x69,0x73,0x20,0x6f,0x70,0x74,0x69,0x6f,0x6e,0x20,0x63,0x61,0x6e,
0x20,0x62,0x65,0x20,0x75,0x73,0x65,0x64,0x20,0x6d,0x6f,0x72,0x65,0x20,0x74,0x68,
0x65,0x6e,0x20,0x6f,0x6e,0x63,0x65,0x20,0x74,0x6f,0x20,0x64,0x65,0x66,0x69,0x6e,
0x65,0x20,0x64,0x69,0x66,0x66,0x65,0x72,0x65,0x6e,0x74,0x0d,0x0a,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x6e,0x65,0x74,
0x77,0x6f,0x72,0x6b,0x73,0x2e,0x20,0x41,0x20,0x73,0x69,0x6e,0x67,0x6c,0x65,0x20,
0x68,0x6f,0x73,0x74,0x20,0x63,0x61,0x6e,0x20,0x62,0x65,0x20,0x64,0x65,0x66,0x69,
0x6e,0x65,0x64,0x20,0x77,0x69,0x74,0x68,0x20,0x49,0x50,0x2f,0x33,0x32,0x2e,0x20,
0x54,0x68,0x65,0x20,0x64,0x65,0x66,0x69,0x6e,0x65,0x64,0x0d,0x0a,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x6e,0x65,0x74,
0x6d,0x61,0x73,0x6b,0x73,0x20,0x61,0x72,0x65,0x20,0x75,0x73,0x65,0x64,0x20,0x66,
0x6f,0x72,0x20,0x61,0x6c,0x6c,0x20,0x49,0x52,0x54,0x72,0x61,0x6e,0x73,0x20,0x61,
0x6e,0x64,0x20,0x4c,0x49,0x52,0x43,0x20,0x63,0x6c,0x69,0x65,0x6e,0x74,0x73,0x2e,
0x0d,0x0a,0x0d,0x0a,0x2d,0x75,0x64,0x70,0x5f,0x72,0x65,0x6c,0x61,0x79,0x20,0x20,
0x20,0x20,0x20,0x20,0x53,0x77,0x69,0x74,0x63,0x68,0x65,0x73,0x20,0x6f,0x6e,0x20,
0x74,0x68,0x65,0x20,0x55,0x44,0x50,0x20,0x52,0x65,0x6c,0x61,0x79,0x20,0x6f,0x66,
0x20,0x72,0x65,0x63,0x65,0x69,0x76,0x65,0x64,0x20,0x63,0x6f,0x6d,0x6d,0x61,0x6e,
0x64,0x73,0x20,0x74,0x6f,0x20,0x63,0x75,0x73,0x74,0x6f,0x6d,0x20,0x73,0x65,0x72,
0x76,0x65,0x72,0x73,0x2e,0x0d,0x0a,0x3c,0x68,0x6f,0x73,0x74,0x3e,0x20,0x3c,0x70,
0x6f,0x72,0x74,0x3e,0x20,0x20,0x20,0x3c,0x68,0x6f,0x73,0x74,0x3e,0x20,0x69,0x73,
0x20,0x6e,0x61,0x6d,0x65,0x20,0x6f,0x72,0x20,0x49,0x50,0x2d,0x41,0x64,0x72,0x65,
0x73,0x73,0x20,0x6f,0x66,0x20,0x74,0x68,0x65,0x20,0x72,0x65,0x6d,0x6f,0x74,0x65,
0x20,0x73,0x65,0x72,0x76,0x65,0x72,0x2e,0x20,0x3c,0x70,0x6f,0x72,0x74,0x3e,0x20,
0x69,0x73,0x0d,0x0a,0x3c,0x66,0x6f,0x72,0x6d,0x61,0x74,0x3e,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x74,0x68,0x65,0x20,0x55,0x44,0x50,0x20,0x70,0x6f,0x72,0x74,
0x20,0x75,0x73,0x65,0x64,0x20,0x66,0x6f,0x72,0x20,0x74,0x68,0x65,0x20,0x72,0x65,
0x6c,0x61,0x79,0x2e,0x20,0x54,0x68,0x65,0x20,0x66,0x6f,0x72,0x6d,0x61,0x74,0x20,
0x73,0x74,0x72,0x69,0x6e,0x67,0x20,0x64,0x65,0x66,0x69,0x6e,0x65,0x73,0x20,0x74,
0x68,0x65,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x66,0x6f,0x72,0x6d,0x61,0x74,0x20,0x77,0x68,0x69,0x63,0x68,
0x20,0x69,0x73,0x20,0x75,0x73,0x65,0x64,0x20,0x74,0x6f,0x20,0x73,0x65,0x6e,0x64,
0x20,0x74,0x68,0x65,0x20,0x63,0x6f,0x6d,0x6d,0x61,0x6e,0x64,0x73,0x3a,0x20,0x25,
0x72,0x20,0x77,0x69,0x6c,0x6c,0x20,0x62,0x65,0x20,0x72,0x65,0x70,0x6c,0x61,0x63,
0x65,0x64,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x77,0x69,0x74,0x68,0x20,0x74,0x68,0x65,0x20,0x52,0x65,0x6d,
0x6f,0x74,0x65,0x20,0x63,0x6f,0x6e,0x74,0x72,0x6f,0x6c,0x3b,0x20,0x25,0x63,0x20,
0x77,0x69,0x6c,0x6c,0x20,0x62,0x65,0x20,0x72,0x65,0x70,0x6c,0x61,0x63,0x65,0x64,
0x20,0x77,0x69,0x74,0x68,0x20,0x74,0x68,0x65,0x20,0x63,0x6f,0x6d,0x6d,0x61,0x6e,
0x64,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x61,0x6e,0x64,0x20,0x25,0x61,0x20,0x77,0x69,0x6c,0x6c,0x20,0x62,
0x65,0x20,0x72,0x65,0x70,0x6c,0x61,0x63,0x65,0x64,0x20,0x77,0x69,0x74,0x68,0x20,
0x74,0x68,0x65,0x20,0x49,0x52,0x54,0x72,0x61,0x6e,0x73,0x20,0x44,0x65,0x76,0x69,
0x63,0x65,0x20,0x41,0x64,0x72,0x65,0x73,0x73,0x2e,0x20,0x53,0x74,0x61,0x74,0x69,
0x63,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x73,0x74,0x72,0x69,0x6e,0x67,0x73,0x20,0x63,0x61,0x6e,0x20,0x62,
0x65,0x20,0x61,0x64,0x64,0x65,0x64,0x20,0x61,0x73,0x20,0x6e,0x65,0x65,0x64,0x65,
0x64,0x2e,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x4e,0x4f,0x54,0x45,0x3a,0x20,0x54,0x68,0x69,0x73,0x20,0x6f,
0x70,0x74,0x69,0x6f,0x6e,0x20,0x63,0x61,0x6e,0x20,0x62,0x65,0x20,0x75,0x73,0x65,
0x64,0x20,0x74,0x6f,0x20,0x63,0x6f,0x6e,0x6e,0x65,0x63,0x74,0x20,0x74,0x6f,0x20,
0x72,0x65,0x6d,0x6f,0x74,0x65,0x20,0x73,0x65,0x72,0x76,0x65,0x72,0x73,0x20,0x74,
0x68,0x61,0x74,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x64,0x6f,0x20,0x6e,0x6f,0x74,0x20,0x6b,0x6e,0x6f,0x77,
0x20,0x74,0x68,0x65,0x20,0x49,0x52,0x54,0x72,0x61,0x6e,0x73,0x20,0x6f,0x72,0x20,
0x4c,0x49,0x52,0x43,0x20,0x70,0x72,0x6f,0x74,0x6f,0x63,0x6f,0x6c,0x2e,0x20,0x54,
0x68,0x65,0x79,0x20,0x6f,0x6e,0x6c,0x79,0x20,0x6e,0x65,0x65,0x64,0x20,0x74,0x6f,
0x20,0x62,0x65,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x61,0x62,0x6c,0x65,0x20,0x74,0x6f,0x20,0x72,0x65,0x63,
0x65,0x69,0x76,0x65,0x20,0x64,0x65,0x66,0x69,0x6e,0x61,0x62,0x6c,0x65,0x20,0x55,
0x44,0x50,0x20,0x74,0x65,0x6c,0x65,0x67,0x72,0x61,0x6d,0x73,0x2e,0x0d,0x0a,0x0d,
0x0a,0x2d,0x6e,0x6f,0x5f,0x63,0x6c,0x6f,0x63,0x6b,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x44,0x6f,0x20,0x6e,0x6f,0x74,0x20,0x73,0x74,0x61,0x72,0x74,0x20,0x74,0x68,
0x65,0x20,0x43,0x6c,0x6f,0x63,0x6b,0x20,0x6f,0x6e,0x20,0x61,0x20,0x63,0x6f,0x6e,
0x6e,0x65,0x63,0x74,0x65,0x64,0x20,0x44,0x69,0x73,0x70,0x6c,0x61,0x79,0x20,0x6d,
0x6f,0x64,0x75,0x6c,0x65,0x20,0x77,0x68,0x65,0x6e,0x20,0x74,0x68,0x65,0x0d,0x0a,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x69,0x72,0x73,0x65,0x72,0x76,0x65,0x72,0x20,0x69,0x73,0x20,0x73,0x68,0x75,0x74,
0x20,0x64,0x6f,0x77,0x6e,0x2e,0x0d,0x0a,0x0d,0x0a,0x2d,0x73,0x74,0x61,0x72,0x74,
0x5f,0x63,0x6c,0x6f,0x63,0x6b,0x20,0x20,0x20,0x20,0x53,0x74,0x61,0x72,0x74,0x20,
0x74,0x68,0x65,0x20,0x63,0x6c,0x6f,0x63,0x6b,0x20,0x6f,0x6e,0x20,0x61,0x20,0x63,
0x6f,0x6e,0x6e,0x65,0x63,0x74,0x65,0x64,0x20,0x44,0x69,0x73,0x70,0x6c,0x61,0x79,
0x20,0x6d,0x6f,0x64,0x75,0x6c,0x65,0x20,0x77,0x68,0x65,0x6e,0x20,0x74,0x68,0x65,
0x20,0x69,0x72,0x73,0x65,0x72,0x76,0x65,0x72,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x73,0x20,0x73,0x74,
0x61,0x72,0x74,0x65,0x64,0x2e,0x0d,0x0a,0x0d,0x0a,0x2d,0x6c,0x63,0x64,0x20,0x3c,
0x74,0x79,0x70,0x65,0x3e,0x20,0x20,0x20,0x20,0x20,0x44,0x65,0x66,0x69,0x6e,0x65,
0x73,0x20,0x74,0x68,0x65,0x20,0x64,0x69,0x73,0x70,0x6c,0x61,0x79,0x20,0x74,0x79,
0x70,0x65,0x20,0x6f,0x66,0x20,0x61,0x20,0x4c,0x43,0x44,0x20,0x64,0x69,0x73,0x70,
0x6c,0x61,0x79,0x20,0x63,0x6f,0x6e,0x6e,0x65,0x63,0x74,0x65,0x64,0x20,0x74,0x6f,
0x20,0x74,0x68,0x65,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x73,0x65,0x72,0x69,0x61,0x6c,0x20,0x62,0x75,0x73,
0x3a,0x20,0x54,0x79,0x70,0x65,0x20,0x3d,0x20,0x31,0x3a,0x20,0x32,0x30,0x20,0x78,
0x20,0x34,0x3b,0x20,0x54,0x79,0x70,0x65,0x20,0x3d,0x20,0x32,0x3a,0x20,0x34,0x30,
0x20,0x78,0x20,0x34,0x0d,0x0a,0x0d,0x0a,0x2d,0x68,0x74,0x74,0x70,0x5f,0x70,0x6f,
0x72,0x74,0x20,0x3c,0x78,0x3e,0x20,0x20,0x44,0x65,0x66,0x69,0x6e,0x65,0x73,0x20,
0x74,0x68,0x65,0x20,0x54,0x43,0x50,0x2f,0x49,0x50,0x20,0x70,0x6f,0x72,0x74,0x20,
0x74,0x6f,0x20,0x62,0x65,0x20,0x75,0x73,0x65,0x64,0x20,0x66,0x6f,0x72,0x20,0x74,
0x68,0x65,0x20,0x69,0x6e,0x74,0x65,0x67,0x72,0x61,0x74,0x65,0x64,0x20,0x57,0x65,
0x62,0x73,0x65,0x72,0x76,0x65,0x72,0x2e,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x4f,0x6e,0x6c,0x79,0x20,0x69,
0x66,0x20,0x74,0x68,0x69,0x73,0x20,0x6f,0x70,0x74,0x69,0x6f,0x6e,0x20,0x69,0x73,
0x20,0x75,0x73,0x65,0x64,0x20,0x74,0x68,0x65,0x20,0x57,0x65,0x62,0x73,0x65,0x72,
0x76,0x65,0x72,0x20,0x77,0x69,0x6c,0x6c,0x20,0x62,0x65,0x20,0x73,0x74,0x61,0x72,
0x74,0x65,0x64,0x20,0x21,0x0d,0x0a,0x0d,0x0a,0x2d,0x70,0x69,0x64,0x66,0x69,0x6c,
0x65,0x20,0x3c,0x66,0x69,0x6c,0x65,0x3e,0x20,0x57,0x72,0x69,0x74,0x65,0x20,0x74,
0x68,0x65,0x20,0x50,0x49,0x44,0x20,0x6f,0x66,0x20,0x74,0x68,0x65,0x20,0x69,0x72,
0x73,0x65,0x72,0x76,0x65,0x72,0x20,0x74,0x6f,0x20,0x74,0x68,0x65,0x20,0x70,0x61,
0x74,0x68,0x2f,0x66,0x69,0x6c,0x65,0x0d,0x0a,0x0d,0x0a,0x2d,0x64,0x61,0x65,0x6d,
0x6f,0x6e,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x53,0x74,0x61,0x72,0x74,
0x73,0x20,0x74,0x68,0x65,0x20,0x69,0x72,0x73,0x65,0x72,0x76,0x65,0x72,0x20,0x61,
0x73,0x20,0x61,0x20,0x4c,0x49,0x4e,0x55,0x58,0x20,0x53,0x65,0x72,0x76,0x69,0x63,
0x65,0x2e,0x20,0x49,0x66,0x20,0x6e,0x6f,0x20,0x2d,0x6c,0x6f,0x67,0x66,0x69,0x6c,
0x65,0x20,0x6f,0x70,0x74,0x69,0x6f,0x6e,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x73,0x20,0x70,0x72,0x65,
0x73,0x65,0x6e,0x74,0x2c,0x20,0x69,0x72,0x73,0x65,0x72,0x76,0x65,0x72,0x2e,0x6c,
0x6f,0x67,0x20,0x69,0x6e,0x20,0x74,0x68,0x65,0x20,0x63,0x75,0x72,0x72,0x65,0x6e,
0x74,0x20,0x64,0x69,0x72,0x65,0x63,0x74,0x6f,0x72,0x79,0x20,0x69,0x73,0x20,0x75,
0x73,0x65,0x64,0x2e,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x54,0x48,0x49,0x53,0x20,0x4f,0x50,0x54,0x49,0x4f,
0x4e,0x20,0x49,0x53,0x20,0x56,0x41,0x4c,0x49,0x44,0x20,0x46,0x4f,0x52,0x20,0x4c,
0x49,0x4e,0x55,0x58,0x20,0x4f,0x4e,0x4c,0x59,0x20,0x21,0x0d,0x0a,0x0d,0x0a,0x2d,
0x73,0x65,0x74,0x5f,0x69,0x64,0x20,0x3c,0x69,0x64,0x3e,0x20,0x20,0x20,0x20,0x53,
0x65,0x74,0x73,0x20,0x74,0x68,0x65,0x20,0x64,0x65,0x76,0x69,0x63,0x65,0x20,0x49,
0x44,0x20,0x66,0x6f,0x72,0x20,0x61,0x20,0x32,0x6e,0x64,0x20,0x67,0x65,0x6e,0x65,
0x72,0x61,0x74,0x69,0x6f,0x6e,0x20,0x49,0x52,0x54,0x72,0x61,0x6e,0x73,0x20,0x6d,
0x6f,0x64,0x75,0x6c,0x65,0x2e,0x20,0x54,0x68,0x69,0x73,0x0d,0x0a,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x6f,0x70,0x74,
0x69,0x6f,0x6e,0x20,0x63,0x61,0x6e,0x20,0x62,0x65,0x20,0x75,0x73,0x65,0x64,0x20,
0x74,0x6f,0x20,0x73,0x65,0x74,0x20,0x74,0x68,0x65,0x20,0x49,0x44,0x20,0x66,0x6f,
0x72,0x20,0x74,0x68,0x65,0x20,0x49,0x52,0x54,0x72,0x61,0x6e,0x73,0x20,0x6d,0x6f,
0x64,0x75,0x6c,0x65,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x63,0x6f,0x6e,0x6e,0x65,0x63,0x74,0x65,0x64,0x20,
0x64,0x69,0x72,0x65,0x63,0x74,0x6c,0x79,0x20,0x74,0x6f,0x20,0x74,0x68,0x65,0x20,
0x73,0x65,0x72,0x76,0x65,0x72,0x2e,0x20,0x49,0x74,0x20,0x69,0x73,0x20,0x6f,0x6e,
0x6c,0x79,0x20,0x76,0x61,0x6c,0x69,0x64,0x20,0x66,0x6f,0x72,0x20,0x74,0x68,0x65,
0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x32,0x6e,0x64,0x20,0x67,0x65,0x6e,0x65,0x72,0x61,0x74,0x69,0x6f,0x6e,
0x20,0x52,0x53,0x32,0x33,0x32,0x2f,0x55,0x53,0x42,0x20,0x6d,0x6f,0x64,0x75,0x6c,
0x65,0x73,0x20,0x74,0x68,0x61,0x74,0x20,0x6e,0x6f,0x20,0x6c,0x6f,0x6e,0x67,0x65,
0x72,0x20,0x68,0x61,0x76,0x65,0x20,0x61,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x44,0x49,0x50,0x20,0x73,0x77,
0x69,0x74,0x63,0x68,0x20,0x74,0x6f,0x20,0x73,0x65,0x74,0x20,0x74,0x68,0x65,0x20,
0x49,0x44,0x2e,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x54,0x48,0x49,0x53,0x20,0x4f,0x50,0x54,0x49,0x4f,0x4e,
0x20,0x57,0x49,0x4c,0x4c,0x20,0x4e,0x4f,0x54,0x20,0x53,0x54,0x41,0x52,0x54,0x20,
0x54,0x48,0x45,0x20,0x53,0x45,0x52,0x56,0x45,0x52,0x2e,0x20,0x49,0x54,0x20,0x4f,
0x4e,0x4c,0x59,0x20,0x53,0x45,0x54,0x53,0x20,0x54,0x48,0x45,0x20,0x49,0x44,0x21,
0x00
};
|
asterics/IRTrans-Server
|
xap.h
|
/*
* Copyright (c) 2007, IRTrans GmbH
* 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.
* * Neither the name of IRTrans GmbH nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY IRTrans GmbH ``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 IRTrans GmbH 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.
*/
void xAP_SendHeartbeat (void);
void xAP_SendData (char data[]);
void xAP_SendIREvent (char remote[],char command[],int bus,int adr);
void xAP_EventReceived (void);
void xAP_ProcessHeader (char data[]);
int xAP_GetItem (char data[],char item[],char value[]);
int xAP_GetLine (char data[],char line[],int pos);
extern SOCKET xAP_rcv;
extern SOCKET xAP_send;
extern int xAP_rcv_port;
extern time_t xAP_last_hbeat;
#define XAP_UID "FF2121"
#define XAP_HBEAT 60
#define XAP_ADR "IRTrans.irserver"
#define XAP_VERSION 12
|
asterics/IRTrans-Server
|
functioncodes.h
|
#define FN_IR 1
#define FN_SBUS 2
#define FN_SER 4
#define FN_USB 8
#define FN_POWERON 16
#define FN_EXT_SW 32
#define FN_CALIBRATE 64
#define FN_SOFTID 128
#define FN_EEPROM 256
#define FN_TRANSL 512
#define FN_HWCARR 1024
#define FN_DUALRCV 2048
#define FN_SBUS_UART 4096
#define FN_FLASH128 8192
#define FN_DUALSND 16384
#define FN_DISP1 32768
#define FN_DISP2 0x10000
#define FN_DISP3 0x20000
#define FN_CLOCK 0x40000
#define FN_DEBOUNCE 0x80000
#define FN_BOOTLOADER 0x100000
#define FN_DUALPOWERON 0x200000
#define FN_USBWAKEUP 0x400000
#define FN_NOSCROLL 0x800000
#define FN_LAN 0x1000000
#define FN_IRDB 0x2000000
#define FN_LARGECPU 0x4000000
#define FN_MULTIRELAY4 0x8000000
#define FN_MULTISEND4 0x10000000
#define FN_MULTISEND8 0x20000000
#define FN_MULTISEND2 0x40000000
#define FN_HTML 0x80000000
#define FN2_FUNCTIONVAL2 1
#define FN2_EXT_RCV 2
#define FN2_ONEWIRE 4
#define FN2_PULSE200 8
#define FN2_V38 16
#define FN2_RECS80 32
#define FN2_PULSELEN_18 64
#define FN2_SW_RCV_SEL 128
#define FN2_RTS_CTS 256
#define FN2_MULTIRELAY2 512
#define FN2_DUTYCYCLE 1024
#define FN2_SBUS_SEND 2048
#define FN2_SEND_ACK 4096
#define FN2_USB_WAKEUP 8192
#define FN2_STATEIO_SBUS 16384
#define FN2_STATEIO_ANALOG 32768
#define FN2_RS232_IO_SBUS 0x10000
#define FN2_RS232_OUT_IR 0x20000
#define FN2_AUX_RS232 0x40000
#define FN2_RS232_PARAMETER 0x80000
#define FN2_AUXRS232_PARAMETER 0x100000
#define FN2_MULTISEND16 0x200000
#define FN2_STATEIO_IRIN 0x400000
#define FN2_SW_SEL_EXT_LOW 0x800000
#define FN2_IRIN_EXTRA_LINE 0x1000000
#define FN2_RELAY_SBUS 0x2000000
#define FN2_EXT_HI_LO_SINGLE 0x4000000 // Single External RCV Connector for HI&LOW RCV
#define FN2_RC5_FREE_TIMING 0x8000000
#define FN2_INTERNAL_PLASMA 0x10000000
#define FN2_HF_BLASTER 0x20000000
#define FN2_RS232_IN_IR 0x40000000
#define FN2_RS232_UDP_RELAY 0x80000000
#define FN3_RCV_LOW_56 1
#define FN3_RCV_LOW_38 2
#define FN3_RCV_LOW_38_PLAS 3
#define FN3_RCV_LOW_455 4
#define FN3_RCV_LOW_455_PLAS 5
#define FN3_RCV_LOW_CODELEARN 6
#define FN3_RCV_LOW_ACTIVE 8
#define FN3_RCV_HI_56 16
#define FN3_RCV_HI_38 32
#define FN3_RCV_HI_38_PLAS 48
#define FN3_RCV_HI_455 64
#define FN3_RCV_HI_455_PLAS 80
#define FN3_RCV_HI_CODELEARN 96
#define FN3_RCV_HI_ACTIVE 128
#define FN3_DUAL_RCV_EXTERNAL 256
#define FN3_WLAN 512
#define FN3_MULTISTREAM 1024
#define FN3_VAR_SEND_POWER 2048
#define FN3_NO_RECEIVE 4096
#define FN3_SEND_MACRO 8192
#define FN3_ONE_WIRE_IR1 16384
#define FN3_ONE_WIRE_IR2 32768
#define FN3_ONE_WIRE_ANALOG1 0x10000
#define FN3_ONE_WIRE_ANALOG2 0x20000
#define FN3_IRIN_ANALOG 0x40000
#define FN3_TRANSLATOR_IRDB 0x80000
#define FN3_ANALOG_LEVEL 0x100000
#define FN_DISPMASK 0x38000
#define FUNCTION_FLASH_MASK ~(FN_SBUS_UART | FN_CLOCK | FN_DEBOUNCE | FN_DUALPOWERON | FN_USBWAKEUP | FN_NOSCROLL | FN_TRANSL | FN_CALIBRATE | FN_POWERON)
#define FUNCTION_FLASH_MASK_2 (FN2_AUX_RS232 | FN2_MULTISEND16)
#define FN4_DEVICETYPE_OTHER 0
#define FN4_DEVICETYPE_USB_3_6 1
#define FN4_DEVICETYPE_USB_3_8 2
#define FN4_DEVICETYPE_TRANS_2_0 3
#define FN4_DEVICETYPE_TRANS_3_2 4
#define FN4_DEVICETYPE_TRANS_XL 5
#define FN4_DEVICETYPE_LAN_1_2 6
#define FN4_DEVICETYPE_LAN_2_2 7 // POE 1.3
#define FN4_DEVICETYPE_LAN_2_3 8 // POE 2.1
//#define FN4_DEVICETYPE_POE_1_3 9
//#define FN4_DEVICETYPE_POE_2_1 10
#define FN4_DEVICETYPE_LANIO_1_5 11
#define FN4_DEVICETYPE_LANIO_CTL_1_5 12
#define FN4_DEVICETYPE_RS232_3_6 13
#define FN4_DEVICETYPE_RS232_3_8 14
#define FN4_DEVICETYPE_BUS_3_5 15
#define FN4_DEVICETYPE_BUS_3_8 16
#define FN4_DEVICETYPE_WIFI_1_5 17
#define FN4_DEVICETYPE_LANC 18
#define FN4_DEVICETYPE_LANC_XL 19
#define FN4_DEVICETYPE_LANC_XXL 20
#define FN4_DEVICETYPE_LANC_MS_16 21
#define FN4_DEVICETYPE_OEM 22
|
asterics/IRTrans-Server
|
lowlevel.h
|
/*
* Copyright (c) 2007, IRTrans GmbH
* 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.
* * Neither the name of IRTrans GmbH nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY IRTrans GmbH ``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 IRTrans GmbH 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.
*/
#ifdef WIN32
#include <time.h>
#include <sys/timeb.h>
#endif
#ifdef LINUX
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <signal.h>
#include <stdint.h>
#include <sys/time.h>
#include <sys/timeb.h>
#endif
word CalcFramelength (IRDATA *ird);
int ReadHTMLDirectory (void);
int SetTransceiverIDEx (int bus,byte id);
int GetBusInfo (STATUS_BUFFER *sb);
int GetBusInfoEx (STATUS_BUFFER_N *sb,int bus);
int GetBusInfoExShort (STATUS_BUFFER_N *sb,int bus);
void CopyBusInfoShort (STATUS_BUFFER_N *sb,int bus);
int GetBusInfoDetail (STATUS_BUFFER_N *sb,int bus);
int SetTransceiverModusEx (int bus,byte mode,word send_mask,byte addr,char *hotcode,int hotlen,byte extended_mode,byte extended_mode2,byte extended_mode_ex[],byte *mac,byte rs232_mode[],STATUS_MEMORY *status_input);
int SetTransceiverModusEx2 (int bus,byte addr,char *hotcode,int hotlen);
int TransferFlashdataEx (int bus,word data[],int adr,int len,byte active,int iradr);
int ReadFlashdataEx (int bus,int adr);
int SendIR (int cmd_num,int address,byte netcommand,word *framelen);
int SendIRMacro (int cmd_num[],int address,word macro_pause[],word *framelen);
int DoSendIR (IRDATA *ir_data,IRDATA *ir_rep,int rpt_len,int rpt_pause,int bus,byte netcommand);
int SendIRDataEx (IRDATA *ir_data,int address);
int SendLCD (IRRAW *ir_data,int address);
int AdvancedLCD (byte mode,byte data[],int len);
void LCDBrightness (int val);
int ResendIREx (int bus,IRDATA *ir_data);
byte Convert2OldCarrier (byte carrier);
int ResetTransceiverEx (int bus);
int SetPowerLED (int bus,byte mode,byte val);
int SetRelaisEx (int bus,byte val,byte rel);
int ReadAnalogInputs (int bus,byte mask,ANALOG_INPUTS *inputs);
int ReadAnalogInputsEx (int bus,word mask,byte mode,byte id[],ANALOG_INPUTS_EX *inputs);
//int ReadAnalogInputs (int bus,byte mask,ANALOG_DATA *inputs);
int SetAnalogConfig (ANALOG_CONFIG_COMMAND *acc);
int SendSerialBlock (int bus,byte data[],byte len,byte param);
int StoreTimerEntry (int bus,TIMERCOMMAND *tim);
int TransferToTimelen18 (IRDATA *src,IRDATA *snd,int bus);
byte CheckLEDValid (byte adr,int bus);
int TestIRLength (IRDATA *ir,byte bus);
int TestStatusAvailable (IRDATA *ir,int bus,byte netcommand);
int ReadIR (byte data[]);
int LearnIREx (IRDATA *ir_data,word addr,word timeout,word ir_timeout,byte carrier,byte modes);
int LearnNextIREx (IRDATA *ir_data,word addr,word timeout,word ir_timeout,byte carrier,byte modes);
int LearnRawIREx (IRRAW *ir_data,word addr,word timeout,word ir_timeout,byte carrier);
int LearnRawIRRepeatEx (IRRAW *ir_data,word addr,word timeout,word ir_timeout,byte carrier);
int LearnRepeatIREx (IRDATA *ir_data,word addr,word timeout,word ir_timeout,byte carrier,byte modes);
void ResetComLines (void);
void CorrectIRTimings (IRDATA *ir_data);
void CorrectIRTimingsRAW (IRRAW *ir_data);
void PrintPulseData (IRDATA *ir_data);
void PrintCommand (IRDATA *ir_data);
void PrintRawData (IRRAW *ir_data);
int WriteTransceiverCommand (byte pnt);
int WriteTransceiver (IRDATA *src,byte usb_mode);
byte get_checksumme (IRDATA *ir);
void ConvertToIRTRANS3 (IRDATA *ird);
void ConvertToIRTRANS4 (IRDATA3 *ird);
int GetTransceiverVersion (char version [],unsigned int *cap,unsigned int *serno,char mac_adr[],byte usbmode);
int ResetTransceiver (void);
int InitCommunication (char device[],char version[]);
int InitCommunicationEx (char devicesel[]);
void InitConversionTables (void);
void ConvertLCDCharset (byte *pnt);
void LCDTimeCommand (byte mode);
void SetSpecialChars (byte dat[]);
void SetLCDProcCharsV (byte dat[]);
void FlushUSB (void);
void FlushCom (void);
void msSleep (int time);
int ReadIRString (byte pnt[],int len,word timeout,byte usb_mode);
void WriteIRString (byte pnt[],int len,byte usb_mode);
void GetError (int res,char st[]);
void log_print (char msg[],int level);
void Hexdump_File (IRDATA *ird);
void Hexdump_Medialon (IRDATA *ird);
void swap_irdata (IRDATA *src,IRDATA *tar);
void swap_word (word *pnt);
void force_swap_word (word *pnt);
void swap_int (int32_t *pnt);
void SwapWordN (word *pnt);
int GetByteorder (void);
void SwapStatusbuffer (STATUS_BUFFER *sb);
unsigned int GetMsTime (void);
int get_devices (char sel[],byte testmode);
int get_detail_deviceinfo (char serno[],char devnode[],byte if_type);
void sort_ir_devices (char selstring[]);
void CloseIRTransLANSocket (void);
void CloseServerSockets (SOCKET sock,SOCKET lirc, SOCKET udp,SOCKET web);
void showDebugTiming (IRDATA *ird);
extern byte byteorder;
#define MINIMUM_SW_VERSION "2.18.04"
#ifdef LINUX
typedef int HANDLE;
typedef int OVERLAPPED;
#endif
#ifndef FTD2XX_H
typedef void* FT_HANDLE;
#endif
#define MAX_IR_DEVICES 256
#pragma pack(8)
#define IF_RS232 0
#define IF_USB 1
#define IF_LAN 2
#define IF_SERUSB 3
typedef struct {
byte if_type; // 0 = RS232 1 = USB 2 = LAN
byte time_len;
byte raw_repeat;
byte ext_carrier;
byte toggle_support;
byte inst_receive_mode;
byte advanced_lcd;
byte io_seq_mode;
byte io_sequence;
byte lan_io_sequence;
char node[20];
FT_HANDLE usbport;
HANDLE comport;
HANDLE event;
OVERLAPPED ov_read;
OVERLAPPED ov_write;
SOCKET socket;
time_t last_time;
int tcp_reconnect;
struct sockaddr_in IPAddr[16];
char receive_buffer[4][256];
int receive_cnt[4];
int receive_buffer_cnt;
} IOINFO;
typedef struct {
char name[40];
char usb_serno[20];
char device_node[40];
char cap_string[80];
char version[20];
char lan_version[20];
byte mac_adr[6];
uint32_t fw_serno;
uint32_t fw_capabilities;
uint32_t fw_capabilities2;
uint32_t fw_capabilities3;
uint32_t fw_capabilities4;
byte extended_mode;
byte extended_mode2;
byte extended_mode_ex[8];
byte extended_mode_ex2[8];
byte ext_rs232_setting[16];
STATUS_MEMORY status_info;
byte my_addr;
IOINFO io;
byte comport_seq_number;
HANDLE virtual_comport;
HANDLE com_event;
OVERLAPPED com_ov;
byte comio_init;
FILE *comport_file;
} DEVICEINFO;
int GetLANParamEx (LANSTATUSBUFFER *buf,DEVICEINFO *dev);
int WriteSysparameter (int bus,SYS_PARAMETER *sysparm);
int SetWLANConfig (int bus,WIFI_MODE *wbuf);
int ReadSerialStringComio (DEVICEINFO *dev,byte pnt[],int len,word timeout);
int WriteIRStringEx (DEVICEINFO *dev,byte pnt[],int len);
int ReadIRStringEx (DEVICEINFO *dev,byte pnt[],int len,word timeout);
int ReadIRStringEx_ITo (DEVICEINFO *dev,byte pnt[],int len,word timeout);
int ReadIRStringAvailable (DEVICEINFO *dev,byte pnt[],int len,word timeout);
int WriteTransceiverEx (DEVICEINFO *dev,IRDATA *src);
void FlushIoEx (DEVICEINFO *dev);
int GetTransceiverVersionEx (DEVICEINFO *dev);
int GetWiFiStatusEx (WLANBUFFER *buf,DEVICEINFO *dev);
int GetWiFiParamEx (WLANSTATUSBUFFER *buf,DEVICEINFO *dev);
int GetSysParameterEx (SYSPARAMBUFFER *buf,DEVICEINFO *dev);
void FlushComEx(HANDLE fp);
void CancelLearnEx (DEVICEINFO *dev);
int ReadInstantReceive (DEVICEINFO *dev,byte pnt[],int len);
int GetAvailableDataEx (DEVICEINFO *dev);
int IRTransLanSend (DEVICEINFO *dev,IRDATA *ird);
int OpenVirtualComPorts (void);
int OpenVirtualComport (char Pname[],HANDLE *port);
int WritePort (DEVICEINFO *dev,byte pnt[],int len);
int OpenComFiles (void);
int rcv_status_timeout (int timeout,uint32_t ip);
int rcv_status_timeout_tcp (DEVICEINFO *dev,int timeout);
int open_irtrans_tcp (DEVICEINFO *dev);
int ReadLearndataLAN (DEVICEINFO *dev,byte *ird,int timeout);
void force_swap_irdata (IRDATA *ir);
extern DEVICEINFO IRDevices[MAX_IR_DEVICES];
extern int device_cnt;
extern char hexfile[256];
extern FILE *hexfp;
extern byte hexflag;
extern STATUS_BUFFER_N remote_statusex[MAX_IR_DEVICES];
#define TABLE_CNT 2
extern byte DispConvTable[TABLE_CNT][256];
extern char virt_comnames[50][100];
extern char virt_comfiles[50][100];
|
asterics/IRTrans-Server
|
dbstruct.h
|
<gh_stars>1-10
/*
* Copyright (c) 2007, IRTrans GmbH
* 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.
* * Neither the name of IRTrans GmbH nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY IRTrans GmbH ``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 IRTrans GmbH 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.
*/
#pragma pack(1)
#define COMMAND_MODE_FN 1
#define COMMAND_MODE_KEY 2
typedef struct {
char name[80];
word target_mask;
} ROUTING;
typedef struct {
char name[80];
byte addr;
} ROOMS;
typedef struct {
char name[80];
int number;
word target_mask;
word source_mask;
int timing_start;
int timing_end;
int command_start;
int command_end;
int toggle_pos;
byte transmitter;
byte rcv_len;
byte rcv_start;
} IRREMOTE;
typedef struct {
int remote;
byte ir_length;
byte transmit_freq;
byte mode;
word pause_len[TIME_LEN_SINGLE];
word pulse_len[TIME_LEN_SINGLE];
byte time_cnt;
byte ir_repeat;
byte repeat_pause;
byte carrier_measured;
word link_count;
word flash_adr;
byte toggle_pos[4];
byte toggle_val[4][2];
byte toggle_num;
byte timecount_mode;
byte repeat_offset;
} IRTIMING;
typedef struct {
char name[20];
int command_link;
int remote_link;
int remote;
int timing;
int command_length;
int pause;
byte toggle_seq;
byte toggle_pos;
byte mode;
word ir_length;
byte data[CODE_LEN * 2 + 200];
word ir_length_cal;
byte data_cal[CODE_LEN * 2 + 200];
word ir_length_offset;
byte data_offset[CODE_LEN * 2 + 100];
byte offset_val;
} IRCOMMAND;
typedef struct {
char name[20];
int command_link;
int remote_link;
int remote;
int timing;
int command_length;
int pause;
byte toggle_seq;
byte toggle_pos;
byte mode;
byte ir_length;
int macro_num;
int macro_len;
} IRMACRO;
typedef struct {
char mac_remote[80];
char mac_command[20];
int pause;
} MACROCOMMAND;
typedef struct {
word id;
word num;
word mode;
char remote[80];
char command[20];
} SWITCH;
typedef union {
int function[8];
char name[32];
} APPFUNCTION;
typedef struct {
int comnum;
byte type[8];
APPFUNCTION function;
} APPCOMMAND;
typedef struct {
char name[20];
char classname[50];
char appname[100];
char remote[80];
int remnum;
byte type;
byte com_cnt;
byte active;
byte align;
APPCOMMAND com[50];
} APP;
#pragma pack(8)
|
asterics/IRTrans-Server
|
winusbio.h
|
<reponame>asterics/IRTrans-Server<gh_stars>1-10
/*
* Copyright (c) 2007, IRTrans GmbH
* 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.
* * Neither the name of IRTrans GmbH nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY IRTrans GmbH ``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 IRTrans GmbH 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 "ftd2xx.h"
//typedef unsigned short word;
extern char usbcomports[20][5];
extern int usbcomcnt;
#ifdef LINUX
#define F_Open FT_Open
#define F_OpenEx FT_OpenEx
#define F_Write FT_Write
#define F_ListDevices FT_ListDevices
#define F_GetDeviceInfo FT_GetDeviceInfo
#define F_Read FT_Read
#define F_SetLatencyTimer FT_SetLatencyTimer
#define F_Close FT_Close
#define F_GetQueueStatus FT_GetQueueStatus
#define F_ResetDevice FT_ResetDevice
#define F_CyclePort FT_CyclePort
#define F_Reload FT_Reload
#define F_Purge FT_Purge
#define F_SetTimeouts FT_SetTimeouts
#define F_SetEventNotification FT_SetEventNotification
#endif
#ifdef WIN32
HMODULE hdll;
void GetComPorts (void);
int GetOSInfo (void);
typedef enum FT_STATUS (WINAPI *PtrToListDevices)(PVOID, PVOID, DWORD);
PtrToListDevices m_pListDevices;
enum FT_STATUS F_ListDevices(PVOID, PVOID, DWORD);
typedef enum FT_STATUS (WINAPI *PtrToOpen)(PVOID, FT_HANDLE *);
PtrToOpen m_pOpen;
enum FT_STATUS F_Open(PVOID, FT_HANDLE *);
typedef enum FT_STATUS (WINAPI *PtrToGetDeviceInfo)(FT_HANDLE,FT_DEVICE *,DWORD *,char *,char *,PVOID);
PtrToGetDeviceInfo m_pGetDeviceInfo;
enum FT_STATUS F_GetDeviceInfo(FT_HANDLE,FT_DEVICE *,DWORD *,char *,char *,PVOID);
typedef enum FT_STATUS (WINAPI *PtrToOpenEx)(PVOID, DWORD, FT_HANDLE *);
PtrToOpenEx m_pOpenEx;
enum FT_STATUS F_OpenEx(PVOID, DWORD, FT_HANDLE *);
typedef enum FT_STATUS (WINAPI *PtrToRead)(FT_HANDLE, LPVOID, DWORD, LPDWORD);
PtrToRead m_pRead;
enum FT_STATUS F_Read(FT_HANDLE,LPVOID, DWORD, LPDWORD);
typedef enum FT_STATUS (WINAPI *PtrToClose)(FT_HANDLE);
PtrToClose m_pClose;
enum FT_STATUS F_Close(FT_HANDLE);
typedef enum FT_STATUS (WINAPI *PtrToGetQueueStatus)(FT_HANDLE, LPDWORD);
PtrToGetQueueStatus m_pGetQueueStatus;
enum FT_STATUS F_GetQueueStatus(FT_HANDLE,LPDWORD);
typedef enum FT_STATUS (WINAPI *PtrToWrite)(FT_HANDLE, LPVOID, DWORD, LPDWORD);
PtrToWrite m_pWrite;
enum FT_STATUS F_Write(FT_HANDLE,LPVOID, DWORD, LPDWORD);
typedef enum FT_STATUS (WINAPI *PtrToResetDevice)(FT_HANDLE);
PtrToResetDevice m_pResetDevice;
enum FT_STATUS F_ResetDevice(FT_HANDLE);
typedef enum FT_STATUS (WINAPI *PtrToCyclePort)(FT_HANDLE);
PtrToCyclePort m_pCyclePort;
enum FT_STATUS F_CyclePort(FT_HANDLE);
typedef enum FT_STATUS (WINAPI *PtrToReload)(WORD, WORD);
PtrToReload m_pReload;
enum FT_STATUS F_Reload(WORD,WORD);
typedef enum FT_STATUS (WINAPI *PtrToPurge)(FT_HANDLE, ULONG);
PtrToPurge m_pPurge;
enum FT_STATUS F_Purge(FT_HANDLE,ULONG);
typedef enum FT_STATUS (WINAPI *PtrToSetTimeouts)(FT_HANDLE, ULONG, ULONG);
PtrToSetTimeouts m_pSetTimeouts;
enum FT_STATUS F_SetTimeouts(FT_HANDLE,ULONG, ULONG);
typedef enum FT_STATUS (WINAPI *PtrToSetEvent)(FT_HANDLE, DWORD, LPVOID);
PtrToSetEvent m_pSetEvent;
enum FT_STATUS F_SetEventNotification(FT_HANDLE,DWORD,LPVOID);
typedef enum FT_STATUS (WINAPI *PtrToSetLatencyTimer)(FT_HANDLE, UCHAR);
PtrToSetLatencyTimer m_pSetLatencyTimer;
enum FT_STATUS F_SetLatencyTimer(FT_HANDLE,UCHAR);
#endif
int LoadUSBLibrary (void);
void cleanup_exit (void);
void break_signal (int sig);
int OpenUSBPort (void);
int WriteUSBString (byte pnt[],int len);
int ReadUSBString (byte pnt[],int len,long timeout);
void FlushUSB (void);
void SetUSBEvent (PVOID,DWORD);
void SetUSBEventEx (DEVICEINFO *dev,DWORD mask);
void FlushUSBEx (FT_HANDLE hndl);
void WriteUSBStringEx (DEVICEINFO *dev,byte pnt[],int len);
int ReadUSBStringEx (DEVICEINFO *dev,byte pnt[],int len,word timeout);
int GetUSBAvailableEx (DEVICEINFO *dev);
int ReadUSBStringEx_ITo (DEVICEINFO *dev,byte pnt[],int len,word timeout);
int ReadUSBStringAvailable (DEVICEINFO *dev,byte pnt[],int len,word timeout);
|
asterics/IRTrans-Server
|
server.h
|
<reponame>asterics/IRTrans-Server
/*
* Copyright (c) 2007, IRTrans GmbH
* 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.
* * Neither the name of IRTrans GmbH nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY IRTrans GmbH ``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 IRTrans GmbH BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
int InitServer (char dev[]);
int RunServer ();
void SwapNetworkheader (NETWORKSTATUS *ns);
void SwapNetworkcommand (NETWORKCOMMAND *nc);
void SwapNetworkstatus (void *pnt);
int GetDeviceStatus (STATUSBUFFER *buf);
int GetHotcode (char rem[],char com[],byte data[]);
void PutNetworkStatus (int res,char msg[],STATUSBUFFER *buf);
void StoreTransItem (TRANSLATECOMMAND *tr);
int StoreDbItem (IRDBCOMMAND *db);
int FileTransData (char nm[],byte dbtype,byte filemode);
int LoadTranslation (TRANSLATEBUFFER *tb,char nm[],word offset);
int LoadIRDB (IRDBBUFFER *db,char nm[],word offset);
int SetFlashdataEx (byte bus,int iradr,STATUSBUFFER *stat);
int SetIRDBEx (byte bus,int iradr,STATUSBUFFER *stat);
unsigned int GetMsTime (void);
void udp_relay (char rem[],char com[],int adr);
void InitMediacenter (void);
int GetDeviceData (int cmd_num,DATABUFFER *dat);
int ReadIRTransDirectory (char filetype[],REMOTEBUFFER *stat,int start,byte statustype);
void send_forward (int client,char remote[],char command[]);
void NetworkClientMessage (char msg[],int num);
void HandleHID (int rem_num,int com_num,char rname[],char xcode[]);
extern byte status_changed;
extern unsigned int netmask[32];
extern unsigned int netip[32];
extern byte netcount;
|
asterics/IRTrans-Server
|
linuxusbio.c
|
<filename>linuxusbio.c
#ifdef LINUX
#include "../../Common/remote.h"
int OpenUSBPort (void)
{
}
int ReadUSBString (byte pnt[],int len,word timeout)
{
}
void FlushUSB (void)
{
}
void WriteUSBString (byte pnt[],int len)
{
}
#endif
|
asterics/IRTrans-Server
|
winusbio.c
|
/*
* Copyright (c) 2007, IRTrans GmbH
* 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.
* * Neither the name of IRTrans GmbH nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY IRTrans GmbH ``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 IRTrans GmbH 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.
*/
#ifdef WIN32
#include "winsock2.h"
#include <windows.h>
#include <winbase.h>
#endif
#ifdef LINUX
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include "WinTypes.h"
#endif
#include <stdio.h>
#include <signal.h>
#include "errcode.h"
#include "remote.h"
#include "network.h"
#include "lowlevel.h"
#include "global.h"
#include "winusbio.h"
FT_HANDLE usb;
char usbcomports[20][5];
int usbcomcnt;
#ifdef WIN32
int GetOSInfo (void)
{
int ver;
OSVERSIONINFO os;
char *cpu;
memset (&os,0,sizeof (OSVERSIONINFO));
os.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
GetVersionEx (&os);
ver = os.dwMajorVersion * 100 + os.dwMinorVersion * 10;
cpu = getenv ("PROCESSOR_ARCHITEW6432");
if (cpu) ver |= 1;
return (ver);
}
void GetComPorts (void)
{
int res,pos,cnt;
char buf[20000];
res = QueryDosDevice (NULL,buf,20000);
cnt = pos = 0;
while (pos < res) {
if (!memcmp (buf+pos,"COM",3)) cnt++;
while (buf[pos]) pos++;
pos++;
}
if (cnt > 20) cnt = 20;
usbcomcnt = cnt;
pos = 0;
while (pos < res) {
if (!memcmp (buf+pos,"COM",3)) {
strcpy (usbcomports[cnt-1],buf+pos);
cnt--;
}
while (buf[pos]) pos++;
pos++;
}
}
#endif
int OpenUSBPort (void)
{
FT_STATUS stat;
stat = F_OpenEx ("IRTrans USB",FT_OPEN_BY_DESCRIPTION,&usb);
if (stat) stat = F_OpenEx ("FB401",FT_OPEN_BY_DESCRIPTION,&usb);
if (stat) stat = F_OpenEx ("IRTrans USB B",FT_OPEN_BY_DESCRIPTION,&usb);
if (stat) stat = F_OpenEx ("IRTrans WiFi",FT_OPEN_BY_DESCRIPTION,&usb);
if (stat) stat = F_OpenEx ("Breakout Box",FT_OPEN_BY_DESCRIPTION,&usb);
if (stat) return (ERR_OPENUSB);
F_SetLatencyTimer (usb,2);
return (0);
}
int WriteUSBString (byte pnt[],int len)
{
DWORD num;
FT_STATUS stat;
stat = F_Write (usb,pnt,len,&num);
if (stat) return (0);
return (num);
}
int ReadUSBString (byte pnt[],int len,long timeout)
{
DWORD num;
FT_STATUS stat;
F_SetTimeouts (usb,timeout,0);
stat = F_Read (usb,pnt,len,&num);
if (stat) return (0);
return (num);
}
int GetUSBAvailableEx (DEVICEINFO *dev)
{
DWORD num;
FT_STATUS stat;
stat = F_GetQueueStatus (dev->io.usbport,&num);
if (stat) return (0);
return (num);
}
int ReadUSBStringEx_ITo (DEVICEINFO *dev,byte pnt[],int len,word timeout)
{
int cnt = 0;
int rcnt;
DWORD wstat;
DWORD num;
SetUSBEventEx (dev,FT_EVENT_RXCHAR);
while (cnt < len) {
#ifdef WIN32
if (!cnt) wstat = WaitForSingleObject(dev->io.event,timeout * 4);
else wstat = WaitForSingleObject(dev->io.event,timeout);
if (wstat == WAIT_TIMEOUT) return (cnt);
ResetEvent (dev->io.event);
#endif
F_GetQueueStatus (dev->io.usbport,&num);
if (num > (DWORD)(len - cnt)) num = len - cnt;
rcnt = ReadUSBStringEx (dev,pnt + cnt,num,100);
cnt += rcnt;
}
return (cnt);
}
int ReadUSBStringAvailable (DEVICEINFO *dev,byte pnt[],int len,word timeout)
{
DWORD wstat;
DWORD num;
F_GetQueueStatus (dev->io.usbport,&num);
if (!num) {
#ifdef WIN32
SetUSBEventEx (dev,FT_EVENT_RXCHAR);
wstat = WaitForSingleObject(dev->io.event,timeout);
if (wstat == WAIT_TIMEOUT) return (0);
ResetEvent (dev->io.event);
#endif
}
F_GetQueueStatus (dev->io.usbport,&num);
if (num > (DWORD)(len)) num = len;
return (ReadUSBStringEx (dev,pnt,num,100));
}
int ReadUSBStringEx (DEVICEINFO *dev,byte pnt[],int len,word timeout)
{
DWORD num;
FT_STATUS stat;
F_SetTimeouts (dev->io.usbport,timeout,0);
stat = F_Read (dev->io.usbport,pnt,len,&num);
if (stat) return (0);
return (num);
}
void FlushUSB (void)
{
F_Purge (usb,FT_PURGE_RX | FT_PURGE_TX);
}
void FlushUSBEx (FT_HANDLE hndl)
{
F_Purge (hndl,FT_PURGE_RX | FT_PURGE_TX);
}
void WriteUSBStringEx (DEVICEINFO *dev,byte pnt[],int len)
{
DWORD num;
FT_STATUS stat;
stat = F_Write (dev->io.usbport,pnt,len,&num);
if (stat == 4) {
F_Close (dev->io.usbport);
if (mode_flag & NO_RECONNECT) {
log_print ("IRTrans Connection lost. Aborting ...\n",LOG_FATAL);
exit (-1);
}
while (stat) {
log_print ("Trying reconnect ...\n",LOG_DEBUG);
#ifdef WIN32
F_Reload (0x403,0xfc60);
F_Reload (0x403,0xfc61);
Sleep (1000);
#endif
stat = F_OpenEx (dev->usb_serno,FT_OPEN_BY_SERIAL_NUMBER,&dev->io.usbport);
#ifdef WIN32
Sleep (2000);
#endif
if (!stat) log_print ("Reconnected ...\n",LOG_DEBUG);
}
}
}
void SetUSBEventEx (DEVICEINFO *dev,DWORD mask)
{
F_SetEventNotification (dev->io.usbport,mask,dev->io.event);
}
void break_signal (int sig)
{
log_print ("Abort ...\n",LOG_FATAL);
exit (0);
}
#ifdef WIN32
void cleanup_exit (void)
{
#ifndef _STANDALONE
int i;
for (i=0;i < device_cnt;i++) if (IRDevices[i].io.if_type == IF_USB) F_Close (IRDevices[i].io.usbport);
#endif
if (hdll) FreeLibrary(hdll);
}
int LoadUSBLibrary (void)
{
char msg[256];
atexit (cleanup_exit);
signal (SIGINT,break_signal);
hdll = LoadLibrary("Ftd2xx.dll");
if(hdll == NULL)
{
sprintf (msg,"Error: Can't Load ftd2xx.dll\n");
log_print (msg,LOG_FATAL);
return (-1);
}
m_pListDevices = (PtrToListDevices)GetProcAddress(hdll, "FT_ListDevices");
m_pOpen = (PtrToOpen)GetProcAddress(hdll, "FT_Open");
m_pOpenEx = (PtrToOpenEx)GetProcAddress(hdll, "FT_OpenEx");
m_pRead = (PtrToRead)GetProcAddress(hdll, "FT_Read");
m_pClose = (PtrToClose)GetProcAddress(hdll, "FT_Close");
m_pGetQueueStatus = (PtrToGetQueueStatus)GetProcAddress(hdll, "FT_GetQueueStatus");
m_pWrite = (PtrToWrite)GetProcAddress(hdll, "FT_Write");
m_pCyclePort = (PtrToCyclePort)GetProcAddress(hdll, "FT_CyclePort");
m_pReload = (PtrToReload)GetProcAddress(hdll,"FT_Reload");
m_pResetDevice = (PtrToResetDevice)GetProcAddress(hdll, "FT_ResetDevice");
m_pPurge = (PtrToPurge)GetProcAddress(hdll, "FT_Purge");
m_pSetTimeouts = (PtrToSetTimeouts)GetProcAddress(hdll, "FT_SetTimeouts");
m_pSetEvent = (PtrToSetEvent)GetProcAddress(hdll, "FT_SetEventNotification");
m_pGetDeviceInfo = (PtrToGetDeviceInfo)GetProcAddress(hdll, "FT_GetDeviceInfo");
m_pSetLatencyTimer = (PtrToSetLatencyTimer)GetProcAddress(hdll, "FT_SetLatencyTimer");
return (0);
}
enum FT_STATUS F_GetDeviceInfo(FT_HANDLE usb,FT_DEVICE *device,DWORD *id,char *serno,char *desc,PVOID dummy)
{
return (*m_pGetDeviceInfo)(usb, device, id, serno, desc, dummy);
}
enum FT_STATUS F_SetEventNotification(FT_HANDLE usb,DWORD mask,PVOID event)
{
return (*m_pSetEvent)(usb, mask, event);
}
enum FT_STATUS F_ListDevices(PVOID pArg1, PVOID pArg2, DWORD dwFlags)
{
return (*m_pListDevices)(pArg1, pArg2, dwFlags);
}
enum FT_STATUS F_Open(PVOID pvDevice,FT_HANDLE *usb)
{
return (*m_pOpen)(pvDevice, usb );
}
enum FT_STATUS F_OpenEx(PVOID pArg1, DWORD dwFlags,FT_HANDLE *usb)
{
return (*m_pOpenEx)(pArg1, dwFlags, usb);
}
enum FT_STATUS F_Read(FT_HANDLE usb,LPVOID lpvBuffer, DWORD dwBuffSize, LPDWORD lpdwBytesRead)
{
return (*m_pRead)(usb, lpvBuffer, dwBuffSize, lpdwBytesRead);
}
enum FT_STATUS F_Close(FT_HANDLE usb)
{
return (*m_pClose)(usb);
}
enum FT_STATUS F_GetQueueStatus(FT_HANDLE usb,LPDWORD lpdwAmountInRxQueue)
{
return (*m_pGetQueueStatus)(usb, lpdwAmountInRxQueue);
}
enum FT_STATUS F_Write(FT_HANDLE usb,LPVOID lpvBuffer, DWORD dwBuffSize, LPDWORD lpdwBytes)
{
return (*m_pWrite)(usb, lpvBuffer, dwBuffSize, lpdwBytes);
}
enum FT_STATUS F_Reload (WORD wVID, WORD wPID)
{
return (*m_pReload)(wVID, wPID);
}
enum FT_STATUS F_CyclePort(FT_HANDLE usb)
{
return (*m_pCyclePort)(usb);
}
enum FT_STATUS F_ResetDevice(FT_HANDLE usb)
{
return (*m_pResetDevice)(usb);
}
enum FT_STATUS F_Purge(FT_HANDLE usb,ULONG dwMask)
{
return (*m_pPurge)(usb, dwMask);
}
enum FT_STATUS F_SetTimeouts(FT_HANDLE usb,ULONG dwReadTimeout, ULONG dwWriteTimeout)
{
return (*m_pSetTimeouts)(usb, dwReadTimeout, dwWriteTimeout);
}
enum FT_STATUS F_SetLatencyTimer (FT_HANDLE usb, UCHAR ucTimer)
{
return (*m_pSetLatencyTimer)(usb, ucTimer);
}
#endif
|
asterics/IRTrans-Server
|
errormessage.c
|
/*
* Copyright (c) 2007, IRTrans GmbH
* 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.
* * Neither the name of IRTrans GmbH nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY IRTrans GmbH ``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 IRTrans GmbH 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.
*/
#ifdef WIN32
#include "winsock2.h"
#include <windows.h>
#include <time.h>
#include <sys/timeb.h>
#define MSG_NOSIGNAL 0
#endif
#ifdef WINCE
#include "winsock2.h"
#include <windows.h>
#endif
#ifdef LINUX
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdint.h>
#include <time.h>
#include <sys/timeb.h>
#endif
#include <stdio.h>
#include "remote.h"
#include "network.h"
#include "lowlevel.h"
#include "global.h"
#include "server.h"
#include "errcode.h"
#ifdef WIN32
#include "winio.h"
#include "winusbio.h"
#endif
void SwapNetworkheader (NETWORKSTATUS *ns);
void CloseIRSocket (int client);
extern NETWORKCLIENT sockinfo[CLIENT_COUNT];
void log_print (char msg[],int level)
{
FILE *fp;
time_t tv;
int ms = 0;
struct tm *tmpnt;
#ifdef WIN32
struct _timeb tb;
#endif
#ifdef LINUX
struct timeb tb;
#endif
if (logfp) fp = logfp;
else fp = stderr;
if (!fp) return;
if (level > (int)(mode_flag & LOG_MASK)) return;
if (mode_flag & TIMESTAMP) {
tv = time (0);
#ifdef WIN32
_ftime (&tb);
#endif
#ifdef LINUX
ftime (&tb);
#endif
tv = tb.time;
ms = tb.millitm;
tmpnt = localtime (&tv);
fprintf (fp,"%4d-%02d-%02d %02d:%02d:%02d.%03d %s",tmpnt->tm_year+1900,tmpnt->tm_mon+1,tmpnt->tm_mday,tmpnt->tm_hour,tmpnt->tm_min,tmpnt->tm_sec,ms,msg);
}
else fprintf (fp,"%s",msg);
fflush (fp);
// if (level <= LOG_ERROR) NetworkClientMessage (msg,0xffff);
}
void NetworkClientMessage (char msg[],int num)
{
int i,res;
NETWORKLOG nl;
memset (&nl,0,sizeof (NETWORKLOG));
nl.clientid = 0;
nl.statuslen = sizeof (NETWORKLOG);
nl.statustype = STATUS_LOG;
strcpy (nl.message,msg);
SwapNetworkheader ((NETWORKSTATUS *)&nl);
if (num != 0xffff) {
res = send (sockinfo[num].fd,(char *)&nl,sizeof (NETWORKLOG),MSG_NOSIGNAL);
if (res <= 0) CloseIRSocket (num);
}
else {
i = 0;
while (i < CLIENT_COUNT) {
if ((sockinfo[i].type == SELECT_SERVER || sockinfo[i].type == SELECT_REOPEN) && sockinfo[i].msg_mode) {
res = send (sockinfo[i].fd,(char *)&nl,sizeof (NETWORKLOG),MSG_NOSIGNAL);
if (res <= 0) CloseIRSocket (i);
}
i++;
}
}
}
void GetError (int res,char st[])
{
switch (res) {
case ERR_OPEN:
sprintf (st,"Error opening COM/USB Port / LAN Device\n");
break;
case ERR_RESET:
sprintf (st,"No IR Transceiver found (Reset not possible)\n");
break;
case ERR_READVERSION:
sprintf (st,"Could not get Transceiver Version\n");
break;
case ERR_VERSION:
sprintf (st,"Wrong IR Transceiver SW Version. Minimum Version: %s\n",MINIMUM_SW_VERSION);
break;
case ERR_TIMEOUT:
sprintf (st,"Timeout (Connection lost ?)\n");
break;
case ERR_OPENUSB:
sprintf (st,"Error opening USB Device / Device not found\n");
break;
case ERR_DBOPENINPUT:
sprintf (st,"Error opening Database file (Access rights ?)\n");
break;
case ERR_REMOTENOTFOUND:
sprintf (st,"Specified Remote Control [%%s] not found\n");
break;
case ERR_COMMANDNOTFOUND:
sprintf (st,"Specified Remote Command [%%s] not found\n");
break;
case ERR_TIMINGNOTFOUND:
sprintf (st,"Specified Remote Timing not found\n");
break;
case ERR_OPENASCII:
sprintf (st,"Could not create new Remote file (Access rights ?)\n");
break;
case ERR_NODATABASE:
sprintf (st,"Could not open Remote Database (No folder 'remotes' / Access rights ?)\n");
break;
case ERR_TOGGLE_DUP:
sprintf (st,"Could not record Toggle Command (No commands yet learned ?)\n");
break;
case ERR_DBOPENINCLUDE:
sprintf (st,"Specified Include File not found\n");
break;
case ERR_NOFILEOPEN:
sprintf (st,"No Remote opened to learn new commands\n");
break;
case ERR_FLOCK:
sprintf (st,"Could not lock input file (USB / TTY)\n");
break;
case ERR_STTY:
sprintf (st,"Could not set serial parameters\n");
break;
case ERR_OPENSOCKET:
sprintf (st,"Could not open IP socket\n");
break;
case ERR_BINDSOCKET:
sprintf (st,"Could not bind to IP socket (Another server running ?)\n");
break;
case ERR_HOTCODE:
sprintf (st,"Hotcode %%s-%%s not found\n");
break;
case ERR_NOTIMING:
sprintf (st,"No timing learned for new commands\n");
break;
case ERR_TEMPCOMMAND:
sprintf (st,"Illegal Temparature Command: %%s\n");
break;
case ERR_OPENTRANS:
sprintf (st,"Error opening translation table file\n");
break;
case ERR_WRONGBUS:
sprintf (st,"Specified Bus does not exist\n");
break;
case ERR_ISMACRO:
sprintf (st,"Cannot get the Device Data for a macro\n");
break;
case ERR_DEVICEUNKNOWN:
sprintf (st,"IR Code received from unknown device: %%s\n");
break;
case ERR_BINDWEB:
sprintf (st,"Cannot bind to Web Port. Another Webserver running ? Try -no_web.\n");
break;
case ERR_OVERWRITE:
sprintf (st,"File already exists. Overwrite ?\n");
break;
case ERR_NO_RS232:
sprintf (st,"No IRTrans Device with AUX RS232 port connected\n");
break;
case ERR_CCF:
sprintf (st,"Illegal CCF Code\n");
break;
case ERR_CCFSYNTAX:
sprintf (st,"Syntax Error in CCF Code\n");
break;
case ERR_CCFLEN:
sprintf (st,"Wrong CCF Code length\n");
break;
case ERR_SSID_WLAN:
sprintf (st,"WLAN Radio status can only be retrieved via USB\n");
break;
case ERR_LEARN_LENGTH:
sprintf (st,"IR Code length > max. length - Code might not work\n");
break;
case ERR_LEARN_RAWLEN:
sprintf (st,"IR RAW Code length > max. length - Code might not work\n");
break;
case ERR_LEARN_TIMECNT:
sprintf (st,"Number of timings to large - use RAW Code - Code might not work\n");
break;
case ERR_LEARN_TC_LEN:
sprintf (st,"IR Code too long for large number of timings - Code might not work\n");
break;
case ERR_SEND_LED:
sprintf (st,"Selected IR Output does not exist\n");
break;
case ERR_OUTPUT_BUSY:
sprintf (st,"IR Output Busy\n");
break;
case ERR_MACRO_LENGTH:
sprintf (st,"Resulting Macro data too long\n");
break;
case ERR_MACRO_COUNT:
sprintf (st,"More than 10 commands in the Macro\n");
break;
case ERR_NO_MACRO:
sprintf (st,"Selected IRTrans device does not support Macros\n");
break;
case ERR_LONGCODE:
sprintf (st,"IR Code length not supported by this device\n");
break;
case ERR_IRCODE_LENGTH:
sprintf (st,"Illegal IR Code length\n");
break;
case ERR_IRCODE_TIMING:
sprintf (st,"Illegal IR Timing\n");
break;
case ERR_IRCODE_DATA:
sprintf (st,"IR Code does not match IR Timings\n");
break;
case ERR_NOSTATEINPUT:
sprintf (st,"No State Input for this IR Output defined\n");
break;
default:
sprintf (st,"Error %d\n",res);
break;
}
}
|
asterics/IRTrans-Server
|
hid.c
|
/*
* Copyright (c) 2007, IRTrans GmbH
* 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.
* * Neither the name of IRTrans GmbH nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY IRTrans GmbH ``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 IRTrans GmbH 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.
*/
#ifdef WIN32
#define _WIN32_WINNT 0x501
#ifndef VC6
#include "winsock2.h"
#endif
#include <windows.h>
#include <winuser.h>
#include <io.h>
#include <direct.h>
#include <stdio.h>
#include <sys/timeb.h>
#include "remote.h"
#include "global.h"
#include "network.h"
#include "lowlevel.h"
#include "dbstruct.h"
#include "fileio.h"
#endif
void KeyboardInput (char code[]);
void EnterKeyboardInput (byte reset);
void MouseInput (char code[]);
#define S_MOD_CTRL 1
#define S_MOD_SHIFT 2
#define S_MOD_ALT 4
static byte mod_flags;
static byte last_mods;
static byte keys[10];
static byte flags[10];
static byte keynum;
void HandleHID (int rem_num,int com_num,char rname[],char xcode[])
{
word relc;
char st[200],rem[100],name[30],code[200];
int start_pos,cnum,rnum;
sprintf (st,"HID: %s\n",xcode);
log_print (st,LOG_DEBUG);
strcpy (code,xcode);
if (!strcmp (rname,"kb") || !strcmp (rname,"kx") || !strcmp (rname,"rm")) {
if (strlen (code) > 11) { // Keyboard / Remote
strcpy (st,code+10);
st[0] = 'C';
while (strlen (st) >= 10) {
start_pos = DBFindCommandName (st,rem,name,0,&rnum,&cnum,&relc,com_num);
if (start_pos && rnum == rem_num) {
KeyboardInput (name);
}
strcpy (code,st);
strcpy (st,code+8);
st[0] = 'C';
}
}
else EnterKeyboardInput (1);
EnterKeyboardInput (0);
}
else if (!strcmp (rname,"power")) EnterKeyboardInput (0);
else if (!strcmp (rname,"pt") || !strcmp (rname,"px")) { // Maus
if (strlen (code) > 11) MouseInput (code + 11);
else MouseInput ("000");
}
}
#define MOUSE_SPEED 1.2
#define MOUSE_ACCEL 1.02
#define ACCEL_MAX 20
#define ACCEL_TIMEOUT 2
#define ACCEL_INC 0.5
#define ACCEL_START 1
#define ACCEL_START_INC 0.1
void MouseInput (char code[])
{
static byte last_m1,last_m2;
static float accel_x,accel_y;
static unsigned long accel_timer;
char st[100];
byte m1,m2;
int p = 0;
INPUT InpInfo[20];
char x = 0,y = 0;
unsigned long tv;
struct _timeb tb;
m1 = code[2] - '0';
m2 = code[1] - '0';
_ftime (&tb);
tv = tb.time * 10 + tb.millitm / 100;
if (tv > accel_timer) accel_x = accel_y = 0;
if (strlen (code) > 4) {
memset (st,0,10);
memcpy (st,code+3,8);
x = (char)strtoul (st,NULL,2);
memset (st,0,10);
memcpy (st,code+11,8);
y = (char)strtoul (st,NULL,2);
}
p = 0;
memset (InpInfo,0,sizeof (InpInfo));
if (last_m1 != m1) {
InpInfo[p].type = INPUT_MOUSE;
if (m1) InpInfo[p].mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
else InpInfo[p].mi.dwFlags = MOUSEEVENTF_LEFTUP;
p++;
}
if (last_m2 != m2) {
InpInfo[p].type = INPUT_MOUSE;
if (m1) InpInfo[p].mi.dwFlags = MOUSEEVENTF_RIGHTDOWN;
else InpInfo[p].mi.dwFlags = MOUSEEVENTF_RIGHTUP;
p++;
}
if (x || y) {
InpInfo[p].type = INPUT_MOUSE;
InpInfo[p].mi.dx = (long)((x + (long)(x * MOUSE_ACCEL * accel_x)) * MOUSE_SPEED);
InpInfo[p].mi.dy = (long)((y + (long)(y * MOUSE_ACCEL * accel_y)) * MOUSE_SPEED);
InpInfo[p].mi.dwFlags = MOUSEEVENTF_MOVE;
if (x && accel_x < ACCEL_START) {
accel_x += (float)ACCEL_START_INC;
}
else {
if (x && accel_x < ACCEL_MAX) accel_x += ACCEL_INC;
}
if (y && accel_y < ACCEL_START) {
accel_y += (float)ACCEL_START_INC;
}
else {
if (y && accel_y < ACCEL_MAX) accel_y += ACCEL_INC;
}
p++;
sprintf (st,"HID Mouse: %d [%f],%d [%f]\n",x,accel_x,y,accel_y);
log_print (st,LOG_DEBUG);
}
if (p) {
SystemParametersInfo (0x1027,FALSE,NULL,0); //turn off screensaver
SetThreadExecutionState (ES_DISPLAY_REQUIRED | ES_SYSTEM_REQUIRED); //reset idle timers
SendInput (p,InpInfo,sizeof (INPUT));
}
last_m1 = m1;
last_m2 = m2;
accel_timer = tv + ACCEL_TIMEOUT;
}
void KeyboardInput (char code[])
{
int key,flg = 0;
if (!strcmp (code,"ctrl")) mod_flags |= S_MOD_CTRL;
else if (!strcmp (code,"shift")) mod_flags |= S_MOD_SHIFT;
else if (!strcmp (code,"alt")) mod_flags |= S_MOD_ALT;
else if (!strcmp (code,"altgr")) mod_flags |= S_MOD_ALT | S_MOD_CTRL;
else {
if (code[1] == 0) {
if (*code >= 'a' && *code <= 'z') *code -= ('a' - 'A');
key = *code;
}
else if (*code == 'c') key = atoi (code + 1);
else if (*code == 'e') {
key = atoi (code + 1);
flg = KEYEVENTF_EXTENDEDKEY;
}
else return;
keys[keynum] = key;
flags[keynum++] = flg;
}
}
void EnterKeyboardInput (byte reset)
{
int p,i;
char st[100];
INPUT InpInfo[20];
HWINSTA hwinsta;
HDESK hdesk;
memset (InpInfo,0,sizeof (InpInfo));
if (reset) {
mod_flags = 0;
last_mods = S_MOD_ALT | S_MOD_CTRL | S_MOD_SHIFT;
keynum = 0;
}
if (mode_flag & DAEMON_MODE) {
if (mod_flags == (S_MOD_ALT | S_MOD_CTRL) && keynum == 1 && keys[0] == VK_DELETE) {
p = 0;
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_LSHIFT;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
p++;
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_LCONTROL;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
p++;
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_MENU;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
p++;
keynum = 0;
last_mods = 0;
mod_flags = 0;
SendInput (p,InpInfo,sizeof (INPUT));
hwinsta = OpenWindowStation("winsta0", FALSE,
WINSTA_ACCESSCLIPBOARD |
WINSTA_ACCESSGLOBALATOMS |
WINSTA_CREATEDESKTOP |
WINSTA_ENUMDESKTOPS |
WINSTA_ENUMERATE |
WINSTA_EXITWINDOWS |
WINSTA_READATTRIBUTES |
WINSTA_READSCREEN |
WINSTA_WRITEATTRIBUTES);
if (hwinsta == NULL) return;
if (!SetProcessWindowStation(hwinsta)) return;
hdesk = OpenDesktop("Winlogon", 0, FALSE,
DESKTOP_CREATEMENU |
DESKTOP_CREATEWINDOW |
DESKTOP_ENUMERATE |
DESKTOP_HOOKCONTROL |
DESKTOP_JOURNALPLAYBACK |
DESKTOP_JOURNALRECORD |
DESKTOP_READOBJECTS |
DESKTOP_SWITCHDESKTOP |
DESKTOP_WRITEOBJECTS);
if (hdesk == NULL) return;
if (!SetThreadDesktop(hdesk)) return;
PostMessage(HWND_BROADCAST,WM_HOTKEY,0,MAKELPARAM(MOD_ALT|MOD_CONTROL,VK_DELETE));
return;
}
hdesk = OpenInputDesktop(0, FALSE,
DESKTOP_CREATEMENU |
DESKTOP_CREATEWINDOW |
DESKTOP_ENUMERATE |
DESKTOP_HOOKCONTROL |
DESKTOP_JOURNALPLAYBACK |
DESKTOP_JOURNALRECORD |
DESKTOP_READOBJECTS |
DESKTOP_SWITCHDESKTOP |
DESKTOP_WRITEOBJECTS);
if (hdesk == NULL) return;
SetThreadDesktop(hdesk);
}
p = 0;
if (mod_flags & S_MOD_SHIFT && !(last_mods & S_MOD_SHIFT)) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_LSHIFT;
p++;
}
if (mod_flags & S_MOD_CTRL && !(last_mods & S_MOD_CTRL)) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_LCONTROL;
p++;
}
if (mod_flags & S_MOD_ALT && !(last_mods & S_MOD_ALT)) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_MENU;
p++;
}
if (!(mod_flags & S_MOD_SHIFT) && last_mods & S_MOD_SHIFT) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_LSHIFT;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
p++;
}
if (!(mod_flags & S_MOD_CTRL) && last_mods & S_MOD_CTRL) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_LCONTROL;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
p++;
}
if (!(mod_flags & S_MOD_ALT) && last_mods & S_MOD_ALT) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_MENU;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
p++;
}
for (i=0;i < keynum;i++) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = keys[i];
InpInfo[p].ki.dwFlags = flags[i];
p++;
}
for (i=0;i < keynum;i++) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP | flags[i];
InpInfo[p].ki.wVk = keys[i];
p++;
}
sprintf (st,"HID Input Count: %d\n",keynum);
log_print (st,LOG_DEBUG);
keynum = 0;
SystemParametersInfo (0x1027,FALSE,NULL,0); //turn off screensaver
SetThreadExecutionState (ES_DISPLAY_REQUIRED | ES_SYSTEM_REQUIRED); //reset idle timers
SendInput (p,InpInfo,sizeof (INPUT));
last_mods = mod_flags;
mod_flags = 0;
if (mode_flag & DAEMON_MODE) {
CloseDesktop (hdesk);
}
}
|
asterics/IRTrans-Server
|
global.h
|
<reponame>asterics/IRTrans-Server<filename>global.h
/*
* Copyright (c) 2007, IRTrans GmbH
* 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.
* * Neither the name of IRTrans GmbH nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY IRTrans GmbH ``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 IRTrans GmbH 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 "functioncodes.h"
#define LOG_DEBUG 4
#define LOG_INFO 3
#define LOG_ERROR 2
#define LOG_FATAL 1
#define LOG_MASK 15
#define DEBUG_CODE 16
#define HEXDUMP 32
#define OLDFORMAT 64
#define CODEDUMP 128
#define LEARNED_ONLY 256
#define XAP 512
#define MEDIALON 1024
#define TIMESTAMP 2048
#define READHTML 4096
#define DAEMON_MODE 0x10000
#define NO_RECONNECT 0x20000
#define NO_RESET 0x40000
#define NO_LIRC 0x80000
#define NO_WEB 0x100000
#define CLOCK_STARTUP 0x200000
#define READ_EEPROM 0x400000
#define NO_CLOCK 0x800000
#define IP_RELAY 0x1000000
#define SEND_FORWARD 0x2000000
#define SEND_FORWARDALL 0x4000000
#define NO_INIT_LAN 0x8000000
#define DEBUG_TIMING 0x10000000
#define PARAMETER_FILE 0x20000000
#define ETHERNET_TCP 0x40000000
#define TCP_RECONNECT 0x80000000
#define TYPE_MCE 1
#define TYPE_KEY 2
#define TYPE_RUN 3
#define TYPE_APPCOM 4
#define TYPE_COM 5
#define TYPE_CHR 6
#define TYPE_KEYF 7
#define TYPE_KEYBOARD 8
#define TYPE_SCANCODE 9
#define TYPE_MOUSE 10
#define TYPE_SHORTCUT 11
#define TYPE_XBMC 12
#define TYPE_STR 13
#define TYPE_XBMC_BUTTON 14
#define TYPE_XBMC_ACTION 15
#define TYPE_XBMC_ACTION_BUILTIN 16
#define SELECT_TRANS 1
#define SELECT_SERVER 2
#define SELECT_LIRC 3
#define SELECT_LOCAL 4
#define SELECT_COMMAND 5
#define SELECT_REOPEN 6
#define SELECT_WEB 7
#define SELECT_UDP 8
#define SELECT_XAP 9
#define SELECT_IRTLAN 10
#define SELECT_CLIENT 11
#define SELECT_RS232 12
#define SELECT_LAN_TCP 13
#define COMMAND_SERVER 102
#define COMMAND_LIRC 103
#define COMMAND_LOCAL 104
#define COMMAND_REOPEN 106
extern unsigned int mode_flag;
extern char logfile[256];
extern FILE *logfp;
extern char irserver_version[20];
extern char irtrans_version[100];
extern byte last_adress,resend_flag;
extern unsigned short capabilities;
extern unsigned short capabilities2;
extern unsigned short capabilities3;
extern unsigned short capabilities4;
extern byte time_len;
extern byte raw_repeat;
extern char err_remote[81];
extern char err_command[21];
#ifdef LINUX
#define INVALID_HANDLE_VALUE -1
#endif
void XBMC_SendBye ();
void XBMC_SendPing ();
int InitXBMC (void);
int BuildXBMCHeader (byte *data,short type,int payload_len);
int BuildXBMCHelo (byte *data,char *name);
int BuildXBMCKey (byte *data,char *button);
int BuildXBMCAction (byte *data,byte type,char *action);
#ifdef WIN32
void PostWindowsMessage (int rem,int com,char name[]);
/* cmd for HSHELL_APPCOMMAND and WM_APPCOMMAND */
#define APPCOMMAND_BROWSER_BACKWARD 1
#define APPCOMMAND_BROWSER_FORWARD 2
#define APPCOMMAND_BROWSER_REFRESH 3
#define APPCOMMAND_BROWSER_STOP 4
#define APPCOMMAND_BROWSER_SEARCH 5
#define APPCOMMAND_BROWSER_FAVORITES 6
#define APPCOMMAND_BROWSER_HOME 7
#define APPCOMMAND_VOLUME_MUTE 8
#define APPCOMMAND_VOLUME_DOWN 9
#define APPCOMMAND_VOLUME_UP 10
#define APPCOMMAND_MEDIA_NEXTTRACK 11
#define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
#define APPCOMMAND_MEDIA_STOP 13
#define APPCOMMAND_MEDIA_PLAY_PAUSE 14
#define APPCOMMAND_LAUNCH_MAIL 15
#define APPCOMMAND_LAUNCH_MEDIA_SELECT 16
#define APPCOMMAND_LAUNCH_APP1 17
#define APPCOMMAND_LAUNCH_APP2 18
#define APPCOMMAND_BASS_DOWN 19
#define APPCOMMAND_BASS_BOOST 20
#define APPCOMMAND_BASS_UP 21
#define APPCOMMAND_TREBLE_DOWN 22
#define APPCOMMAND_TREBLE_UP 23
#define APPCOMMAND_MICROPHONE_VOLUME_MUTE 24
#define APPCOMMAND_MICROPHONE_VOLUME_DOWN 25
#define APPCOMMAND_MICROPHONE_VOLUME_UP 26
#define APPCOMMAND_HELP 27
#define APPCOMMAND_FIND 28
#define APPCOMMAND_NEW 29
#define APPCOMMAND_OPEN 30
#define APPCOMMAND_CLOSE 31
#define APPCOMMAND_SAVE 32
#define APPCOMMAND_PRINT 33
#define APPCOMMAND_UNDO 34
#define APPCOMMAND_REDO 35
#define APPCOMMAND_COPY 36
#define APPCOMMAND_CUT 37
#define APPCOMMAND_PASTE 38
#define APPCOMMAND_REPLY_TO_MAIL 39
#define APPCOMMAND_FORWARD_MAIL 40
#define APPCOMMAND_SEND_MAIL 41
#define APPCOMMAND_SPELL_CHECK 42
#define APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE 43
#define APPCOMMAND_MIC_ON_OFF_TOGGLE 44
#define APPCOMMAND_CORRECTION_LIST 45
#define APPCOMMAND_MEDIA_PLAY 46
#define APPCOMMAND_MEDIA_PAUSE 47
#define APPCOMMAND_MEDIA_RECORD 48
#define APPCOMMAND_MEDIA_FAST_FORWARD 49
#define APPCOMMAND_MEDIA_REWIND 50
#define APPCOMMAND_MEDIA_CHANNEL_UP 51
#define APPCOMMAND_MEDIA_CHANNEL_DOWN 52
#define WM_APPCOMMAND 0x0319
#endif
|
asterics/IRTrans-Server
|
webserver.c
|
/*
* Copyright (c) 2007, IRTrans GmbH
* 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.
* * Neither the name of IRTrans GmbH nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY IRTrans GmbH ``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 IRTrans GmbH 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.
*/
#ifdef WIN32
#include <winsock2.h>
#include <windows.h>
#include <io.h>
#include <direct.h>
#define MSG_NOSIGNAL 0
#endif
#ifdef WINCE
#include <winsock2.h>
#include <windows.h>
#define MSG_NOSIGNAL 0
#endif
#ifdef LINUX
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdint.h>
typedef int DWORD;
#define closesocket close
extern int hCom;
#endif
#include <stdio.h>
#include <time.h>
#include "pictures.h"
#include "remote.h"
#include "network.h"
#include "errcode.h"
#include "dbstruct.h"
#include "global.h"
#include "server.h"
#include "lowlevel.h"
#include "fileio.h"
#include "webserver.h"
#ifdef WIN32
extern WSAEVENT WebEvent;
#endif
void ProcessWebRequest (SOCKET sock)
{
int res;
char data[2048];
SOCKET call;
int clilen;
unsigned int adr;
struct sockaddr_in cli_addr;
clilen = sizeof (cli_addr);
call = accept (sock,(struct sockaddr *)&cli_addr,&clilen);
#ifdef WIN32
adr = ntohl (cli_addr.sin_addr.S_un.S_addr);
#else
adr = ntohl (cli_addr.sin_addr.s_addr);
#endif
if (adr != 0x7f000001) {
for (res=0;res < netcount;res++) {
if ((netip[res] & netmask[res]) == (adr & netmask[res])) break;
}
if (netcount && res == netcount) {
sprintf (data,"Error: IP Address %s not allowed (Access rights).\n",inet_ntoa (cli_addr.sin_addr));
log_print (data,LOG_ERROR);
shutdown (call,2);
closesocket (call);
return;
}
}
#ifdef WIN32
res = 0;
WSAEventSelect (call,WebEvent,0);
ioctlsocket (call,FIONBIO,&res);
#endif
res = recv (call,data,2048,MSG_NOSIGNAL);
data[res] = 0;
ParseRequest (data,call);
}
void ParseRequest (char* data,SOCKET sock)
{
char mem[65536];
int len;
if (!strncmp (data,"GET ",4)) {
len = GetHtmlPage (mem,data + 4);
send (sock,mem,len,0);
closesocket (sock);
}
}
int GetHtmlPage (char *mem,char *page)
{
int i = 0;
char content[65536];
char parm[2050];
char value[2050];
char lang[10];
while (page[i] > ' ') i++;
page[i] = 0;
*parm = 0;
for (i=0;page[i] && page[i] != '?';i++);
if (page[i] == '?') {
page[i++] = 0;
page[i + 2048] = 0;
strcpy (parm,page + i);
}
GetHtmlParameter (parm,"lang",value);
value[8] = 0;
strcpy (lang,value);
if (*lang == 0) strcpy (lang,"EN");
printf ("%s\n",page);
if (!strcmp (page,"/") || !strcmp (page,"/index.htm") || !strcmp (page,"/index.html")) {
GetIndexPage (content,lang);
GenerateHtmlHeader (mem,content);
return ((int)strlen (mem));
}
if (!strcmp (page,"/DeviceList.htm")) {
GetDevicesPage (content,lang,NULL);
GenerateHtmlHeader (mem,content);
return ((int)strlen (mem));
}
if (!strcmp (page,"/DeviceConfig.htm")) {
GetHtmlParameter (parm,"id",value);
i = atoi (value);
if (i < 0 || i > 15) i = 0;
GetDeviceConfigPage (content,lang,i);
GenerateHtmlHeader (mem,content);
return ((int)strlen (mem));
}
if (!strcmp (page,"/SetConfig.htm")) {
GetDevicesPage (content,lang,parm);
GenerateHtmlHeader (mem,content);
return ((int)strlen (mem));
}
if (!strcmp (page,"/Send.htm")) {
GetSendPage (content,lang,parm);
GenerateHtmlHeader (mem,content);
return ((int)strlen (mem));
}
if (!strcmp (page,"/IRTransLogo.gif")) return (GenerateImageHeader (mem,irtrans_logo,"gif",sizeof (irtrans_logo)));
if (!strcmp (page,"/OKButton.gif")) return (GenerateImageHeader (mem,ok_button,"gif",sizeof (ok_button)));
if (!strcmp (page,"/GoButton.gif")) return (GenerateImageHeader (mem,go_button,"gif",sizeof (go_button)));
if (!strcmp (page,"/English.jpg")) return (GenerateImageHeader (mem,england_logo,"jpeg",sizeof (england_logo)));
if (!strcmp (page,"/Deutsch.jpg")) return (GenerateImageHeader (mem,deutschland_logo,"jpeg",sizeof (deutschland_logo)));
if (!strcmp (page,"/BackButton.gif")) return (GenerateImageHeader (mem,back_button,"gif",sizeof (back_button)));
GenerateErrorPage (mem,404);
return ((int)strlen (mem));
}
void GetHtmlParameter (char *pnt,char *name,char *value)
{
char parm[2050];
int i = 0,j;
*value = 0;
strcpy (parm,pnt);
while (parm[i]) {
j = i;
while (parm[i] && parm[i] != '=' && parm[i] != '?' && parm[i] != '&') i++;
if (!parm[i]) return;
if (parm[i] == '=') {
parm[i++] = 0;
if (!strcmp (name,parm+j)) {
j = i;
while (parm[i] && parm[i] != '?' && parm[i] != '&') i++;
parm[i] = 0;
strcpy (value,parm+j);
}
while (parm[i] && parm[i] != '?' && parm[i] != '&') i++;
}
if (parm[i] == '?' || parm[i] == '&') i++;
}
}
void GetSendPage (char *mem,char *lang,char *parm)
{
int res,mask,setres = 0;
int cmd_num;
char err[1000];
char value[1000];
char ln[1000];
char remote[100],command[100];
STATUSBUFFER stat;
NETWORKSTATUS *ns;
strcpy (mem,"<HTML><HEAD><TITLE>IRTrans Send Command</TITLE></HEAD><BODY bgcolor=\"#C0C0C0\">");
strcat (mem,"<table width=\"80%\"><tr><td align = \"center\">");
strcat (mem,"<IMG src=\"IRTransLogo.gif\" align = \"center\">");
strcat (mem,"</td><td width=\"40\"> </td><td align = \"center\"><font face=\"Verdana\" size=\"4\">IRTrans Send Command</font></td><td>");
sprintf (ln,"<a href=\"index.htm?lang=%s\">",lang);
strcat (mem,ln);
strcat (mem,"<IMG src=\"BackButton.gif\" align = \"center\" border=\"0\"></a></td></tr></table><hr><br>");
if (parm) {
mask = 0;
GetHtmlParameter (parm,"remote",remote);
GetHtmlParameter (parm,"command",command);
GetHtmlParameter (parm,"sendmask",value);
sscanf (value,"%x",&mask);
if (*remote && *command) {
res = DBFindRemoteCommand (remote,command,&cmd_num,NULL);
if (res) {
ns = (NETWORKSTATUS *)&stat;
PutNetworkStatus (res,NULL,&stat);
strcpy (err,ns->message);
if (res == ERR_REMOTENOTFOUND) sprintf (ns->message,err,remote);
if (res == ERR_COMMANDNOTFOUND) sprintf (ns->message,err,command);
strcat (mem,"<p align=\"center\"><font face=\"Verdana\" size=\"4\">");
strcat (mem,ns->message);
strcat (mem,"</p></font>");
}
else {
if (mask) mask = ((word)mask & 0xffff) | 0x10000;
SendIR (cmd_num,mask,COMMAND_SEND,NULL);
}
resend_flag = 0;
return;
}
}
}
void GetDeviceConfigPage (char *mem,char *lang,int id)
{
int res,i;
char ln[1000];
STATUSBUFFER buf;
NETWORKMODE *status;
strcpy (mem,"<HTML><HEAD><TITLE>IRTrans Device Status</TITLE></HEAD><BODY bgcolor=\"#C0C0C0\">");
strcat (mem,"<table width=\"80%\"><tr><td align = \"center\">");
strcat (mem,"<IMG src=\"IRTransLogo.gif\" align = \"center\">");
strcat (mem,"</td><td width=\"40\"> </td><td align = \"center\"><font face=\"Verdana\" size=\"4\">IRTrans Device Configuration</font></td><td>");
sprintf (ln,"<a href=\"DeviceList.htm?lang=%s\">",lang);
strcat (mem,ln);
strcat (mem,"<IMG src=\"BackButton.gif\" align = \"center\" border=\"0\"></a></td></tr></table><hr><br>");
res = GetDeviceStatus (&buf);
if (res) {
}
else {
status = (NETWORKMODE *)&buf;
strcat (mem,"<font face=\"Verdana\" size=\"3\"><table><tr><td width=\"20\"> </td><td>");
sprintf (ln,"Configuring IRTrans Device ID %d:</td></tr>",id);
if (!strcmp (lang,"DE")) sprintf (ln,"IRTrans mit ID %d wird konfiguriert:</td></tr>",id);
strcat (mem,ln);
strcat (mem,"</table>");
strcat (mem,"<font face=\"Verdana\" size=\"3\"><form method=\"GET\" action=\"SetConfig.htm\"><table><tr><td width=\"20\"> </td>");
strcat (mem,"<td>Target Mask</td></tr><tr><td width=\"20\"> </td><td>");
sprintf (ln,"<input type=\"hidden\" value=\"%d\" name=\"id\">",id);
strcat (mem,ln);
for (i=0; i<=15; i++) {
if (status->stat[id].send_mask & (1 << i)) sprintf (ln,"<input type=\"checkbox\" name=\"TM%02d\" value=\"%d\" checked>%d",i,1<<i,i);
else sprintf (ln,"<input type=\"checkbox\" name=\"TM%02d\" value=\"%d\">%d",i,1<<i,i);
strcat (mem,ln);
}
strcat (mem,"</td></tr><tr><td> </td></tr>");
strcat (mem,"<tr><td width=\"20\"> </td><td><table width=\"100%\"><tr><td>");
sprintf (ln,"<input type=\"checkbox\" name=\"DEVMODE_SEND\" value=\"%d\" %s>IR Send",DEVMODE_SEND,(status->stat[id].device_mode & DEVMODE_SEND ? "checked":""));
if (!strcmp (lang,"DE")) sprintf (ln,"<input type=\"checkbox\" name=\"SEND\" value=\"%d\" %s>IR Senden",DEVMODE_SEND,(status->stat[id].device_mode & DEVMODE_SEND ? "checked":""));
strcat (mem,ln);
strcat (mem,"</td>");
strcat (mem,"<td>");
sprintf (ln,"<input type=\"checkbox\" name=\"DEVMODE_IR\" value=\"%d\" %s>IR Receive",DEVMODE_IR,(status->stat[id].device_mode & DEVMODE_IR ? "checked":""));
if (!strcmp (lang,"DE")) sprintf (ln,"<input type=\"checkbox\" name=\"RECEIVE\" value=\"%d\" %s>IR Empfangen",DEVMODE_IR,(status->stat[id].device_mode & DEVMODE_IR ? "checked":""));
strcat (mem,ln);
strcat (mem,"</td></tr>");
strcat (mem,"<tr><td>");
sprintf (ln,"<input type=\"checkbox\" name=\"DEVMODE_REPEAT\" value=\"%d\" %s>Repeat Mode",DEVMODE_REPEAT,(status->stat[id].device_mode & DEVMODE_REPEAT ? "checked":""));
if (!strcmp (lang,"DE")) sprintf (ln,"<input type=\"checkbox\" name=\"REPEAT\" value=\"%d\" %s>Repeat Modus",DEVMODE_REPEAT,(status->stat[id].device_mode & DEVMODE_REPEAT ? "checked":""));
strcat (mem,ln);
strcat (mem,"</td>");
strcat (mem,"<td>");
sprintf (ln,"<input type=\"checkbox\" name=\"DEVMODE_SBUS\" value=\"%d\" %s>SBUS Active",DEVMODE_SBUS,(status->stat[id].device_mode & DEVMODE_SBUS ? "checked":""));
if (!strcmp (lang,"DE")) sprintf (ln,"<input type=\"checkbox\" name=\"SBUS\" value=\"%d\" %s>SBUS aktivieren",DEVMODE_SBUS,(status->stat[id].device_mode & DEVMODE_SBUS ? "checked":""));
strcat (mem,ln);
strcat (mem,"</td></tr>");
/* strcat (mem,"<tr><td>");
sprintf (ln,"<input type=\"checkbox\" name=\"DEVMODE_IRCODE\" value=\"%d\" %s>Remote Control IR",DEVMODE_IRCODE,(status->stat[id].device_mode & DEVMODE_IRCODE ? "checked":""));
if (!strcmp (lang,"DE")) sprintf (ln,"<input type=\"checkbox\" name=\"RCIR\" value=\"%d\" %s>PC über IR steuern",DEVMODE_IRCODE,(status->stat[id].device_mode & DEVMODE_IRCODE ? "checked":""));
strcat (mem,ln);
strcat (mem,"</td>");*/
strcat (mem,"<td>");
sprintf (ln,"<input type=\"checkbox\" name=\"DEVMODE_SBUSCODE\" value=\"%d\" %s>Remote Control SBUS",DEVMODE_SBUSCODE,(status->stat[id].device_mode & DEVMODE_SBUSCODE ? "checked":""));
if (!strcmp (lang,"DE")) sprintf (ln,"<input type=\"checkbox\" name=\"RCSBUS\" value=\"%d\" %s>PC über SBUS steuern",DEVMODE_SBUSCODE,(status->stat[id].device_mode & DEVMODE_SBUSCODE ? "checked":""));
strcat (mem,ln);
strcat (mem,"</td></tr>");
sprintf (ln,"<input type=\"checkbox\" name=\"DEVMODE_RAW\" value=\"%d\" %s>RAW Mode",DEVMODE_RAW,(status->stat[id].device_mode & DEVMODE_RAW ? "checked":""));
if (!strcmp (lang,"DE")) sprintf (ln,"<input type=\"checkbox\" name=\"RAW\" value=\"%d\" %s>RAW Modus",DEVMODE_RAW,(status->stat[id].device_mode & DEVMODE_RAW ? "checked":""));
strcat (mem,ln);
strcat (mem,"</td></tr>");
strcat (mem,"<tr><td>");
sprintf (ln,"Hotremote <input type=\"text\" name=\"Remote\" value=\"%s\" size=\"20\"> ",status->stat[id].remote);
if (!strcmp (lang,"DE")) sprintf (ln,"PowerOn FB <input type=\"text\" name=\"Remote\" value=\"%s\" size=\"20\"> ",status->stat[id].remote);
strcat (mem,ln);
strcat (mem,"</td>");
strcat (mem,"<td>");
sprintf (ln,"Hotcommand <input type=\"text\" name=\"Command\" value=\"%s\" size=\"20\">",status->stat[id].command);
if (!strcmp (lang,"DE")) sprintf (ln,"PowerOn Befehl <input type=\"text\" name=\"Command\" value=\"%s\" size=\"20\">",status->stat[id].command);
strcat (mem,ln);
strcat (mem,"</td></tr>");
strcat (mem,"<tr><td> ");
strcat (mem,"</td></tr>");
strcat (mem,"<tr><td> ");
strcat (mem,"</td></tr>");
strcat (mem,"<tr><td align=\"center\">");
// strcat (mem,"<input type=\"submit\" value=\"Werte setzen\" name=\"SET\">");
strcat (mem,"</td>");
strcat (mem,"<td align=\"center\">");
// strcat (mem,"<input type=\"reset\">");
strcat (mem,"</td></tr>");
strcat (mem,"</table></td></tr>");
strcat (mem,"</table></form>");
}
strcat (mem,"<br><br><br><br>");
strcat (mem,"<p align=\"center\"><font face=\"Verdana\" size=\"3\">");
sprintf (ln,"IRServer %s (c) 2003 <NAME>üller</font></p>",irserver_version);
strcat (mem,ln);
strcat (mem,"</BODY></HTML>");
}
void GetDevicesPage (char *mem,char *lang,char *parm)
{
int res,cnt,i,id,setres = 0;
word tm;
byte md;
char err[1000];
char nm[100];
char value[1000];
char ln[1000];
char remote[100],command[100];
STATUSBUFFER buf;
NETWORKMODE *status;
strcpy (mem,"<HTML><HEAD><TITLE>IRTrans Device Status</TITLE></HEAD><BODY bgcolor=\"#C0C0C0\">");
strcat (mem,"<table width=\"80%\"><tr><td align = \"center\">");
strcat (mem,"<IMG src=\"IRTransLogo.gif\" align = \"center\">");
strcat (mem,"</td><td width=\"40\"> </td><td align = \"center\"><font face=\"Verdana\" size=\"4\">IRTrans Device Status</font></td><td>");
sprintf (ln,"<a href=\"index.htm?lang=%s\">",lang);
strcat (mem,ln);
strcat (mem,"<IMG src=\"BackButton.gif\" align = \"center\" border=\"0\"></a></td></tr></table><hr><br>");
status = (NETWORKMODE *)&buf;
res = GetDeviceStatus (&buf);
if (res) {
}
else {
if (parm) {
GetHtmlParameter (parm,"id",value);
id = atoi (value);
if (*value == 0 || id < 0 || id > 15) {
setres = -1;
strcpy (err,"Can not set status: Illegal Device ID");
if (!strcmp (lang,"DE")) strcpy (err,"Status kann nicht gesetzt werden: Illegale Device ID");
}
else {
tm = 0;
for (i=0;i<=15;i++) {
sprintf (nm,"TM%02d",i);
GetHtmlParameter (parm,nm,value);
tm += atoi (value);
}
md = 0;
GetHtmlParameter (parm,"DEVMODE_SEND",value);
md += atoi (value);
GetHtmlParameter (parm,"DEVMODE_IR",value);
md += atoi (value);
GetHtmlParameter (parm,"DEVMODE_SBUS",value);
md += atoi (value);
GetHtmlParameter (parm,"DEVMODE_IRCODE",value);
md += atoi (value);
GetHtmlParameter (parm,"DEVMODE_SBUSCODE",value);
md += atoi (value);
GetHtmlParameter (parm,"DEVMODE_RAW",value);
md += atoi (value);
GetHtmlParameter (parm,"DEVMODE_RAWFAST",value);
md += atoi (value);
GetHtmlParameter (parm,"DEVMODE_REPEAT",value);
md += atoi (value);
GetHtmlParameter (parm,"Remote",remote);
GetHtmlParameter (parm,"Command",command);
res = GetHotcode (remote,command,value);
if (res == -1) {
GetError (ERR_HOTCODE,value);
sprintf (err,value,remote,command);
setres = -1;
}
else {
StoreSwitch ((word)id,0,remote,command,1);
WriteSwitches ();
res = SetTransceiverModusEx (0,md,tm,(byte)id,value,res,0xf,4,0,0,0,0); // !! Bus
if (res) {
strcpy (err,"Could not set status");
if (!strcmp (lang,"DE")) strcpy (err,"Status konnte nicht gesetzt werden.");
setres = -1;
}
else {
strcpy (err,"Devicestatus was updated.");
if (!strcmp (lang,"DE")) strcpy (err,"Devicestatus wurde gesetzt.");
setres = 1;
}
}
status_changed = 1;
}
}
status = (NETWORKMODE *)&buf;
cnt = 0;
for (i=0;i < 16;i++) {
if (status->stat[i].version[0]) cnt++;
status->stat[i].version[8] = 0;
}
if (setres) {
strcat (mem,"<br><font face=\"Verdana\" size=\"4\" color=\"red\"><p align=\"center\">");
strcat (mem,err);
strcat (mem,"</p></font><br>");
}
strcat (mem,"<font face=\"Verdana\" size=\"3\"><table><tr><td width=\"20\"> </td><td>");
sprintf (ln,"%d IRTrans Devices found:</td></tr>",cnt);
if (!strcmp (lang,"DE")) sprintf (ln,"%d IRTrans gefunden:</td></tr>",cnt);
strcat (mem,ln);
strcat (mem,"<font face=\"Verdana\" size=\"3\"><table>");
for (i=0;i < 16;i++) if (status->stat[i].version[0]) {
GetIRTransType (status->stat[i].version[0],nm);
sprintf (ln,"<tr><td width=\"20\"> </td><td>%d </td><td>IRTrans %s </td><td>%s</td>",i,nm,status->stat[i].version);
strcat (mem,ln);
sprintf (ln,"<td><a href=\"DeviceConfig.htm?lang=%s&id=%d\"><img border=\"0\" src=\"GoButton.gif\"></a></td></tr>",lang,i);
strcat (mem,ln);
}
strcat (mem,"</table>");
}
strcat (mem,"<br><br><br><br>");
strcat (mem,"<p align=\"center\"><font face=\"Verdana\" size=\"3\">");
sprintf (ln,"IRServer %s (c) 2003 <NAME></font></p>",irserver_version);
strcat (mem,ln);
strcat (mem,"</BODY></HTML>");
}
void GetIRTransType (char ver,char typ[])
{
*typ = 0;
switch (ver) {
case 'C':
strcpy (typ,"Temp");
return;
case 'U':
strcpy (typ,"USB");
return;
case 'V':
strcpy (typ,"USB B&O");
return;
case 'S':
strcpy (typ,"RS232/Bus");
return;
case 'T':
strcpy (typ,"RS232/Bus B&O");
return;
case 'X':
strcpy (typ,"IR Translator");
return;
}
}
void GetIndexPage (char *mem,char *lang)
{
char nm[100];
char ln[1000];
char intfc[20];
strcpy (mem,"<HTML><HEAD><TITLE>IRTrans Server</TITLE></HEAD><BODY bgcolor=\"#C0C0C0\">");
strcat (mem,"<table><tr><td align = \"center\">");
strcat (mem,"<IMG src=\"IRTransLogo.gif\" align = center>");
strcat (mem,"</td><td width=\"30\"> </td><td><table><tr><td>");
*nm = 0;
gethostname (nm,100);
*intfc = 0;
if (*irtrans_version == 'U' || *irtrans_version == 'V') strcpy (intfc,"USB");
if (*irtrans_version == 'S' || *irtrans_version == 'T') strcpy (intfc,"RS232");
sprintf (ln,"<font face=\"Verdana\" size=\"4\">IRTrans Server on <font face=\"Courier\" color=\"blue\">%s</font></font></td></tr>",nm);
if (!strcmp (lang,"DE")) sprintf (ln,"<font face=\"Verdana\" size=\"4\">IRTrans Server auf <font face=\"Courier\" color=\"blue\">%s</font></font></td></tr>",nm);
strcat (mem,ln);
strcat (mem,"<tr><td> </td></tr>");
// sprintf (ln,"<tr><td><font face=\"Verdana\" size=\"4\">IRTrans <font face=\"Courier\" color=\"blue\">%s %s SerNo.%u</font> connected.",intfc,irtrans_version,serno);
//t if (!strcmp (lang,"DE")) sprintf (ln,"<tr><td><font face=\"Verdana\" size=\"4\">IRTrans <font face=\"Courier\" color=\"blue\">%s %s SerNr.%u</font> angeschlossen.",intfc,irtrans_version,serno);
strcat (mem,ln);
if (!strcmp (lang,"DE")) strcat (mem,"</td></tr></table></td><td width=\"20\"> </td><td align=\"center\"><a href=\"index.htm?lang=EN\"><img border=\"0\" src=\"English.jpg\"><br><font face=\"Verdana\" size=\"2\">English</font></a></td></tr></table>");
else strcat (mem,"</td></tr></table></td><td width=\"20\"> </td><td align=\"center\"><a href=\"index.htm?lang=DE\"><img border=\"0\" src=\"Deutsch.jpg\"><br><font face=\"Verdana\" size=\"2\">Deutsch</font></a></td></tr></table>");
strcat (mem,"<br><hr><br><table>");
strcat (mem,"<tr><td width=\"20\"> </td>");
if (!strcmp (lang,"DE")) strcat (mem,"<td height=\"40\"><font face=\"Verdana\" size=\"4\">IRTrans Devices am Bus zeigen</font></td>");
else strcat (mem,"<td height=\"40\"><font face=\"Verdana\" size=\"4\">Show IRTrans Devices connected to the Bus</font></td>");
sprintf (ln,"<td width=\"10\"> </td><td><a href=\"DeviceList.htm?lang=%s\"><img border=\"0\" src=\"GoButton.gif\"></a></td></tr>",lang);
strcat (mem,ln);
strcat (mem,"<tr><td width=\"20\"> </td>");
/* if (!strcmp (lang,"DE")) strcat (mem,"<td height=\"40\"><font face=\"Verdana\" size=\"4\">IR Befehle lernen</font></td>");
else strcat (mem,"<td height=\"40\"><font face=\"Verdana\" size=\"4\">Learn IR Commands</font></td>");
sprintf (ln,"<td width=\"10\"> </td><td><a href=\"Learn.htm?lang=%s\"><img border=\"0\" src=\"GoButton.gif\"></a></td></tr>",lang);
strcat (mem,ln);
strcat (mem,"<tr><td width=\"20\"> </td>");
if (!strcmp (lang,"DE")) strcat (mem,"<td height=\"40\"><font face=\"Verdana\" size=\"4\">IR Befehle senden</font></td>");
else strcat (mem,"<td height=\"40\"><font face=\"Verdana\" size=\"4\">Send IR Commands</font></td>");
sprintf (ln,"<td width=\"10\"> </td><td><a href=\"Send.htm?lang=%s\"><img border=\"0\" src=\"GoButton.gif\"></a></td></tr>",lang);
strcat (mem,ln);*/
strcat (mem,"</table><br><br><br><br>");
strcat (mem,"<p align=\"center\"><font face=\"Verdana\" size=\"3\">");
sprintf (ln,"IRServer %s (c) 2003 <NAME></font></p>",irserver_version);
strcat (mem,ln);
strcat (mem,"</BODY></HTML>");
}
void GenerateErrorPage (char *mem,int error)
{
char ln[1000],stat[1000],body[1000];
if (error == 404) {
sprintf (body,"<HTML><HEAD><TITLE>404 Not found</TITLE></HEAD><BODY>The requested page was not found on this Server</BODY></HTML>");
sprintf (stat,"HTTP/1.1 404 Not found\r\n");
}
strcpy (mem,stat);
strcat (mem,"Date: Sun, 21 Dec 2003 23:10:01 GMT\r\n");
strcat (mem,"Server: IRTrans 2.0\r\n");
strcat (mem,"Mime-Version: 1.0\r\n");
sprintf (ln,"Content-Type: text/html\r\nContent-Length: %6d\r\n",strlen (body));
strcat (mem,ln);
strcat (mem,"Expires: Sun, 21 Dec 2003 23:10:01 GMT\r\n");
strcat (mem,"Cache-control: no-cache\r\n");
strcat (mem,"\r\n");
strcat (mem,body);
}
void GenerateHtmlHeader (char *mem,char *data)
{
int len;
char ln[1000];
len = (int)strlen (data);
sprintf (mem,"HTTP/1.1 200 OK\r\n");
strcat (mem,"Date: Sun, 21 Dec 2003 23:10:01 GMT\r\n");
strcat (mem,"Server: IRTrans 2.0\r\n");
strcat (mem,"Mime-Version: 1.0\r\n");
sprintf (ln,"Content-Type: text/html\r\nContent-Length: %6d\r\n",len);
strcat (mem,ln);
strcat (mem,"Expires: Sun, 21 Dec 2003 23:10:01 GMT\r\n");
strcat (mem,"Cache-control: no-cache\r\n");
strcat (mem,"\r\n");
strcat (mem,data);
}
int GenerateImageHeader (char *mem,char *data,char *type,int len)
{
char ln[1000];
int hlen;
sprintf (mem,"HTTP/1.1 200 OK\r\n");
strcat (mem,"Date: Sun, 21 Dec 2003 23:10:01 GMT\r\n");
strcat (mem,"Server: IRTrans 2.0\r\n");
strcat (mem,"Mime-Version: 1.0\r\n");
sprintf (ln,"Content-Type: image/%s\r\nContent-Length: %6d\r\n",type,len);
strcat (mem,ln);
strcat (mem,"\r\n");
hlen = (int)strlen (mem);
memcpy (mem+hlen,data,len);
return (hlen + len);
}
|
asterics/IRTrans-Server
|
fileio.h
|
<filename>fileio.h
/*
* Copyright (c) 2007, IRTrans GmbH
* 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.
* * Neither the name of IRTrans GmbH nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY IRTrans GmbH ``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 IRTrans GmbH 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.
*/
extern NETWORKCLIENT sockinfo[CLIENT_COUNT];
int DBReadCommandFile (char remote[]);
int DBStoreRemote (FILE *fp,char newremote[]);
int DBStoreTimings (FILE *fp,char remote[]);
int DBStoreCommands (FILE *fp,char remote[]);
int DBStoreCCFCode (char cd[]);
void DBShowStatus (void);
void ReadRoutingTable (void);
void ReadSwitches (void);
void ReadAppConfig (void);
void WriteSwitches (void);
int FindSwitch (word id,word num,char *rem,char *com,word *mode);
int StoreSwitch (word id,word num,char *rem,char *com,word mode);
int DBStoreRooms (FILE *fp);
void DBStoreRouting (FILE *fp,char section[],ROUTING **pnt,int *cnt);
void FreeDatabaseMemory (void);
void ReadCalibrateData (byte *pnt,byte *pntcal);
FILE *DBOpenFile (char remote[],char mode[]);
char *DBReadString (char ln[],FILE *fp,int *fpos);
char *DBFindSection (FILE *fp,char section[],char data[],char end[],int *fpos);
int StoreIRTiming (IRTIMING *irp,char data[],int toggle);
void ConvertLcase (char *pnt,int len);
int GetFunctionCode (byte type,char *com);
int GetKeyCode (char *com);
void ConvertIRDARAW (char data[]);
int FindLineSection (char ln[],char section[]);
void StorePulseTiming (IRTIMING *irp,char cmd[],char data[]);
void StoreSingleTimingPulse (IRTIMING *irp,char cmd[],char data[]);
void StoreSingleTimingPause (IRTIMING *irp,char cmd[],char data[]);
FILE *ASCIIOpenRemote (char name[],NETWORKCLIENT *client);
void ASCIITimingSample (FILE *fp,NETWORKCLIENT *client);
int ASCIIStoreCommand (FILE *fp,IRDATA *ird,char name[],int timing,int seq_number);
int ASCIIStoreCCF (int client,char name[],char ccf[]);
int ASCIIStoreRS232 (int client,char name[],char rs232[]);
int ASCIIStoreLink (int client,char name[],char link[]);
int FormatCCF (char *ccf);
int ASCIIFindToggleSeq (FILE *fp,IRDATA *ird,char name[]);
int ASCIIStoreTiming (FILE *fp,IRDATA *ird,NETWORKLEARNSTAT *stat);
int ASCIIStoreRAW (FILE *fp,IRRAW *ird,char name[]);
void ASCIIStoreTimingParam (FILE *fp,IRDATA *ird,int timing);
int ASCIIFindCommand (FILE *fp,char name[],NETWORKCLIENT *client);
int CompareTiming (IRDATA *ird,IRTIMING *irt);
int ASCIIFindTiming (FILE *fp,IRDATA *ird);
void GetRemoteAddressMask (int num);
void CopyStateInfo (byte *state,int cmd);
byte CopyToggleData (int tim,int cmd);
void CopyRepeatOffset (byte repeat_offset,int cmd);
int GetRepeatOffset (IRDATA *ird);
void FillInTiming (IRDATA *ir,IRTIMING *tim);
int DBFindCommandName (byte command[],char remote[],char name[],byte address,int *remote_num,int *command_num,word *command_num_rel,int start);
int DBFindRemoteCommand (char remote[],char command[],int *cmd_num,int *rem_num);
int DBFindRemoteMacro (char remote[],char command[],int cmd_array[],word pause_array[]);
int DBFindRemoteCommandEx(char remote[],char command[],IRDATA *ir,byte cal,byte toggle);
int DBGetIRCode (int cmd_num,IRDATA *ir,int idx,int *mac_len,int *mac_pause,int *rpt_len,byte calflag,byte toggle);
int DBGetRepeatCode (int cmd_num,IRDATA *ir,byte calflag,byte toggle);
int DBFindCommand (char command[],int32_t *remote);
int DBFindRemote (char remote[]);
void GetNumericCode (char command[],char numeric[],char rem[],char com[]);
void GetRemoteDatabase (REMOTEBUFFER *buf,int offset);
int GetCommandDatabase (COMMANDBUFFER *buf,char remote[],int offset);
int DBReferenceLinks (void);
#define RS232_IRCOMMAND -10
#define LINK_IRCOMMAND -20
#define LINK_ERROR -21
|
asterics/IRTrans-Server
|
xap.c
|
/*
* Copyright (c) 2007, IRTrans GmbH
* 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.
* * Neither the name of IRTrans GmbH nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY IRTrans GmbH ``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 IRTrans GmbH 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.
*/
#ifdef WIN32
#include <winsock2.h>
#include <windows.h>
#include <winuser.h>
#include <io.h>
#include <direct.h>
#include <sys/types.h>
#include <time.h>
#include <sys/timeb.h>
#include <process.h>
#include <string.h>
#define MSG_NOSIGNAL 0
#endif
#ifdef WINCE
#include <winsock2.h>
#include <windows.h>
#include <winuser.h>
#include <time.h>
#define MSG_NOSIGNAL 0
#endif
#include <stdio.h>
#include <stdlib.h>
#ifdef LINUX
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <netdb.h>
#include <stdint.h>
typedef int DWORD;
#define closesocket close
#define _getpid getpid
#endif
#include "remote.h"
#include "dbstruct.h"
#include "network.h"
#include "errcode.h"
#include "fileio.h"
#include "lowlevel.h"
#include "server.h"
#include "global.h"
#include "webserver.h"
#include "flash.h"
#include "xap.h"
#include "ccf.h"
time_t xAP_last_hbeat;
int xAP_rcv_port;
SOCKET xAP_rcv;
SOCKET xAP_send;
// target=IRTrans.irserver.<bus>:<ID>.<LED>
// Internal LEDs: target=IRTrans.irserver.<bus>:<ID>:int
// External LEDs: target=IRTrans.irserver.<bus>:<ID>:ext
void xAP_SendHeartbeat (void)
{
int i;
char st[1500];
if (!(mode_flag & XAP)) return;
for (i=0;i<device_cnt;i++) {
sprintf (st,"xap-hbeat\n{\nv=%d\nhop=1\nuid=%s00\nclass=xap-hbeat.alive\nsource=%s.%d\ninterval=%d\nport=%d\npid=%d\n}\n",
XAP_VERSION,XAP_UID,XAP_ADR,i,XAP_HBEAT,xAP_rcv_port,_getpid ());
xAP_SendData (st);
}
xAP_last_hbeat = time (0);
}
void xAP_SendIREvent (char remote[],char command[],int bus,int adr)
{
char st[1500];
if (!(mode_flag & XAP)) return;
sprintf (st,"xap-header\n{\nv=%d\nhop=1\nuid=%s%02x\nclass=ir.receive\nsource=%s.%d:%d\n}\nIR.Signal\n{\ndevice=%s\nsignal=%s\n}\n",
XAP_VERSION,XAP_UID,adr+1,XAP_ADR,bus,adr,remote,command);
xAP_SendData (st);
}
void xAP_EventReceived (void)
{
int res;
char data[1500];
res = recv(xAP_rcv,data,1500,MSG_NOSIGNAL);
if (res <= 0) return;
data[res] = 0;
xAP_ProcessHeader (data);
}
void xAP_SendData (char data[])
{
send (xAP_send,data,(int)strlen (data),MSG_NOSIGNAL);
}
void xAP_ProcessHeader (char data[])
{
IRDATA ird;
int cmd_num;
unsigned int adr;
int p,q,pos,res,bus,mask,led;
char line[256],err[256],txt[256];
char remote[1500];
char command[512];
if (strncmp (data,"xap-header",10)) return;
if (xAP_GetItem (data,"class=",line) <= 0 || strcmp (line,"ir.transmit")) return;
adr = 0;
bus = 0;
mask = 0xffff;
led = 0;
if (xAP_GetItem (data,"target=",line) > 0) {
if (xAP_GetItem (data,"target=irtrans.irserver.",line) <= 0) return;
pos = 0;
while (line[pos] && line[pos] != ':') pos++;
p = line[pos];
line[pos] = 0;
if (line[0] == '*') {
adr = 0x40000000;
bus = 255;
}
else {
adr = atoi (line) << 20;
bus = atoi (line);
}
if (p) {
p = ++pos;
while (line[pos] && line[pos] != '.') pos++;
q = line[pos];
line[pos] = 0;
if (line[p] == '*') {
adr |= 0x1ffff;
mask = 0xffff;
}
else {
adr |= 0x10000 | (1 << atoi (line+p));
mask = (1 << atoi (line+p));
}
}
if (q) {
pos++;
if (line[pos] == '*') {
adr |= 0x60000;
led = 3;
}
else if (line[pos] == 'i') {
adr |= 0x20000;
led = 1;
}
else if (line[pos] == 'e') {
adr |= 0x40000;
led = 2;
}
}
}
if ((pos = xAP_GetItem (data,"ir.signal",line)) > 0) {
if (xAP_GetItem (data+pos,"device=",remote) <= 0) return;
if (xAP_GetItem (data+pos,"signal=",command) <= 0) return;
res = DBFindRemoteCommand (remote,command,&cmd_num,NULL);
if (!res) res = SendIR (cmd_num,adr,COMMAND_SEND,NULL);
if (res) {
GetError (res, txt);
switch(res) {
case ERR_REMOTENOTFOUND:
sprintf (err, txt, remote);
break;
case ERR_COMMANDNOTFOUND:
sprintf (err, txt, command);
break;
case ERR_WRONGBUS:
sprintf (err,txt,(adr >> 20) & (MAX_IR_DEVICES - 1));
break;
default:
sprintf (err, txt);
break;
}
log_print (err, LOG_ERROR);
return;
}
sprintf (txt,"xAP send: %s-%s [%x]\n", remote,command,adr);
log_print (txt,LOG_DEBUG);
}
if ((pos = xAP_GetItem (data,"ir.pronto",line)) > 0) {
if (xAP_GetItem (data+pos,"ir=",remote) <= 0) return;
res = DecodeCCF (remote,&ird,START);
if (res <= 0) {
sprintf (err,"Illegal xAP Pronto command\n");
log_print (err, LOG_ERROR);
return;
}
ird.address = led;
ird.target_mask = mask;
DoSendIR (&ird,NULL,0,0,bus,COMMAND_SEND);
}
}
int xAP_GetItem (char data[],char item[],char value[])
{
int i = 0;
char line[256];
do {
i = xAP_GetLine (data,line,i);
ConvertLcase (line,(int)strlen (line));
if (!memcmp (line,item,strlen (item))) {
strcpy (value,line + strlen (item));
return (i);
}
} while (i != -1);
return (0);
}
int xAP_GetLine (char data[],char line[],int pos)
{
int p;
line[0] = 0;
while (data[pos] == 10 || data[pos] == 13) pos++;
if (!data[pos]) return (-1);
p = pos;
while (data[pos] && data[pos] != 10 && data[pos] != 13) pos++;
memcpy (line,data+p,pos-p);
line[pos-p] = 0;
return (pos);
}
|
asterics/IRTrans-Server
|
errcode.h
|
<gh_stars>1-10
/*
* Copyright (c) 2007, IRTrans GmbH
* 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.
* * Neither the name of IRTrans GmbH nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY IRTrans GmbH ``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 IRTrans GmbH 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.
*/
#define ERR_OPEN 1
#define ERR_RESET 2
#define ERR_VERSION 3
#define ERR_TIMEOUT 4
#define ERR_READVERSION 5
#define ERR_USBCOM 6
#define ERR_NETIO 7
#define ERR_DBOPENINPUT 11
#define ERR_REMOTENOTFOUND 12
#define ERR_COMMANDNOTFOUND 13
#define ERR_TIMINGNOTFOUND 14
#define ERR_OPENASCII 15
#define ERR_NODATABASE 16
#define ERR_OPENUSB 17
#define ERR_RESEND 18
#define ERR_TOGGLE_DUP 19
#define ERR_DBOPENINCLUDE 20
#define ERR_NOFILEOPEN 21
#define ERR_FLOCK 22
#define ERR_STTY 23
#define ERR_HOTCODE 24
#define ERR_NOTIMING 25
#define ERR_TEMPCOMMAND 26
#define ERR_OPENTRANS 27
#define ERR_TESTCOM 28
#define ERR_SHUTDOWN 29
#define ERR_ISMACRO 30
#define ERR_LONGRAW 31
#define ERR_LONGDATA 32
#define ERR_WRONGBUS 33
#define ERR_COMMANDSTRING 34
#define ERR_OVERWRITE 35
#define ERR_CCF 36
#define ERR_UDPFORMAT 37
#define ERR_TESTCOMOK 38
#define ERR_NOIRDB 39
#define ERR_NOTSUPPORTED 40
#define ERR_NO_RS232 41
#define ERR_SENDOK 42
#define ERR_CCFLEN 43
#define ERR_ACTIONSEND 44
#define ERR_CCFSYNTAX 45
#define ERR_SSID_WLAN 46
#define ERR_SEND_DISABLED 47
#define ERR_SEND_LED 48
#define ERR_IRDB_EMPTY 49
#define ERR_OUTPUT_BUSY 50
#define ERR_MACRO_LENGTH 51
#define ERR_MACRO_COUNT 52
#define ERR_NO_MACRO 53
#define ERR_ANALOG 54
#define ERR_LONGCODE 55
#define ERR_IRCODE_LENGTH 56
#define ERR_IRCODE_TIMING 57
#define ERR_IRCODE_DATA 58
#define ERR_NOSTATEINPUT 59
#define ERR_ASCIIFORMAT 60
#define ERR_LEARN_LENGTH 95
#define ERR_LEARN_RAWLEN 96
#define ERR_LEARN_TIMECNT 97
#define ERR_LEARN_TC_LEN 98
#define ERR_OPENSOCKET 100
#define ERR_BINDSOCKET 101
#define ERR_FINDHOST 103
#define ERR_CONNECT 104
#define ERR_SEND 105
#define ERR_RECV 106
#define ERR_BINDWEB 107
#define ERR_DEVICEUNKNOWN 108
#define FATAL 1
#define IR 2
#define IRTIMEOUT 3
void GetError (int res,char st[]);
|
asterics/IRTrans-Server
|
mce.c
|
/*
* Copyright (c) 2007, IRTrans GmbH
* 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.
* * Neither the name of IRTrans GmbH nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY IRTrans GmbH ``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 IRTrans GmbH 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.
*/
#ifdef WIN32
#define _WIN32_WINNT 0x501
#ifndef VC6
#include "winsock2.h"
#endif
#include <windows.h>
#include <winuser.h>
#include <io.h>
#include <direct.h>
#include <sys/timeb.h>
HMODULE kdll;
#endif
#include <stdio.h>
#ifdef LINUX
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdint.h>
typedef int DWORD;
#define closesocket close
#endif
#include "remote.h"
#include "global.h"
#include "network.h"
#include "lowlevel.h"
#include "dbstruct.h"
#define CONTROL 1
#define SHIFT 2
#define NO_KEYUP 4
#define ALT 8
#define LWINKEY 16
#define MULTIKEY_TIMEOUT 750
#define SCAN_SHIFT 1
#define SCAN_CTRL 2
#define SCAN_ALT 4
#define SCAN_WIN 8
#define SC_ALTGR 1
#define SC_SHIFT_R 2
#define SC_CTRL_R 4
#define SC_WIN_R 8
#define SC_ALT 16
#define SC_SHIFT_L 32
#define SC_CTRL_L 64
void SendXBMC (APPCOMMAND *appcom);
#ifdef MEDIACENTER
extern DEVICEINFO IRDevices[MAX_IR_DEVICES];
extern APP app_pnt[30];
extern int app_cnt;
void SendMediaCenterAction (int app,int com);
void IRTransSendInput (int key,int flags);
void SendKey (APP *app,APPCOMMAND *appcom,byte flag);
void ConvertLcase (char *pnt,int len);
void SendMediacenterEvent (int eventcode);
void SendAppcommand (APP *app,APPCOMMAND *appcom);
void SendWMChar (APP *app,APPCOMMAND *appcom);
void HandleKeyboardScancodes (char scan[]);
void HandleDirectScancodes (char scan[]);
void HandleMouse (char mov[]);
void HandleShortcut (char shortcut[]);
void StartXBMC (APP *app);
extern byte xbmc_mode;
extern int xbmc_remote;
extern byte xbmc_init;
unsigned int GetFineTime (void);
void PostWindowsMessage (int rem,int com,char name[])
{
int i,j;
APPCOMMAND *appcom;
for (i=0;i < app_cnt;i++) if (app_pnt[i].remnum == rem) {
#ifdef WIN32
if (app_pnt[i].type == TYPE_KEYBOARD) {
HandleKeyboardScancodes (name);
}
else if (app_pnt[i].type == TYPE_SCANCODE) {
HandleDirectScancodes (name);
}
else if (app_pnt[i].type == TYPE_MOUSE) {
HandleMouse (name);
}
else if (app_pnt[i].type == TYPE_SHORTCUT) {
HandleShortcut (name);
}
else
#endif
for (j=0;j < app_pnt[i].com_cnt;j++) if (app_pnt[i].com[j].comnum == com) {
appcom = &(app_pnt[i].com[j]);
#ifdef WIN32
if (!xbmc_init || rem != xbmc_remote) {
if (appcom->type[0] == TYPE_MCE) SendMediaCenterAction (i,j);
if (appcom->type[0] == TYPE_KEY) SendKey (app_pnt + i,appcom,0);
if (appcom->type[0] == TYPE_KEYF) SendKey (app_pnt + i,appcom,1);
if (appcom->type[0] == TYPE_APPCOM) SendAppcommand (app_pnt + i,appcom);
if (appcom->type[0] == TYPE_CHR) SendWMChar (app_pnt + i,appcom);
}
#endif
if (appcom->type[0] == TYPE_XBMC) StartXBMC (app_pnt + i);
if (appcom->type[0] == TYPE_STR || appcom->type[0] == TYPE_XBMC_BUTTON ||
appcom->type[0] == TYPE_XBMC_ACTION || appcom->type[0] == TYPE_XBMC_ACTION_BUILTIN) SendXBMC (appcom);
}
}
}
#ifdef WIN32
void HandleShortcut (char shortcut[])
{
ShellExecute(NULL,"open",shortcut,NULL,NULL,SW_SHOWNORMAL ); //execute shortcut in remotes folder
}
void HandleMouse (char mov[])
{
static byte last_m1,last_m2;
byte m1,m2;
INPUT InpInfo[20];
int x,y,p = 0;
m1 = mov[9] - '0';
m2 = mov[8] - '0';
x = atoi (mov);
y = atoi (mov + 4);
p = 0;
memset (InpInfo,0,sizeof (InpInfo));
if (last_m1 != m1) {
InpInfo[p].type = INPUT_MOUSE;
if (m1) InpInfo[p].mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
else InpInfo[p].mi.dwFlags = MOUSEEVENTF_LEFTUP;
p++;
}
if (last_m2 != m2) {
InpInfo[p].type = INPUT_MOUSE;
if (m1) InpInfo[p].mi.dwFlags = MOUSEEVENTF_RIGHTDOWN;
else InpInfo[p].mi.dwFlags = MOUSEEVENTF_RIGHTUP;
p++;
}
if (x || y) {
InpInfo[p].type = INPUT_MOUSE;
InpInfo[p].mi.dx = x;
InpInfo[p].mi.dy = y;
InpInfo[p].mi.dwFlags = MOUSEEVENTF_MOVE;
p++;
}
//------------------------------------------modified------------------------------------------
if (p)
{
SystemParametersInfo (0x1027,FALSE,NULL,0); //turn off screensaver
SetThreadExecutionState (ES_DISPLAY_REQUIRED | ES_SYSTEM_REQUIRED); //reset idle timers
SendInput (p,InpInfo,sizeof (INPUT));
}
last_m1 = m1;
last_m2 = m2;
}
void HandleDirectScancodes (char scan[])
{
static byte last_scan;
static byte last_flags;
static unsigned int last_time;
HKL layout;
INPUT InpInfo[20];
int p,key;
byte chr;
byte scancode;
byte flags;
chr = scan[0];
if (chr >= 'a' && chr <= 'f') chr = chr - 'a' + 10;
else chr -= '0';
scancode = chr;
chr = scan[1];
if (chr >= 'a' && chr <= 'f') chr = chr - 'a' + 10;
else chr -= '0';
scancode = scancode * 16 + chr;
p = 2;
flags = 0;
key = 1;
while (p <= 8) {
if (scan[p] == '1') flags |= key;
p++;
key <<= 1;
}
if (flags & SC_ALTGR) flags |= SC_ALT | SC_CTRL_L;
if (last_scan == scancode && last_flags != flags && (GetFineTime () - last_time) < 250) return;
layout = GetKeyboardLayout (0);
if (scancode == VK_APPS) key = VK_APPS;
else key = MapVirtualKeyEx (scancode,1,layout);
memset (InpInfo,0,sizeof (InpInfo));
p = 0;
if (flags & SC_SHIFT_L) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_LSHIFT;
p++;
}
if (flags & SC_SHIFT_R) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_RSHIFT;
p++;
}
if (flags & SC_CTRL_L) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_LCONTROL;
p++;
}
if (flags & SC_CTRL_R) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_RCONTROL;
p++;
}
if (flags & SC_ALT) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_MENU;
p++;
}
if (flags & SC_WIN_R) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_LWIN;
p++;
}
if (key) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = key;
p++;
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
InpInfo[p].ki.wVk = key;
p++;
}
if (flags & SC_WIN_R) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_LWIN;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
p++;
}
if (flags & SC_ALT) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_MENU;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
p++;
}
if (flags & SC_CTRL_R) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_RCONTROL;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
p++;
}
if (flags & SC_CTRL_L) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_LCONTROL;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
p++;
}
if (flags & SC_SHIFT_R) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_RSHIFT;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
p++;
}
if (flags & SC_SHIFT_L) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_LSHIFT;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
p++;
}
SystemParametersInfo (0x1027,FALSE,NULL,0); //turn off screensaver
SetThreadExecutionState (ES_DISPLAY_REQUIRED | ES_SYSTEM_REQUIRED); //reset idle timers
SendInput (p,InpInfo,sizeof (INPUT));
last_scan = scancode;
last_flags = flags;
last_time = GetFineTime ();
}
void HandleKeyboardScancodes (char scan[])
{
static byte last_scan;
static byte last_flags;
static unsigned int last_time;
HKL layout;
INPUT InpInfo[10];
int p,key;
byte chr;
byte scancode;
byte flags;
chr = scan[0];
if (chr >= 'a' && chr <= 'f') chr = chr - 'a' + 10;
else chr -= '0';
scancode = chr;
chr = scan[1];
if (chr >= 'a' && chr <= 'f') chr = chr - 'a' + 10;
else chr -= '0';
scancode = scancode * 16 + chr;
flags = scan[2] - '0';
if (last_scan == scancode && last_flags != flags && (GetFineTime () - last_time) < 250) return;
layout = GetKeyboardLayout (0);
if (scancode == VK_APPS) key = VK_APPS;
else key = MapVirtualKeyEx (scancode,1,layout);
memset (InpInfo,0,sizeof (InpInfo));
p = 0;
if (flags & SCAN_CTRL) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_CONTROL;
p++;
}
if (flags & SCAN_SHIFT) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_SHIFT;
p++;
}
if (flags & SCAN_ALT) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_MENU;
p++;
}
if (flags & SCAN_WIN) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_LWIN;
p++;
}
if (key) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = key;
p++;
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
InpInfo[p].ki.wVk = key;
p++;
}
if (flags & SCAN_WIN) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
InpInfo[p].ki.wVk = VK_LWIN;
p++;
}
if (flags & SCAN_ALT) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
InpInfo[p].ki.wVk = VK_MENU;
p++;
}
if (flags & SCAN_SHIFT) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_SHIFT;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
p++;
}
if (flags & SCAN_CTRL) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_CONTROL;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
p++;
}
SystemParametersInfo (0x1027,FALSE,NULL,0); //turn off screensaver
SetThreadExecutionState (ES_DISPLAY_REQUIRED | ES_SYSTEM_REQUIRED); //reset idle timers
SendInput (p,InpInfo,sizeof (INPUT));
last_scan = scancode;
last_flags = flags;
last_time = GetFineTime ();
}
void SendWMChar (APP *app,APPCOMMAND *appcom)
{
HWND win;
win = FindWindow (app->classname,NULL);
if (!win) return;
PostMessage (win,WM_KEYDOWN,(WPARAM)appcom->function.function[0],(LPARAM)0);
}
void SendAppcommand (APP *app,APPCOMMAND *appcom)
{
HWND win;
win = FindWindow (app->classname,NULL);
if (!win) return;
PostMessage (win,WM_APPCOMMAND,(WPARAM)1,(LPARAM)(appcom->function.function[0] << 16));
}
void SendKey (APP *app,APPCOMMAND *appcom,byte flag)
{
HWND win;
DWORD thr;
byte mf = 0;
struct _timeb tb;
unsigned int tv;
static byte cindex;
static APPCOMMAND *lastcom;
static unsigned int lasttime;
if (app && app->classname[0]) {
win = FindWindow (app->classname,NULL);
if (!win) return;
if (flag) {
thr = GetWindowThreadProcessId (win,NULL);
AttachThreadInput (GetCurrentThreadId (),thr,TRUE);
SetFocus (win);
AttachThreadInput (GetCurrentThreadId (),thr,FALSE);
}
}
_ftime (&tb);
tv = (unsigned int)((tb.time & 0x7fffff) * 1000 + tb.millitm);
if (appcom != lastcom) cindex = 0;
else {
if ((tv - lasttime) < MULTIKEY_TIMEOUT) mf = ++cindex;
else cindex = 0;
}
if (appcom->type[cindex] != TYPE_KEY) {
if (cindex == 1) mf = 0;
cindex = 0;
}
if (mf != 0)
{
IRTransSendInput (VK_DELETE,0);
}
IRTransSendInput (appcom->function.function[cindex] & 0xff,(appcom->function.function[cindex] & 0xff00) >> 8);
lastcom = appcom;
lasttime = tv;
}
void SendMediaCenterAction (int app,int com)
{
int res;
HWND mcewin;
char *sysdir,prog[256];
mcewin = FindWindow (app_pnt[app].classname,NULL);
if (mcewin == NULL) {
if (xbmc_mode && app_pnt[app].remnum == xbmc_remote) return; // Wenn XBMC aktiv kein MCE starten
if (app_pnt[app].com[com].type[0] == TYPE_RUN || app_pnt[app].com[com].type[1] == TYPE_RUN) {
sysdir = getenv ("SystemRoot");
if (sysdir) {
sprintf (prog,"%s\\ehome\\ehshell.exe",sysdir);
if (app_pnt[app].com[com].function.function[0] == 40) strcat (prog," /homepage:VideoCollection.xml /pushstartpage:true"); // Video
if (app_pnt[app].com[com].function.function[0] == 35) strcat (prog," /homepage:Audio.Home.xml /pushstartpage:true"); // Music
if (app_pnt[app].com[com].function.function[0] == 39) strcat (prog," /homepage:VideoHome.xml /pushstartpage:true"); // TV
if (app_pnt[app].com[com].function.function[0] == 45) strcat (prog," /homepage:Radio.xml /pushstartpage:true"); // Radio
if (app_pnt[app].com[com].function.function[0] == 36) strcat (prog," /homepage:Photos.xml /pushstartpage:true"); // Pictures
if (app_pnt[app].com[com].function.function[0] == 37) strcat (prog," /homepage:VideoRecordedPrograms.xml /pushstartpage:true"); // RecTV
res = WinExec (prog,SW_SHOWMAXIMIZED);
}
}
else if (app_pnt[app].com[com].function.function[0] == 42) IRTransSendInput (VK_RETURN,ALT | LWINKEY);
}
else {
switch (app_pnt[app].com[com].function.function[0]) {
case 12: // Clear
IRTransSendInput (VK_ESCAPE,0);
return;
case 17: // Mute
// IRTransSendInput (119,0);
SendMediacenterEvent (APPCOMMAND_VOLUME_MUTE);
return;
case 18: // Vol-
// IRTransSendInput (120,0);
SendMediacenterEvent (APPCOMMAND_VOLUME_DOWN);
return;
case 19: // Vol+
// IRTransSendInput (121,0);
SendMediacenterEvent (APPCOMMAND_VOLUME_UP);
return;
case 20: // Play
// IRTransSendInput (80,SHIFT | CONTROL);
SendMediacenterEvent (APPCOMMAND_MEDIA_PLAY);
return;
case 21: // Stop
// IRTransSendInput (83,SHIFT | CONTROL);
SendMediacenterEvent (APPCOMMAND_MEDIA_STOP);
return;
case 22: // Next
// IRTransSendInput (70,CONTROL);
SendMediacenterEvent (APPCOMMAND_MEDIA_NEXTTRACK);
return;
case 23: // Prev
// IRTransSendInput (66,CONTROL);
SendMediacenterEvent (APPCOMMAND_MEDIA_PREVIOUSTRACK);
return;
case 24: // REC
// IRTransSendInput (82,CONTROL);
SendMediacenterEvent (APPCOMMAND_MEDIA_RECORD);
return;
case 25: // Pause
// IRTransSendInput (80,CONTROL);
SendMediacenterEvent (APPCOMMAND_MEDIA_PAUSE);
return;
case 26: // REW
// IRTransSendInput (66,SHIFT | CONTROL);
SendMediacenterEvent (APPCOMMAND_MEDIA_REWIND);
return;
case 27: // FWD
// IRTransSendInput (70,SHIFT | CONTROL);
SendMediacenterEvent (APPCOMMAND_MEDIA_FAST_FORWARD);
return;
case 28: // Ch+
IRTransSendInput (187,CONTROL);
// SendMediacenterEvent (APPCOMMAND_MEDIA_CHANNEL_UP);
return;
case 29: // Ch-
IRTransSendInput (189,CONTROL);
// SendMediacenterEvent (APPCOMMAND_MEDIA_CHANNEL_DOWN);
return;
case 31: // DVDMenu
IRTransSendInput (77,SHIFT | CONTROL);
return;
case 32: // DVDAudio
IRTransSendInput (65,SHIFT | CONTROL);
return;
case 33: // DVDSubtitle
IRTransSendInput (85, CONTROL);
return;
case 34: // EPG
IRTransSendInput (71,CONTROL);
return;
case 35: // Music
IRTransSendInput (77,CONTROL);
return;
case 36: // Pictures
IRTransSendInput (73,CONTROL);
return;
case 37: // RecTV
IRTransSendInput (79,CONTROL);
return;
case 38: // TV
IRTransSendInput (84,CONTROL | SHIFT);
return;
case 39: // LiveTV
IRTransSendInput (84,CONTROL);
return;
case 40: // Video
IRTransSendInput (69,CONTROL);
return;
case 41: // Info
IRTransSendInput (68,CONTROL);
return;
case 42: // Ehome
IRTransSendInput (VK_RETURN,ALT | LWINKEY);
return;
case 43: // Messenger
IRTransSendInput (78,CONTROL);
return;
case 44: // Teletext
IRTransSendInput (68,CONTROL);
return;
case 45: // Radio
IRTransSendInput (65,CONTROL);
return;
case 46: // Back
SendMediacenterEvent (APPCOMMAND_BROWSER_BACKWARD);
return;
}
}
}
void SendMediacenterEvent (int eventcode)
{
HWND mcewin;
mcewin = FindWindow ("eHome Render Window",NULL);
if (!mcewin) return;
PostMessage (mcewin,WM_APPCOMMAND,(WPARAM)1,(LPARAM)(eventcode << 16));
}
void IRTransSendInput (int key,int flags)
{
INPUT InpInfo[10];
int p;
memset (InpInfo,0,sizeof (InpInfo));
p = 0;
if (flags & CONTROL) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_CONTROL;
p++;
}
if (flags & SHIFT) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_SHIFT;
p++;
}
if (flags & ALT) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_MENU;
p++;
}
if (flags & LWINKEY) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_LWIN;
p++;
}
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = key;
p++;
if (!(flags & NO_KEYUP)) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
InpInfo[p].ki.wVk = key;
p++;
}
if (flags & LWINKEY) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
InpInfo[p].ki.wVk = VK_LWIN;
p++;
}
if (flags & ALT) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
InpInfo[p].ki.wVk = VK_MENU;
p++;
}
if (flags & SHIFT) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_SHIFT;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
p++;
}
if (flags & CONTROL) {
InpInfo[p].type = INPUT_KEYBOARD;
InpInfo[p].ki.wVk = VK_CONTROL;
InpInfo[p].ki.dwFlags = KEYEVENTF_KEYUP;
p++;
}
SystemParametersInfo (0x1027,FALSE,NULL,0); //turn off screensaver
SetThreadExecutionState (ES_DISPLAY_REQUIRED | ES_SYSTEM_REQUIRED); //reset idle timers
SendInput (p,InpInfo,sizeof (INPUT));
}
#endif
#endif
int GetKeyCode (char *com)
{
int key = 0;
#ifdef WIN32
if (*com == '\\') {
com++;
if (!strcmp (com,"space")) return ' ';
if (!strcmp (com,"period")) return 0xbe;
if (!strcmp (com,"comma")) return 0xbc;
if (!strcmp (com,"enter")) return VK_RETURN;
if (!strcmp (com,"up")) return VK_UP;
if (!strcmp (com,"down")) return VK_DOWN;
if (!strcmp (com,"right")) return VK_RIGHT;
if (!strcmp (com,"left")) return VK_LEFT;
if (!strcmp (com,"backspace")) return VK_BACK;
if (!strcmp (com,"end")) return VK_END;
if (!strcmp (com,"home")) return VK_HOME;
if (!strcmp (com,"pgup")) return VK_PRIOR;
if (!strcmp (com,"pgdown")) return VK_NEXT;
if (!strcmp (com,"esc")) return VK_ESCAPE;
if (!strcmp (com,"tab")) return VK_TAB;
if (!strcmp (com,"f1")) return VK_F1;
if (!strcmp (com,"f2")) return VK_F2;
if (!strcmp (com,"f3")) return VK_F3;
if (!strcmp (com,"f4")) return VK_F4;
if (!strcmp (com,"f5")) return VK_F5;
if (!strcmp (com,"f6")) return VK_F6;
if (!strcmp (com,"f7")) return VK_F7;
if (!strcmp (com,"f8")) return VK_F8;
if (!strcmp (com,"f9")) return VK_F9;
if (!strcmp (com,"f10")) return VK_F10;
if (!strcmp (com,"f11")) return VK_F11;
if (!strcmp (com,"f12")) return VK_F12;
if (!strcmp (com,"menu")) return VK_APPS;
if (!strcmp (com,"pause")) return VK_PAUSE;
while (!strncmp (com,"alt",3) || !strncmp (com,"ctrl",4) || !strncmp (com,"shift",5)) {
if (!strncmp (com,"alt",3)) {
key |= ALT << 8;
com += 3;
}
if (!strncmp (com,"ctrl",4)) {
key |= CONTROL << 8;
com += 4;
}
if (!strncmp (com,"shift",5)) {
key |= SHIFT << 8;
com += 5;
}
if (*com == 0) return (0);
if (*com == '\\') {
com++;
if (!strcmp (com,"space")) return key | ' ';
if (!strcmp (com,"period")) return key | 0xbe;
if (!strcmp (com,"comma")) return key | 0xbc;
if (!strcmp (com,"enter")) return key | VK_RETURN;
if (!strcmp (com,"up")) return key | VK_UP;
if (!strcmp (com,"down")) return key | VK_DOWN;
if (!strcmp (com,"right")) return key | VK_RIGHT;
if (!strcmp (com,"left")) return key | VK_LEFT;
if (!strcmp (com,"backspace")) return key | VK_BACK;
if (!strcmp (com,"end")) return key | VK_END;
if (!strcmp (com,"home")) return key | VK_HOME;
if (!strcmp (com,"pgup")) return key | VK_PRIOR;
if (!strcmp (com,"pgdown")) return key | VK_NEXT;
if (!strcmp (com,"esc")) return key | VK_ESCAPE;
if (!strcmp (com,"tab")) return key | VK_TAB;
if (!strcmp (com,"f1")) return key | VK_F1;
if (!strcmp (com,"f2")) return key | VK_F2;
if (!strcmp (com,"f3")) return key | VK_F3;
if (!strcmp (com,"f4")) return key | VK_F4;
if (!strcmp (com,"f5")) return key | VK_F5;
if (!strcmp (com,"f6")) return key | VK_F6;
if (!strcmp (com,"f7")) return key | VK_F7;
if (!strcmp (com,"f8")) return key | VK_F8;
if (!strcmp (com,"f9")) return key | VK_F9;
if (!strcmp (com,"f10")) return key | VK_F10;
if (!strcmp (com,"f11")) return key | VK_F11;
if (!strcmp (com,"f12")) return key | VK_F12;
if (!strcmp (com,"menu")) return key | VK_APPS;
if (!strcmp (com,"pause")) return key | VK_PAUSE;
}
else {
if (*com >= 'a' && *com <= 'z') return (key | (*com - ('a' - 'A')));
return (key | *com);
}
}
return (0);
}
if (*com >= 'a' && *com <= 'z') return (*com - ('a' - 'A'));
if (*com == '+') return VK_ADD;
if (*com == '-') return VK_SUBTRACT;
if (*com == '*') return VK_MULTIPLY;
if (*com == '/') return VK_DIVIDE;
return (*com);
#else
return (0);
#endif
}
int GetFunctionCode (byte type,char *com)
{
if (type == TYPE_APPCOM) {
#ifdef WIN32
if (!strcmp (com,"appcommand_media_play")) return APPCOMMAND_MEDIA_PLAY;
if (!strcmp (com,"appcommand_volume_mute")) return APPCOMMAND_VOLUME_MUTE;
if (!strcmp (com,"appcommand_volume_down")) return APPCOMMAND_VOLUME_DOWN;
if (!strcmp (com,"appcommand_volume_up")) return APPCOMMAND_VOLUME_UP;
if (!strcmp (com,"appcommand_media_stop")) return APPCOMMAND_MEDIA_STOP;
if (!strcmp (com,"appcommand_media_nexttrack")) return APPCOMMAND_MEDIA_NEXTTRACK;
if (!strcmp (com,"appcommand_media_previoustrack")) return APPCOMMAND_MEDIA_PREVIOUSTRACK;
if (!strcmp (com,"appcommand_media_record")) return APPCOMMAND_MEDIA_RECORD;
if (!strcmp (com,"appcommand_media_pause")) return APPCOMMAND_MEDIA_PAUSE;
if (!strcmp (com,"appcommand_media_rewind")) return APPCOMMAND_MEDIA_REWIND;
if (!strcmp (com,"appcommand_media_fast_forward")) return APPCOMMAND_MEDIA_FAST_FORWARD;
if (!strcmp (com,"appcommand_browser_backward")) return APPCOMMAND_BROWSER_BACKWARD;
#endif
}
else if (type == TYPE_MCE) {
if (!strcmp (com,"clear")) return 12;
if (!strcmp (com,"mute")) return 17;
if (!strcmp (com,"vol-")) return 18;
if (!strcmp (com,"vol+")) return 19;
if (!strcmp (com,"play")) return 20;
if (!strcmp (com,"stop")) return 21;
if (!strcmp (com,"next")) return 22;
if (!strcmp (com,"prev")) return 23;
if (!strcmp (com,"rec")) return 24;
if (!strcmp (com,"pause")) return 25;
if (!strcmp (com,"rew")) return 26;
if (!strcmp (com,"fwd")) return 27;
if (!strcmp (com,"ch+")) return 28;
if (!strcmp (com,"ch-")) return 29;
if (!strcmp (com,"dvdmenu")) return 31;
if (!strcmp (com,"dvdaudio")) return 32;
if (!strcmp (com,"dvdsubtitle")) return 33;
if (!strcmp (com,"epg")) return 34;
if (!strcmp (com,"music")) return 35;
if (!strcmp (com,"pictures")) return 36;
if (!strcmp (com,"rectv")) return 37;
if (!strcmp (com,"tv")) return 38;
if (!strcmp (com,"livetv")) return 39;
if (!strcmp (com,"video")) return 40;
if (!strcmp (com,"info")) return 41;
if (!strcmp (com,"ehome")) return 42;
if (!strcmp (com,"messenger")) return 43;
if (!strcmp (com,"teletext")) return 44;
if (!strcmp (com,"radio")) return 45;
if (!strcmp (com,"back")) return 46;
return 0;
}
else if (type == TYPE_XBMC) {
if (!strcmp (com,"xbmc")) return 1;
return 0;
}
return 0;
}
|
Drengr-Engine/Drengr
|
Drengr/src/Test.h
|
<gh_stars>0
#pragma once
#include <application/Application.h>
class Test : public Drengr::Application
{
public:
Test() {
Drengr::Debugger::Log("Drengr Engine Initilization Complete!");
}
~Test() {}
};
Drengr::Application* Drengr::CreateApplication() {
return new Test();
}
|
Drengr-Engine/Drengr
|
Engine/src/core/graphics/buffers/VertexBuffer.h
|
#pragma once
#include <glad/glad.h>
#include "glm/glm.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <vector>
#include <iomanip>
#include <ostream>
namespace Drengr {
struct Vertex {
glm::vec3 m_position;
glm::vec3 Normal;
glm::vec3 Color;
glm::vec2 UV;
friend std::ostream& operator<<(std::ostream& _in, Vertex _v) {
_in << std::setw(4)
<< std::setfill(' ')
<< std::fixed
<< std::setprecision(1)
<< _v.m_position.x << ", " << _v.m_position.y << ", " << _v.m_position.z << ", "
<< _v.Color.r << ", " << _v.Color.g << ", " << _v.Color.b << ", "
<< _v.Normal.x << ", " << _v.Normal.y << ", " << _v.Normal.z << ", "
<< _v.UV.x << ", " << _v.UV.y << std::endl;
return _in;
}
};
class VertexBuffer
{
public:
VertexBuffer(std::vector<Vertex> vertices);
void Bind();
void Unbind();
void Delete();
private:
unsigned int m_ID;
};
}
|
Drengr-Engine/Drengr
|
Engine/src/core/graphics/renderer/Renderer.h
|
#include <glad/glad.h>
namespace Drengr {
class Renderer {
};
}
|
Drengr-Engine/Drengr
|
Engine/src/core/windows/ui/UiWindow.h
|
#pragma once
#include <debug/Debugger.h>
#include <imgui/imgui.h>
#include <imgui/imgui_impl_opengl3.h>
#include <imgui/imgui_impl_glfw.h>
namespace Drengr {
namespace UI {
class UIWindow
{
public:
bool Begin(const char* title);
void End();
virtual void Draw() = 0;
protected:
bool show = true;
};
}
}
|
Drengr-Engine/Drengr
|
Engine/src/core/windows/ui/InspectorWindow.h
|
#pragma once
#include "UiWindow.h"
#include <core/graphics/cameras/Camera.h>
namespace Drengr {
namespace UI {
class InspectorWindow : public UIWindow
{
public:
// Inherited via UIWindow
virtual void Draw() override;
};
}
}
|
Drengr-Engine/Drengr
|
Engine/src/core/graphics/buffers/VertexArrayObject.h
|
<gh_stars>0
#pragma once
#include <glad/glad.h>
#include "VertexBuffer.h"
namespace Drengr {
class VertexArrayObject
{
public:
VertexArrayObject();
void AddAttribPointer(VertexBuffer& vbo, unsigned int layout, unsigned int size, unsigned int stride, void* offset);
void Bind();
void Unbind();
void Delete();
private:
unsigned int m_ID;
};
}
|
Drengr-Engine/Drengr
|
Engine/src/application/Application.h
|
#pragma once
#include <optional>
#include <core/windows/ui/UI.h>
#include <core/graphics/renderer/Renderer.h>
#include <core/graphics/assets/Shader.h>
#include <core/graphics/cameras/Camera.h>
#include <map>
namespace Drengr {
class Application
{
public:
Application();
virtual ~Application();
std::optional<int> Run();
static unsigned int framebuffer;
static unsigned int textureColorBuffer;
private:
static Application* m_instance;
UI::UI m_UI;
//Renderer<Vertex> rend;
std::map<const char*, Shader> m_shaders;
bool m_run = true;
};
Application* CreateApplication();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.