int reverse_v(void) { char bp[1024]; char *term; char **area; char *cap; area = NULL; if ((term = getenv("TERM")) == NULL) { print_err("Cannot determine term\n"); return (-1); } if (tgetent(bp, term) != 1) return (-1); cap = xtgetstr("so", area); if (!cap) return (-1); tputs(cap, 1, outc); return (0); }
static void control_parameter_init() { FILE *fp_control_para; int buf[32]; int i; if((fp_control_para=fopen(CONTROL_PARAMETER,"r"))==NULL){ printf("can not open control parameter file\n"); return ; } for(i=0;i<32;i++){ if(fscanf(fp_control_para,"%d,",buf+i)==EOF){ print_err("control parameter file error\n"); fclose(fp_control_para); return; } } fclose(fp_control_para); for(i=0;i<32;i++) K.k[i]=buf[i]; }
int waypoint_modify (uint8 *waypoint, int no) { int i = 0; waypoint_list_s *wp = waypoint_list_head; for(i= 0; i < no; i++) { if (wp == NULL){ print_err("waypoint list node is NULL, modify failed\n"); return -1; } wp = wp->next; } //memcpy(&wp->waypoint, waypoint, sizeof(waypoint_s)); wp->waypoint.id = *(uint16*)(waypoint); wp->waypoint.task = *(waypoint+2); wp->waypoint.task_para = *(waypoint+3); wp->waypoint.v = *(float*)(waypoint+4); wp->waypoint.lon = *(double*)(waypoint+8); wp->waypoint.lat = *(double*)(waypoint+16); wp->waypoint.h = *(float*)(waypoint+24); return 0; }
static int on_header_field(http_parser* parser, const char* at, size_t length) { evweb_header_line* current_line; size_t current_length; evweb_request* request = &(((evweb_http_processer*)parser)->request); print_debug("header field received: %.*s\n", (int)length, at); current_line = request->header_lines + request->num_header_lines - 1; if (true == request->last_was_value) { request->num_header_lines += 1; if (request->num_header_lines > request->max_num_header_lines) { request->max_num_header_lines *= 2; print_debug("expanding the number of headers we can store to %d\n", request->max_num_header_lines); request->header_lines = realloc(request->header_lines, request->max_num_header_lines * sizeof (evweb_header_line)); if (NULL == request->header_lines) { print_err("failed to allocate memory to expand the number of headers we can store: %s\n", strerror(errno)); return 1; } } current_line = request->header_lines + request->num_header_lines - 1; memset(current_line, 0, sizeof (evweb_header_line)); } else { print_debug("adding %zu to the previous header field of length %zu\n", length, current_line->field_len); print_debug("previous (incomplete) header field = %s\n", current_line->field); } current_length = current_line->field_len; current_line->field_len += length; current_line->field = realloc(current_line->field, current_line->field_len+1); memcpy(current_line->field + current_length, at, length); current_line->field[current_line->field_len] = '\0'; request->last_was_value = false; return 0; }
void param(int level) { int this_line = line_cnt; pTreeType[this_line][0] = PARAM; pTreeType[this_line][1] = level; findType(this_line); id_num_check(ID,this_line); if(strcmp(tokenPos->textOfLine,"[") == 0) { //교제에 있는 C-언어의 정의에서 전역변수로 배열을 정의할때 //ID [NUM]이 되기 때문에 다른 하위 Terminal로 넘어가지 않고 바로 종결. NUM만 있으면 되니. push(LSGWAL, this_line); if(strcmp(tokenPos->textOfLine,"]") != 0) { id_num_check(NUM,this_line); if(strcmp(tokenPos->textOfLine,"]") != 0) { print_err(tokenPos->lineNum,tokenPos->textOfLine,"PARAM","]",tokenPos->tokenType); } else { push(RSGWAL, this_line); } } else { push(RSGWAL, this_line); } } }
int main(void) { stackstr errstk = {0}, stk = {0}; int c, linenbr = 0, errcount = 0, linelen; char line[MAXLINE]; while ((linelen = getl(line, MAXLINE)) > 0) { linenbr++; scanline(&stk, &errstk, line, linelen); if (errstk.top) { print_err(&errstk, linenbr); errcount++; } } if (errcount) printf("%d lines contained error(s)\n", errcount); else printf("Well, *I* didn't find any syntax errors, but don't take my word for it...:)\n"); return 0; }
static char *find_cmd_loop(char **exec, int i, char **cmd) { char *path; path = add_file_to_path(exec[i], *cmd); if (access(path, F_OK) != -1) { if (access(path, X_OK) != -1) { strfree_2d(exec); return (path); } else { wait_children(); g_exit_status = PERM_DENIED_EXIT_STATUS; print_err(path, PERMISSION_DENIED); } } free(path); return (0); }
void factor(int level) { int this_line = line_cnt; list<line>::iterator look_var; look_var = tokenPos; look_var ++; if(strcmp(tokenPos->textOfLine,"(") == 0 ) { push(LGWAL,this_line); push_child(this_line,EXP); exp(level); push(RGWAL,this_line); } else if(tokenPos->tokenType == NUM ) { push(NUM,this_line); pTreeType[this_line][0] = IDEN; pTreeType[this_line][1] = level; } else if(tokenPos->tokenType == ID) { if(strcmp(look_var->textOfLine,"(") == 0 ) { push_child(this_line,CALL); call(level); } else { push_child(this_line,VAR); var(level); } } else { print_err(tokenPos->lineNum,tokenPos->textOfLine,"FACTOR","(, NUM, ID",tokenPos->tokenType); } }
int dsm_invalidatepage_internal(dhandle chunk_id, dhandle page_offset) { dsm_chunk_meta *chunk_meta = &g_dsm->g_dsm_page_map[chunk_id]; dsm_page_meta *page_meta = &chunk_meta->pages[page_offset]; char *base_ptr = chunk_meta->g_base_ptr; char *page_start_addr = base_ptr + page_offset * PAGESIZE; // Change permissions to NONE // set the new owner for this page // TODO read-only pages can be kept log("Acquiring mutex lock, chunk_id: %"PRIu64", %"PRIu64"\n", chunk_id, page_offset); if (mprotect(page_start_addr, PAGESIZE, PROT_NONE) == -1) { print_err("mprotect failed for addr=%p, error=%s\n", page_start_addr, strerror(errno)); return -1; } pthread_mutex_lock(&page_meta->lock); page_meta->page_prot = PROT_NONE; page_meta->nodes_reading[g_dsm->c.this_node_idx] = 0; pthread_mutex_unlock(&page_meta->lock); log("Released lock, chunk_id: %"PRIu64", %"PRIu64"\n", chunk_id, page_offset); return 0; }
void cmd_answer(WINDOW *window, ToxWindow *self, Tox *m, int argc, char (*argv)[MAX_STR_SIZE]) { TOXAV_ERR_ANSWER error; const char *error_str; if ( argc != 0 ) { error_str = "Unknown arguments."; goto on_error; } if ( !CallControl.av ) { error_str = "Audio not supported!"; goto on_error; } if ( !CallControl.pending_call ) { error_str = "No incoming call!"; goto on_error; } toxav_answer(CallControl.av, self->num, CallControl.audio_bit_rate, CallControl.video_bit_rate, &error); if ( error != TOXAV_ERR_ANSWER_OK ) { if ( error == TOXAV_ERR_ANSWER_FRIEND_NOT_CALLING ) error_str = "No incoming call!"; else if ( error == TOXAV_ERR_ANSWER_CODEC_INITIALIZATION ) error_str = "Failed to initialize codecs!"; else if ( error == TOXAV_ERR_ANSWER_FRIEND_NOT_FOUND ) error_str = "Friend not found!"; else if ( error == TOXAV_ERR_ANSWER_INVALID_BIT_RATE ) error_str = "Invalid bit rate!"; else error_str = "Internal error!"; goto on_error; } /* Callback will print status... */ callback_recv_starting(self->num); CallControl.pending_call = false; return; on_error: print_err (self, error_str); }
void cmd_hangup(WINDOW *window, ToxWindow *self, Tox *m, int argc, char (*argv)[MAX_STR_SIZE]) { const char *error_str; if (argc != 0) { error_str = "Unknown arguments."; goto on_error; } if ( !ASettins.av ) { error_str = "Audio not supported!"; goto on_error; } ToxAvError error; if (toxav_get_call_state(ASettins.av, self->call_idx) == av_CallInviting) { error = toxav_cancel(ASettins.av, self->call_idx, self->num, "Only those who appreciate small things know the beauty that is life"); #ifdef SOUND_NOTIFY stop_sound(self->ringing_sound); #endif line_info_add(self, NULL, NULL, NULL, SYS_MSG, 0, 0, "Call canceled!"); } else { error = toxav_hangup(ASettins.av, self->call_idx); } if ( error != ErrorNone ) { if ( error == ErrorInvalidState ) error_str = "Cannot hangup in invalid state!"; else if ( error == ErrorNoCall ) error_str = "No call!"; else error_str = "Internal error!"; goto on_error; } return; on_error: print_err (self, error_str); }
int waypoint_insert (uint8 *waypoint, int no) { int i = 0; waypoint_list_s *wp = waypoint_list_head; waypoint_list_s *prev = NULL; waypoint_list_s *curr = malloc(sizeof(waypoint_list_s)); //memcpy(&curr->waypoint, waypoint, sizeof(waypoint_s));; curr->waypoint.id = *(uint16*)(waypoint); curr->waypoint.task = *(waypoint+2); curr->waypoint.task_para = *(waypoint+3); curr->waypoint.v = *(float*)(waypoint+4); curr->waypoint.lon = *(double*)(waypoint+8); curr->waypoint.lat = *(double*)(waypoint+16); curr->waypoint.h = *(float*)(waypoint+24); for(i= 0; i < no; i++) { if (wp == NULL){ print_err("waypoint list node is NULL, insert failed\n"); return -1; } wp = wp->next; } prev = wp->prev; curr->next = wp; wp->prev = curr; curr->prev = prev; prev->next = curr; wp = waypoint_list_head; waypoint_info.received_num ++; waypoint_info.total_num ++; //reassign id no for(i=0;i<waypoint_info.total_num;i++){ wp->waypoint.id = i; wp = wp->next; } return 0; }
static void heli_configuration_init() { FILE *fp_heli_config; uint32 buf[11]; int i; if((fp_heli_config=fopen(HELI_CONFIGURATION,"r"))==NULL){ printf("can not open heli configuration file\n"); return ; } for(i=0;i<11;i++){ if(fscanf(fp_heli_config,"%u,",buf+i)==EOF){ print_err("heli configuration file error\n"); fclose(fp_heli_config); return; } } fclose(fp_heli_config); for(i=0;i<11;i++) *((uint8*)(&aircraft_preparing_status)+i)=(uint8)(buf[i]&0xff); update_setting_status(&aircraft_preparing_status); switch(aircraft_preparing_status.o_fp){ case SERVO_PWM_PERIOD_20: set_servo_pwm_period(20000); break; case SERVO_PWM_PERIOD_14: set_servo_pwm_period(14000); break; case SERVO_PWM_PERIOD_7: set_servo_pwm_period(7000); break; case SERVO_PWM_PERIOD_3: set_servo_pwm_period(3031); break; default: break; } }
void stmt(int level) { int this_line = line_cnt; if(strcmp(tokenPos->textOfLine,"if") == 0) { push_child(this_line,IF); ifstmt(level); } else if(strcmp(tokenPos->textOfLine,"while") == 0) { push_child(this_line,WHILE); itestmt(level); } else if(strcmp(tokenPos->textOfLine,"return") == 0) { push_child(this_line,RETURN); return_stmt(level); } else if(strcmp(tokenPos->textOfLine,"{") == 0) { push_child(this_line,COM_STMT); compound_stmt(level); } else if(tokenPos->tokenType == ID || tokenPos->tokenType == NUM || strcmp(tokenPos->textOfLine,"(") == 0 || strcmp(tokenPos->textOfLine,";") == 0) { push_child(this_line,EXP_STMT); exp_stmt(level); } else { print_err(tokenPos->lineNum,tokenPos->textOfLine,"STMT","IF,WHILE,RETURN,{,ID,NUM,(,;",tokenPos->tokenType); } }
/* Write a deleted node record to the database */ Int2 DB_WriteTaxDelNodeRec(Int4 taxId) { if(taxId < 0) { ErrPostEx(SEV_INFO, 3, 0, "DB_WriteTaxDelNodeRec: Passed taxId < 0."); return(-1); } /*set up the input parameters */ SQLBindParameter(hstmt_del, 1, SQL_PARAM_INPUT, SQL_C_LONG,SQL_INTEGER, 0, 0, &taxId, 0, NULL); /* set auto commit on */ SQLSetConnectAttr( hdbc, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER)SQL_AUTOCOMMIT_ON, SQL_NTS); /* execute statment */ if (SQLExecute (hstmt_del) != SQL_SUCCESS){ ErrPostEx(SEV_ERROR,0,0, "DB_WriteTaxDelRec: unable to execute insert statement. "); print_err(hstmt_del); return FALSE; } return TRUE; }
int dsm_freechunk_internal(dhandle chunk_id, const uint8_t *requestor_host, uint32_t requestor_port) { log("Freeing chunk %"PRIu64", requestor=%s:%d\n", chunk_id, requestor_host, requestor_port); int requestor_idx = get_request_idx(g_dsm, requestor_host, requestor_port); dsm_chunk_meta *chunk_meta = &g_dsm->g_dsm_page_map[chunk_id]; if (g_dsm->is_master) { acquire_chunk_lock(chunk_id); if (chunk_meta->count == 0) { print_err("Nothing to free. Chunk not allocated size is 0\n"); release_chunk_lock(chunk_id); return -1; } chunk_meta->ref_counter--; chunk_meta->clients_using[requestor_idx] = 0; log("ref counter %d\n", chunk_meta->ref_counter); fetch_remotely_owned_pages(chunk_id, requestor_idx); release_chunk_lock(chunk_id); } if (g_dsm->is_master == 0 || chunk_meta->ref_counter == 0) dsm_really_freechunk(chunk_id); // MARK1 return 0; }
static int dsm_getpage_internal_nonmaster(dsm_chunk_meta *chunk_meta, dhandle page_offset, uint8_t **data, uint64_t *count, uint32_t flags) { log("I am not the master. Take the page I have.\n"); int error = 0; dsm_page_meta *page_meta = &chunk_meta->pages[page_offset]; char *base_ptr = chunk_meta->g_base_ptr; char *page_start_addr = base_ptr + page_offset*PAGESIZE; memcpy(*data, page_start_addr, PAGESIZE); *count = PAGESIZE; if (flags & FLAG_PAGE_WRITE) { // Change permissions to NONE // set the new owner for this page if ( (error = mprotect(page_start_addr, PAGESIZE, PROT_NONE)) == -1) { print_err("mprotect failed for addr=%p, error=%s\n", page_start_addr, strerror(errno)); return -1; } page_meta->page_prot = PROT_NONE; page_meta->nodes_reading[g_dsm->c.this_node_idx] = 0; } return 0; }
static char *construct_flag(option_clone *opt) { char *str=NULL; unsigned int length=1; char *prefix=(char *)SHORT_FLAG; tvalue uselong=FALSE; if(opt->longflag != NULL) { length+=LONG_FLAG_LENGTH+strlen(opt->longflag); prefix=(char *)LONG_FLAG; uselong=TRUE; } else length+=SHORT_FLAG_LENGTH+1; str=malloc(length); if(!str) { print_err("Error: Ran out of memory in getopt_clone while constructing a" " flag representation.\n"); return NULL; } memset(str,0,length); strcat(str,prefix); if(uselong==TRUE) strcat(str,opt->longflag); else { unsigned int pos=strlen(str); str[pos] = opt->shortflag; str[pos+1] = 0; } return str; }
void cmd_hangup(WINDOW *window, ToxWindow *self, Tox *m, int argc, char (*argv)[MAX_STR_SIZE]) { const char *error_str; if ( argc != 0 ) { error_str = "Unknown arguments."; goto on_error; } if ( !CallControl.av ) { error_str = "Audio not supported!"; goto on_error; } #ifdef VIDEO callback_video_end(self->num); #endif /* VIDEO */ if ( CallControl.pending_call ) { /* Manually send a cancel call control because call hasn't started */ toxav_call_control(CallControl.av, self->num, TOXAV_CALL_CONTROL_CANCEL, NULL); callback_call_canceled(self->num); } else { stop_transmission(&CallControl.calls[self->num], self->num); callback_call_ended(self->num); } CallControl.pending_call = false; return; on_error: print_err (self, error_str); }
static void smbus_print_error(unsigned char host_status_register) { print_err("smbus_error: "); print_err_hex8(host_status_register); print_err("\n"); if (host_status_register & (1 << 4)) { print_err("Interrup/SMI# was Failed Bus Transaction\n"); } if (host_status_register & (1 << 3)) { print_err("Bus Error\n"); } if (host_status_register & (1 << 2)) { print_err("Device Error\n"); } if (host_status_register & (1 << 1)) { print_err("Interrupt/SMI# was Successful Completion\n"); } if (host_status_register & (1 << 0)) { print_err("Host Busy\n"); } }
static char *check_in_path(char **cmd) { char *path; int i; char **exec; if ((path = ft_getenv("PATH")) != NULL) { exec = ft_strsplit(path, ':'); i = 0; while (exec[i]) { if ((path = find_cmd_loop(exec, i++, cmd))) return (path); } strfree_2d(exec); } if (g_exit_status > 0) return (NULL); wait_children(); g_exit_status = NOT_FOUND_EXIT_STATUS; print_err(cmd[0], CMD_NOT_FOUND); return (NULL); }
/* * Extract data and output it as PS * * Returns 0 if all went well, 1 if something went wrong. */ static int extract_data(int input, FILE *output, uint16_t program_number, int max, int verbose, int quiet) { int err; PES_reader_p reader; err = build_PES_reader(input,TRUE,!quiet,!quiet,program_number,&reader); if (err) { print_err("### Error building PES reader over input file\n"); return 1; } // Temporarily, just writes out PES packets, not a PS stream... for (;;) { size_t count; err = read_next_PES_packet(reader); if (err == EOF) break; else if (err) { print_err("### Error reading next PES packet\n"); (void) free_PES_reader(&reader); return 1; } err = write_pack_header(output); if (err) { print_err("### Error writing PS pack header\n"); (void) free_PES_reader(&reader); return 1; } // It is possible that the TS data for video might have specified a zero // length in the PES. Our TS reader will have read all of the packet for // us, but will not have "adjusted" said length at the start of the packet. // It is thus up to us to catch this case and amend it before we output // the data... if (reader->packet->data[4] == 0 && reader->packet->data[5] == 0) { int32_t PES_packet_length = reader->packet->data_len - 6; byte *start = reader->packet->data; // Our maximum length is determined by the maximum length we can // indicate in the two bytes of the PES_packet_length. When we're // *writing* data, we also have to allow for writing the two flag // bytes and PES_header_data_length that come thereafter. #define MAX_LENGTH 0xFFFF if (PES_packet_length > MAX_LENGTH) { fprint_err("PES packet of 'zero' length is really %6d - too long for one packet\n", PES_packet_length); // Output what we can of the original packet reader->packet->data[4] = (MAX_LENGTH & 0xFF00) >> 8; reader->packet->data[5] = (MAX_LENGTH & 0x00FF); // Remember that we also write out the 6 bytes preceding those // MAX_LENGTH bytes... fprint_err(".. writing out %5d (%5d total)\n",MAX_LENGTH,MAX_LENGTH+6); count = fwrite(reader->packet->data,MAX_LENGTH+6,1,output); if (count != 1) { print_err("### Error writing (start of) PES packet out to file\n"); (void) free_PES_reader(&reader); return 1; } PES_packet_length -= MAX_LENGTH; start += MAX_LENGTH+6; while (PES_packet_length > 0) { // Now, when writing out chunks of data as PES packets, // we have 6 bytes of header (00 00 01 stream_id length/length) // followed by two bytes of flags (81 00) and a zero // PES_header_data_length (00). Those last three bytes have // to be included in the PES_packet_length of the PES packet // we write out, which means that the longest "chunk" of data // we can write is three less than the (otherwise) maximum. int this_length = min(MAX_LENGTH-3,PES_packet_length); int err; fprint_err(".. writing out %5d\n",this_length); err = write_PES_packet(output,start,this_length, reader->packet->data[3]); if (err) { print_err("### Error writing (part of) PES packet out to file\n"); (void) free_PES_reader(&reader); return 1; } PES_packet_length -= this_length; start += this_length; } } else {
int main(int argc, char** argv){ (void)umask(0); //checking number of arguments and converting it (char*) to (int) if(argc != 2){ printf("Invalid argument. Number of clients = %s\n",argv[1]); exit(-1); } int n = atoi(argv[1]); if(n <= 0 || n == INT_MAX) print_err("invalid number of clients"); //create or get message quewe key_t msg_key = ftok(IPC_FTOK_FILE, 1); if(msg_key < 0) print_err("generation of IPC key"); int msgid = msgget(msg_key, 0666 | IPC_CREAT); if(msgid < 0) print_err("create or get message quewe for sendind"); //Messege quewe info for debagging struct msginfo msg_data; if(msgctl(msgid, MSG_INFO, (struct msqid_ds*)&msg_data) < 0) print_err("get message quewe limits data"); printf("Max message lenght = %d\nMax quewe lenght = %d\nMax number of quewes = %d\n", msg_data.msgmax, msg_data.msgmnb, msg_data.msgmni); //open data file (format - from "generate" program) int fd; if((fd = open(DATA, O_RDONLY, 0666)) < 0) print_err("open data file"); //read matrixes from file int *mtx1,*mtx2; int mtx_sizes[3]; read_matrixes(mtx_sizes, &mtx1, &mtx2, fd); if(close(fd) < 0) print_err("close data file"); //create supporting variables int i,j,tmp; //create result matrix int* res = (int*)malloc(mtx_sizes[0]*mtx_sizes[0]*sizeof(int)); //defining work for different threads struct thread_data* thread; thread = (struct thread_data*)malloc((n+1)*sizeof(struct thread_data)); int total_size_of_work = mtx_sizes[0]*mtx_sizes[2]; if(total_size_of_work > n){ //setting up number of elements (work_size) for calculation for each thread (case n < total_size_of_work) int initial_work = (mtx_sizes[0]*mtx_sizes[2])/n; int rest_work = (mtx_sizes[0]*mtx_sizes[2])%n; for(i=0;i<n;i++) thread[i].work_size = initial_work; for(i=0;rest_work>0;rest_work--) ++thread[i++].work_size; //setting up coordinates of start point for each thread (case n < total_size_of_work) thread[0].i_start_index = thread[0].j_start_index = 0; for(i=1;i<n;i++) { thread[i].j_start_index = thread[i-1].j_start_index + thread[i-1].work_size/mtx_sizes[0]; if( (thread[i].i_start_index = thread[i-1].i_start_index + thread[i-1].work_size%mtx_sizes[0]) >= mtx_sizes[0]){ thread[i].j_start_index++; thread[i].i_start_index = thread[i-1].work_size%mtx_sizes[0] - mtx_sizes[0] + thread[i-1].i_start_index; } } //calculating usage of colomns and rows for each thread thread[n].i_start_index = 0; thread[n].j_start_index = mtx_sizes[2]; //here is a trick: we consider imaginary element with (i,j) = (0,mtx_size[2]) for short code for(i=0;i<n;i++){ thread[i].col_count = (thread[i+1].i_start_index == 0) ? thread[i+1].j_start_index - thread[i].j_start_index : thread[i+1].j_start_index - thread[i].j_start_index + 1; if(thread[i].col_count == 1) thread[i].row_count = thread[i+1].i_start_index - thread[i].i_start_index; else if(thread[i].col_count == 2) thread[i].row_count = (thread[i+1].i_start_index >= thread[i].i_start_index) ? mtx_sizes[0] : mtx_sizes[0] + thread[i+1].i_start_index - thread[i+1].i_start_index; else thread[i].row_count = mtx_sizes[0]; } } else { //setting up numbers of elements for calculation and respective coordinates for each thread (case n >= total_size_of_work) thread[0].i_start_index = thread[0].j_start_index = 0; thread[0].work_size = thread[0].col_count = thread[0].row_count = 1; for(i=1;i<total_size_of_work;i++){ thread[i].work_size = 1; thread[i].col_count = 1; thread[i].row_count = 1; thread[i].i_start_index = (thread[i-1].i_start_index == (mtx_sizes[0] - 1) ) ? 0 : thread[i-1].i_start_index + 1; thread[i].j_start_index = (thread[i].i_start_index == 0) ? thread[i-1].j_start_index + 1 : thread[i-1].j_start_index; } for(i=total_size_of_work;i<n;i++) thread[i].work_size = 0; } //debugging information for(i = 0; i < n; i++) printf("%d %d %d %d %d\n", thread[i].work_size, thread[i].row_count, thread[i].col_count, thread[i].i_start_index, thread[i].j_start_index); //start timer struct timeval start_time; gettimeofday(&start_time, NULL); //create and start threads for clients pthread_t *thread_id; thread_id = (pthread_t*)malloc(n*sizeof(pthread_t)); for(i = 0; i < n; i++){ thread[i].msgid = msgid; thread[i].mtx1 = mtx1; thread[i].mtx2 = mtx2; thread[i].res = res; thread[i].mtx_sizes[0] = mtx_sizes[0]; thread[i].mtx_sizes[1] = mtx_sizes[1]; thread[i].mtx_sizes[2] = mtx_sizes[2]; if(pthread_create(&thread_id[i], NULL, client, &thread[i]) > 0) print_err("create thread"); } //waiting for threads for(i = 0;i < n;i++) pthread_join(thread_id[i], (void**)NULL); //free used heap free(mtx1); free(mtx2); free(thread); free(thread_id); //print time of calculation struct timeval end_time; gettimeofday(&end_time,NULL); int delta = end_time.tv_usec - start_time.tv_usec; int sec = delta / (1000 * 1000); int msec = (delta - sec * 1000 * 1000) / 1000; int usec = delta - sec * 1000 * 1000 - msec * 1000; printf("Working time: %ds %dms %dmcs\n", sec, msec, usec); //synchronization of clients' shutting down struct client_msg msg_s; struct client_msg msg_r; for(i=0;i<n;i++){ msg_r.mtype = BYE_MSG_ID; if(msgrcv(msgid, (void*) &msg_r, sizeof(int),BYE_MSG_ID,0)<0) print_err("recieve BYE message from client"); msg_s.mtype = msg_r.data[0]; msg_s.data[0] = (i == n-1) ? 0 : 1; if(msgsnd(msgid, (void*) &msg_s, sizeof(int), 0) < 0) print_err("send BYE from server messege"); } //delete message quewe if(msgrcv(msgid, (void*) &msg_r, 0, msg_r.data[0], 0)<0) print_err("recieve BYE message from last client"); if(msgctl(msgid, IPC_RMID, NULL) < 0) print_err("delete message quewe"); //write integer matrix into RES if ((fd = open(RES, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0) print_err("open result file"); char* buffer; char space = ' ', end = '\n'; for(i = 0;i < mtx_sizes[0];i++) { for(j = 0;j < mtx_sizes[2];j++) { buffer = itoa(*(res + i*mtx_sizes[1] + j)); write_into_file(fd,buffer,strlen(buffer)); write_into_file(fd,&space,1); free(buffer); } write_into_file(fd,&end,1); } free(res); if(close(fd)) print_err("close result file"); return 0; }
size_t write_into_file(int fd,void* addr, const size_t size){ size_t len; if((len = write(fd,addr,size)) < 0) print_err("write into file"); return len; }
size_t read_int_from_file(void* addr,int fd){ size_t size; if((size = read(fd,addr,sizeof(int))) < 0) print_err("read from file"); return size; }
static void do_extension_pdf(int immediate) { int i; if(scan_keyword("literal")){ new_whatsit(pdf_literal_node); if(scan_keyword("direct")) set_pdf_literal_mode(tail,direct_always); else if(scan_keyword("page")) set_pdf_literal_mode(tail,direct_page); else set_pdf_literal_mode(tail,set_origin); scan_toks(false,true); set_pdf_literal_type(tail,normal); set_pdf_literal_data(tail,def_ref); }else if(scan_keyword("dest")){ scan_pdfdest(static_pdf); }else if(scan_keyword("annot")){ scan_annot(static_pdf); }else if(scan_keyword("save")){ new_whatsit(pdf_save_node); }else if(scan_keyword("restore")){ new_whatsit(pdf_restore_node); }else if(scan_keyword("setmatrix")){ new_whatsit(pdf_setmatrix_node); scan_toks(false,true); set_pdf_setmatrix_data(tail,def_ref); }else if(scan_keyword("obj")){ scan_obj(static_pdf); if(immediate){ if(obj_data_ptr(static_pdf,pdf_last_obj)==0) normal_error("pdf backend","\\pdfextension obj 'reserveobjnum' cannot be used with \\immediate"); pdf_write_obj(static_pdf,pdf_last_obj); } }else if(scan_keyword("refobj")){ scan_refobj(static_pdf); }else if(scan_keyword("colorstack")){ scan_int(); if(cur_val>=colorstackused()){ print_err("Unknown color stack number "); print_int(cur_val); help3 ("Allocate and initialize a color stack with \\pdfextension colorstackinit.", "I'll use default color stack 0 here.", "Proceed, with fingers crossed."); error(); cur_val= 0; } if(cur_val<0){ print_err("Invalid negative color stack number"); help2("I'll use default color stack 0 here.", "Proceed, with fingers crossed."); error(); cur_val= 0; } if(scan_keyword("set")) i= colorstack_set; else if(scan_keyword("push")) i= colorstack_push; else if(scan_keyword("pop")) i= colorstack_pop; else if(scan_keyword("current")) i= colorstack_current; else i= -1; if(i>=0){ new_whatsit(pdf_colorstack_node); set_pdf_colorstack_stack(tail,cur_val); set_pdf_colorstack_cmd(tail,i); set_pdf_colorstack_data(tail,null); if(i<=colorstack_data){ scan_toks(false,true); set_pdf_colorstack_data(tail,def_ref); } }else{ print_err("Color stack action is missing"); help3("The expected actions for \\pdfextension colorstack:", " set, push, pop, current", "I'll ignore the color stack command."); error(); } }else if(scan_keyword("startlink")){ scan_startlink(static_pdf); }else if(scan_keyword("endlink")){ if(abs(mode)==vmode) normal_error("pdf backend","\\pdfextension endlink cannot be used in vertical mode"); new_whatsit(pdf_end_link_node); }else if(scan_keyword("startthread")){ new_annot_whatsit(pdf_start_thread_node); scan_thread_id(); }else if(scan_keyword("endthread")){ new_whatsit(pdf_end_thread_node); }else if(scan_keyword("thread")){ new_annot_whatsit(pdf_thread_node); scan_thread_id(); }else if(scan_keyword("outline")){ scan_pdfoutline(static_pdf); }else if(scan_keyword("glyphtounicode")){ glyph_to_unicode(); }else if(scan_keyword("catalog")){ scan_pdfcatalog(static_pdf); }else if(scan_keyword("fontattr")){ scan_font_ident(); i= cur_val; if(i==null_font) normal_error("pdf backend","invalid font identifier"); scan_toks(false,true); set_pdf_font_attr(i,tokens_to_string(def_ref)); if(str_length(pdf_font_attr(i))==0){ flush_str((str_ptr-1)); set_pdf_font_attr(i,0); } }else if(scan_keyword("mapfile")){ scan_toks(false,true); pdfmapfile(def_ref); delete_token_ref(def_ref); }else if(scan_keyword("mapline")){ scan_toks(false,true); pdfmapline(def_ref); delete_token_ref(def_ref); }else if(scan_keyword("includechars")){ pdf_include_chars(static_pdf); }else if(scan_keyword("info")){ scan_toks(false,true); pdf_info_toks= concat_tokens(pdf_info_toks,def_ref); }else if(scan_keyword("names")){ scan_toks(false,true); pdf_names_toks= concat_tokens(pdf_names_toks,def_ref); }else if(scan_keyword("trailer")){ scan_toks(false,true); pdf_trailer_toks= concat_tokens(pdf_trailer_toks,def_ref); }else{ tex_error("unexpected use of \\pdfextension",null); } }
int main(int argc, char *argv[]) { #if 1 glite_jp_context_t jpctx; glite_jp_is_conf *conf; glite_jpis_context_t isctx; int ret; long int uniqueid; char *ps, *feedid; jpctx = NULL; isctx = NULL; conf = NULL; glite_jp_init_context(&jpctx); if (glite_jp_get_conf(argc, argv, NULL, &conf) != 0) goto fail; if (glite_jpis_init_context(&isctx, jpctx, conf) != 0) goto fail; if (glite_jpis_init_db(isctx) != 0) goto fail; printf("dropping...\n"); if (glite_jpis_dropDatabase(isctx) != 0) goto faildb; printf("initializing...\n"); if (glite_jpis_initDatabase(isctx) != 0) goto faildb; printf("locking...\n"); do { if ((ret = glite_jpis_lockUninitializedFeed(isctx, &uniqueid, &ps)) == ENOLCK) goto faildb; if (ret == 0) { printf("locked: uniqueid=%li, ps=%s\n", uniqueid, ps); free(ps); asprintf(&feedid, "feed://%lu", uniqueid + 3); if (glite_jpis_initFeed(isctx, uniqueid, feedid, (time_t)10000) != 0) { free(feedid); goto faildb; } free(feedid); if (glite_jpis_unlockFeed(isctx, uniqueid) != 0) goto faildb; } } while (ret == 0); if (glite_jpis_tryReconnectFeed(isctx, uniqueid, time(NULL) + 10) != 0) goto faildb; glite_jpis_free_db(isctx); glite_jpis_free_context(isctx); glite_jp_free_conf(conf); glite_jp_free_context(jpctx); return 0; faildb: glite_jpis_free_db(isctx); fail: printf("failed\n"); glite_jpis_free_context(isctx); glite_jp_free_conf(conf); if (jpctx) { print_err(jpctx); glite_jp_free_context(jpctx); } return 1; #endif #if 0 glite_jp_context_t ctx; glite_jp_is_conf *conf; void *blob; size_t len; int ret, i; glite_jp_query_rec_t **queries; ret = 0; glite_jp_init_context(&ctx); if (glite_jp_get_conf(argc, argv, NULL, &conf) != 0) goto fail_ctx; if ((ret = glite_jpis_db_queries_serialize(&blob, &len, conf->feeds[0]->query)) != 0) goto fail; if (write(1, blob, len) != len) { ret = errno; free(blob); goto fail; } if ((ret = glite_jpis_db_queries_deserialize(&queries, blob, len)) != 0) goto fail_blob; i = 0; while (queries[i] && queries[i]->attr) { printf("query: attr=%s, op=%d, value=%s, value2=%s, bin=%d\n", queries[i]->attr, queries[i]->op, queries[i]->value, queries[i]->value2, queries[i]->binary); free(queries[i]->attr); free(queries[i]->value); free(queries[i]->value2); free(queries[i]); i++; } free(queries); free(blob); glite_jp_free_context(ctx); return 0; fail_blob: free(blob); fail: fprintf(stderr, "fail: %s\n", strerror(ret)); fail_ctx: glite_jp_free_context(ctx); return 1; #endif }
int main(int argc, char *argv[]) { char ch; char str[STR_BUFFSIZE]; char plom_help_string[] = "PLOM Kalman\n" "usage:\n" "kalman [implementation] [--no_dem_sto] [--no_white_noise] [--no_diff]\n" " [-s, --DT <float>] [--eps_abs <float>] [--eps_rel <float>]\n" " [-g, --freeze_forcing <float>]\n" " [-r, --traj] [-p, --path <path>] [-i, --id <integer>]\n" " [-b, --no_trace] [-e, --no_hat] [--prior] [--transf]\n" " [-q, --quiet] [-P, --pipe]" " [-h, --help]\n" "where implementation is 'sde' (default)\n" "options:\n" "\n" "-q, --quiet no verbosity\n" "-P, --pipe pipe mode (echo theta.json on stdout)\n" "\n" "--no_dem_sto turn off demographic stochasticity (if possible)\n" "--no_white_noise turn off environmental stochasticity (if any)\n" "--no_diff turn off drift (if any)\n" "\n" "-s, --DT Initial integration time step\n" "--eps_abs Absolute error for adaptive step-size contro\n" "--eps_rel Relative error for adaptive step-size contro\n" "-g, --freeze_forcing freeze the metadata to their value at the specified time\n" "\n" "-r, --traj print the trajectories\n" "--prior add log(prior) to the estimated loglik\n" "--transf add log(JacobianDeterminant(transf)) to the estimated loglik. (combined to --prior, gives posterior density in transformed space)\n" "-p, --path path where the outputs will be stored\n" "-b, --no_trace do not write trace_<id>.output file\n" "-h, --no_hat do not write hat_<general_id>.output file\n" "-d, --no_pred_res do not write pred_res_<general_id>.output file (prediction residuals)\n" "-i, --id general id (unique integer identifier that will be appended to the output files)\n" "-l, --LIKE_MIN particles with likelihood smaller that LIKE_MIN are considered lost\n" "-o, --nb_obs number of observations to be fitted (for tempering)" "-h, --help print the usage on stdout\n"; // general options GENERAL_ID =0; snprintf(SFR_PATH, STR_BUFFSIZE, "%s", DEFAULT_PATH); LIKE_MIN = 1e-17; LOG_LIKE_MIN = log(LIKE_MIN); enum plom_print print_opt = PLOM_PRINT_BEST | PLOM_PRINT_HAT | PLOM_PRINT_PRED_RES; // options OPTION_PRIOR = 0; OPTION_TRANSF = 0; int nb_obs = -1; double freeze_forcing = -1.0; double dt = 0.0, eps_abs = PLOM_EPS_ABS, eps_rel = PLOM_EPS_REL; J = 1; //not an option, needed for print_X enum plom_implementations implementation; enum plom_noises_off noises_off = 0; static struct option long_options[] = { {"traj", no_argument, 0, 'r'}, {"no_dem_sto", no_argument, 0, 'x'}, {"no_white_noise", no_argument, 0, 'y'}, {"no_diff", no_argument, 0, 'z'}, {"DT", required_argument, 0, 's'}, {"eps_abs", required_argument, 0, 'v'}, {"eps_rel", required_argument, 0, 'w'}, {"freeze_forcing", required_argument, 0, 'g'}, {"help", no_argument, 0, 'h'}, {"path", required_argument, 0, 'p'}, {"id", required_argument, 0, 'i'}, {"no_trace", no_argument, 0, 'b'}, {"no_hat", no_argument, 0, 'e'}, {"no_pred_res",no_argument, 0, 'd'}, {"prior", no_argument, &OPTION_PRIOR, 1}, {"transf", no_argument, &OPTION_TRANSF, 1}, {"nb_obs", required_argument, 0, 'o'}, {"quiet", no_argument, 0, 'q'}, {"pipe", no_argument, 0, 'P'}, {"LIKE_MIN", required_argument, 0, 'l'}, {0, 0, 0, 0} }; int option_index = 0; while ((ch = getopt_long (argc, argv, "qPxyzs:v:w:i:l:p:rbhedo:g:", long_options, &option_index)) != -1) { switch (ch) { case 0: break; case 'x': noises_off = noises_off | PLOM_NO_DEM_STO; break; case 'y': noises_off = noises_off | PLOM_NO_ENV_STO; break; case 'z': noises_off = noises_off | PLOM_NO_DRIFT; break; case 'o': nb_obs = atoi(optarg); break; case 'g': freeze_forcing = atof(optarg); break; case 's': dt = atof(optarg); break; case 'v': eps_abs = atof(optarg); break; case 'w': eps_rel = atof(optarg); break; case 'h': print_log(plom_help_string); return 1; case 'p': snprintf(SFR_PATH, STR_BUFFSIZE, "%s", optarg); break; case 'i': GENERAL_ID = atoi(optarg); break; case 'l': LIKE_MIN = atof(optarg); LOG_LIKE_MIN = log(LIKE_MIN); break; case 'r': print_opt |= PLOM_PRINT_X; break; case 'b': print_opt &= ~PLOM_PRINT_BEST; break; case 'e': print_opt &= ~PLOM_PRINT_HAT; break; case 'd': print_opt &= ~PLOM_PRINT_PRED_RES; break; case 'q': print_opt |= PLOM_QUIET; break; case 'P': print_opt |= PLOM_PIPE | PLOM_QUIET; break; case '?': /* getopt_long already printed an error message. */ return 1; default: snprintf(str, STR_BUFFSIZE, "Unknown option '-%c'\n", optopt); print_err(str); return 1; } } argc -= optind; argv += optind; if(argc == 0) { implementation = PLOM_ODE; //with Kalman the SDE uses f_pred of PLOM_ODE (OK will do better)... } else { if (!strcmp(argv[0], "sde")) { implementation = PLOM_ODE; } else { print_log(plom_help_string); return 1; } } plom_unlink_done(SFR_PATH, GENERAL_ID); json_t *settings = load_settings(PATH_SETTINGS); if (!(print_opt & PLOM_QUIET)) { snprintf(str, STR_BUFFSIZE, "Starting plom-Kalman with the following options: i = %d, LIKE_MIN = %g", GENERAL_ID, LIKE_MIN); print_log(str); } json_t *theta = load_json(); struct s_kalman *p_kalman = build_kalman(theta, settings, implementation, noises_off, OPTION_PRIOR, dt, eps_abs, eps_rel, freeze_forcing, nb_obs); json_decref(settings); int64_t time_begin, time_end; if (!(print_opt & PLOM_QUIET)) { time_begin = s_clock(); } back_transform_theta2par(p_kalman->p_par, p_kalman->p_best->mean, p_kalman->p_data->p_it_all, p_kalman->p_data); linearize_and_repeat(p_kalman->p_X, p_kalman->p_par, p_kalman->p_data, p_kalman->p_data->p_it_par_sv); prop2Xpop_size(p_kalman->p_X, p_kalman->p_data, p_kalman->calc[0]); theta_driftIC2Xdrift(p_kalman->p_X, p_kalman->p_best->mean, p_kalman->p_data); FILE *p_file_X = (print_opt & PLOM_PRINT_X) ? plom_fopen(SFR_PATH, GENERAL_ID, "X", "w", header_X, p_kalman->p_data): NULL; FILE *p_file_hat = (print_opt & PLOM_PRINT_HAT) ? plom_fopen(SFR_PATH, GENERAL_ID, "hat", "w", header_hat, p_kalman->p_data): NULL; FILE *p_file_pred_res = (print_opt & PLOM_PRINT_PRED_RES) ? plom_fopen(SFR_PATH, GENERAL_ID, "pred_res", "w", header_prediction_residuals_ekf, p_kalman->p_data): NULL; double log_like = run_kalman(p_kalman->p_X, p_kalman->p_best, p_kalman->p_par, p_kalman->p_kalman_update, p_kalman->p_data, p_kalman->calc, f_prediction_ode, 0, p_file_X, p_file_hat, p_file_pred_res, print_opt); if (print_opt & PLOM_PRINT_X) { plom_fclose(p_file_X); } if (print_opt & PLOM_PRINT_HAT) { plom_fclose(p_file_hat); } if (print_opt & PLOM_PRINT_PRED_RES) { plom_fclose(p_file_pred_res); } if (!(print_opt & PLOM_QUIET)) { time_end = s_clock(); struct s_duration t_exec = time_exec(time_begin, time_end); sprintf(str, "logV: %g", log_like); print_log(str); sprintf(str, "Done in:= %dd %dh %dm %gs", t_exec.d, t_exec.h, t_exec.m, t_exec.s); print_log(str); } if (print_opt & PLOM_PRINT_BEST) { FILE *p_file_trace = plom_fopen(SFR_PATH, GENERAL_ID, "trace", "w", header_trace, p_kalman->p_data); print_trace(p_file_trace, 0, p_kalman->p_best, p_kalman->p_data, log_like); plom_fclose(p_file_trace); } plom_print_done(theta, p_kalman->p_data, p_kalman->p_best, SFR_PATH, GENERAL_ID, print_opt); if (!(print_opt & PLOM_QUIET)) { print_log("clean up..."); } json_decref(theta); clean_kalman(p_kalman); return 0; }
void tex::conditional () { bool b=false; sym s; int m, n; ptr p, q, r; int this_if; ptr save_cond_ptr; int save_scanner_status; push_cond(); save_cond_ptr = cond_ptr; this_if = cur_chr; switch (this_if) { case IF_CHAR_CODE: case IF_CAT_CODE: #define get_x_token_or_active_char() {get_x_token(); \ if (cur_cmd == RELAX && cur_chr == NO_EXPAND_FLAG) { \ cur_cmd = ACTIVE_CHAR; \ cur_chr = tok2sym(cur_tok) - active_base[0]; }} get_x_token_or_active_char(); if (cur_cmd > ACTIVE_CHAR || cur_chr > 255) { m = RELAX; n = 256; } else { m = cur_cmd; n = cur_chr; } get_x_token_or_active_char(); if (cur_cmd > ACTIVE_CHAR || cur_chr > 255) { cur_cmd = RELAX; cur_chr = 256; } if (this_if == IF_CHAR_CODE) { b = n == cur_chr; } else { b = m == cur_cmd; } break; case IF_INT_CODE: case IF_DIM_CODE: if (this_if == IF_INT_CODE) { scan_int(); } else { scan_normal_dimen(); } n = cur_val; get_nbx_token(); if (cur_tok >= OTHER_TOKEN + '<' && cur_tok <= OTHER_TOKEN + '>') { r = cur_tok - OTHER_TOKEN; } else { print_err("Missing = inserted for "); print_cmd_chr(IF_TEST, this_if); help_relation(); back_error(); r = '='; } if (this_if == IF_INT_CODE) { scan_int(); } else { scan_normal_dimen(); } switch (r) { case '<': b = n < cur_val; break; case '=': b = n == cur_val; break; case '>': b = n > cur_val; break; } break; case IF_ODD_CODE: scan_int(); b = odd(cur_val); break; case IF_VMODE_CODE: b = abs(mode) == VMODE; break; case IF_HMODE_CODE: b = abs(mode) == HMODE; break; case IF_MMODE_CODE: b = abs(mode) == MMODE; break; case IF_INNER_CODE: b = mode < 0; break; case IF_VOID_CODE: case IF_HBOX_CODE: case IF_VBOX_CODE: scan_eight_bit_int(); p = box(cur_val); if (this_if == IF_VOID_CODE) { b = p == null; } else if (p == null) { b = FALSE; } else if (this_if == IF_HBOX_CODE) { b = type(p) == HLIST_NODE; } else { b = type(p) == VLIST_NODE; } break; case IFX_CODE: save_scanner_status = scanner_status; scanner_status = NORMAL; get_next(); s = cur_cs; p = cur_cmd; q = cur_chr; get_next(); if (cur_cmd != p) { b = FALSE; } else if (cur_cmd < CALL) { b = cur_chr == q; } else { p = token_link(cur_chr); q = token_link(equiv(s)); if (p == q) { b = TRUE; } else { while (p != null && q != null) { if (token(p) != token(q)) { p = null; } else { p = token_link(p); q = token_link(q); } } b = p == null && q == null; } } scanner_status = save_scanner_status; break; case IF_EOF_CODE: scan_four_bit_int(); b = read_open[cur_val] == CLOSED; break; case IF_TRUE_CODE: b = TRUE; break; case IF_FALSE_CODE: b = FALSE; break; case IF_CASE_CODE: scan_int(); n = cur_val; if (tracing_commands > 1) { begin_diagnostic(); print("{case "); print_int(n); print("}"); end_diagnostic(FALSE); } while (n != 0) { pass_text(); if (cond_ptr == save_cond_ptr) { if (cur_chr == OR_CODE) { decr(n); } else { goto common_end; } } else if (cur_chr == FI_CODE) { pop_cond(); } } change_if_limit(OR_CODE, save_cond_ptr); return; default: break; } if (tracing_commands > 1) { begin_diagnostic(); print(b ? "{true}" : "{false}"); end_diagnostic(FALSE); } if (b) { change_if_limit(ELSE_CODE, save_cond_ptr); return; } loop { pass_text(); if (cond_ptr == save_cond_ptr) { if (cur_chr != OR_CODE) goto common_end; print_err("Extra "); print_esc("or"); help_or(); error(); } else if (cur_chr == FI_CODE) { pop_cond(); } } common_end: if (cur_chr == FI_CODE) { pop_cond(); } else { if_limit = FI_CODE; } }
/* * Report on the given file with characters representing packets * * - `ps` is the PS file we're reading * - if `max` is more than zero, then it is the maximum number of PS packs * we want to read * - `verbose` is true if we want an explanation of the characters * * Returns 0 if all went well, 1 if something went wrong. */ static int report_ps_dots(PS_reader_p ps, int max, int verbose) { int err; int count = 0; int num_packs = 0; offset_t posn; // The location in the input file of the current packet byte stream_id; // The packet's stream id int end_of_file = FALSE; struct PS_packet packet = {0}; struct PS_pack_header header = {0}; if (verbose) print_msg("Characters represent the following:\n" " [ Pack header\n" " H System header\n" " ] MPEG_program_end_code\n" " p<n> Private stream <n> (1 or 2)\n" " v Video stream 0\n" " v<n> Video stream <n> (>0)\n" " a Audio stream 0\n" " a<n> Audio stream <n> (>0)\n" " M Program stream map\n" " D Program stream directory\n" " . Padding\n" " ? Something else\n" ); // Read the start of the first packet (we confidently expect this // to be a pack header) err = read_PS_packet_start(ps,FALSE,&posn,&stream_id); if (err == EOF) { print_err("### Error reading first pack header\n"); print_err(" Unexpected end of PS at start of stream\n"); return 1; } else if (err) { print_err("### Error reading first pack header\n"); return 1; } if (stream_id != 0xba) { print_err("### Program stream does not start with pack header\n"); fprint_err(" First packet has stream id %02X (",stream_id); print_stream_id(FALSE,stream_id); print_err(")\n"); return 1; } // But given that, we can now happily loop reading in packs for (;;) { int num_system_headers = 0; if (max > 0 && num_packs >= max) { fprint_msg("\nStopping after %d packs\n",num_packs); return 0; } num_packs ++; print_msg("["); fflush(stdout); err = read_PS_pack_header_body(ps,&header); if (err) { fprint_err("### Error reading data for pack header starting at " OFFSET_T_FORMAT "\n",posn); return 1; } // Read (and, for the moment, at least, ignore) any system headers for (;;) { err = read_PS_packet_start(ps,FALSE,&posn,&stream_id); if (err == EOF) { end_of_file = TRUE; if (stream_id == 0xB9) { print_msg("]"); fflush(stdout); } break; } else if (err) return 1; if (stream_id == 0xbb) // System header { print_msg("H"); fflush(stdout); err = read_PS_packet_body(ps,stream_id,&packet); if (err) { fprint_err("### Error reading system header starting at " OFFSET_T_FORMAT "\n",posn); return 1; } // For the moment, just ignore the system header content num_system_headers ++; } else break; } if (end_of_file) break; // We've finished with system headers - onto data (one fondly hopes) for (;;) { if (stream_id == 0xba) // Start of the next pack break; if (stream_id == 0xBC) print_msg("M"); else if (stream_id == 0xFF) print_msg("D"); else if (stream_id == 0xBD) print_msg("p1"); else if (stream_id == 0xBE) print_msg("."); else if (stream_id == 0xBF) print_msg("p2"); else if (stream_id >= 0xC0 && stream_id <=0xDF) { int number = stream_id & 0x1F; if (number == 0) print_msg("a"); else fprint_msg("a%x",number); } else if (stream_id >= 0xE0 && stream_id <= 0xEF) { int number = stream_id & 0x0F; if (number == 0) print_msg("v"); else fprint_msg("v%x",number); } else print_msg("?"); fflush(stdout); err = read_PS_packet_body(ps,stream_id,&packet); if (err) { fprint_err("### Error reading PS packet starting at " OFFSET_T_FORMAT "\n",posn); return 1; } err = read_PS_packet_start(ps,FALSE,&posn,&stream_id); if (err == EOF) { if (stream_id == 0xB9) { print_msg("]"); fflush(stdout); } end_of_file = TRUE; break; } else if (err) return 1; } if (end_of_file) break; } clear_PS_packet(&packet); fprint_msg("\nRead %d PS packet%s in %d pack%s\n", count,(count==1?"":"s"), num_packs,(num_packs==1?"":"s")); return 0; }