예제 #1
0
파일: certsearch.c 프로젝트: fm4dd/webcert
int cgiMain() {

  static char      title[256]        = "";
  static char   subtitle[256]        = "";
         char      sorting[16]       = "desc";
         time_t    now               = time(NULL);
         time_t    start             = time(NULL);
         time_t    expiration        = time(NULL);
         double    available_secs    = 0;
         double    remaining_secs    = 0;
  struct dirent    **certstore_files = NULL;
         int       pagenumber        = 1;
         int       certcounter       = 0;
         int       tempcounter       = 0;
         int       pagecounter       = 0;
         int       dispcounter       = 0;
         int       dispmaxlines      = 0;
         int       certvalidity      = 0;
         div_t     disp_calc;
         div_t     oddline_calc;
         double    percent           = 0;

         cert                        = X509_new();
         certsubject                 = X509_NAME_new();
	 char      **form_data       = NULL;  /* string array for query data */

  /* get the current time */
  now = time(NULL);

/* ------------------------------------------------------------------------- *
 * If we are called without arguments, we display the cert search criteria   *
 * ------------------------------------------------------------------------- */
  if (cgiFormEntries(&form_data) != cgiFormSuccess)
    int_error("Error: Could not retrieve CGI form data.");
  if(form_data[0] == NULL) {

    start_tm = *gmtime(&now);

    snprintf(title, sizeof(title), "Search existing Certificates");
    pagehead(title);
    fprintf(cgiOut, "<form action=\"certsearch.cgi\" method=\"get\">");
    fprintf(cgiOut, "<table>");

    /* Search for Subject String */
    fprintf(cgiOut, "<tr><th colspan=\"5\">Search by Name</th></tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"cnt\" rowspan=\"2\">\n");
    fprintf(cgiOut, "<input type=\"radio\" value=\"dn\" name=\"search\" />");
    fprintf(cgiOut, "</th>\n");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "Distinguished Name Field:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    fprintf(cgiOut, "<select name=\"field\">");
    fprintf(cgiOut, "<option value=\"countryName\">Country</option>");
    fprintf(cgiOut, "<option value=\"stateOrProvinceName\">State</option>");
    fprintf(cgiOut, "<option value=\"localityName\">Location</option>");
    fprintf(cgiOut, "<option value=\"organizationName\">Organisation</option>");
    fprintf(cgiOut, "<option value=\"organizationalUnitName\">Department</option>");
    fprintf(cgiOut, "<option value=\"emailAddress\">E-Mail Addr</option>");
    fprintf(cgiOut, "<option selected=\"selected\" value=\"commonName\">Common Name</option>");
    fprintf(cgiOut, "<option value=\"surname\">Surname</option>");
    fprintf(cgiOut, "<option value=\"givenName\">Given Name</option>");
    fprintf(cgiOut, "</select>");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "Search String<br />[20 chars max]:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    fprintf(cgiOut, "<input type=\"text\" size=\"15\" name=\"dnvalue\" value=\"changeme.com\" />");
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"desc\" colspan=\"4\">\n");
    fprintf(cgiOut, "Search for certificates that have the given string in the selected DN field. ");
    fprintf(cgiOut, "The search is case sensitive, so results for country=us can be different from country=US and country=Us.");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "</tr>\n");

    /* Search for Expiration Date */
    fprintf(cgiOut, "<tr><th colspan=\"5\">Search by Expiration Date</th></tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"cnt\" rowspan=\"2\">\n");
    fprintf(cgiOut, "<input type=\"radio\" value=\"exp\" name=\"search\" checked=\"checked\" />");
    fprintf(cgiOut, "</th>\n");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "Expiration Date is<br />between Start Date:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    strftime(membio_buf, sizeof(membio_buf), "%d.%m.%Y", &start_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"9\" name=\"exp_startdate\" value=\"%s\" /> ", membio_buf);
    strftime(membio_buf, sizeof(membio_buf), "%H:%M", &start_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"3\" name=\"exp_starttime\" value=\"%s\" />", membio_buf);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "and End Date<br />[default 90 days]:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    /* set second time 3 months (90 days) into the future: 86400s/d*90d=7776000s */
    expiration = now + 7776000;
    expiration_tm = *gmtime(&expiration);
    strftime(membio_buf, sizeof(membio_buf), "%d.%m.%Y", &expiration_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"9\" name=\"exp_enddate\" value=\"%s\" /> ", membio_buf);
    strftime(membio_buf, sizeof(membio_buf), "%H:%M", &expiration_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"3\" name=\"exp_endtime\" value=\"%s\" />", membio_buf);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"desc\" colspan=\"4\">\n");
    fprintf(cgiOut, "Search for certificates that expire(d) between the selected start and end date. ");
    fprintf(cgiOut, "By default, the search is pre-set to find certificates that expire in the next 3 months.");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "</tr>\n");

    /* Search for Enabled Date */
    fprintf(cgiOut, "<tr><th colspan=\"5\">Search by Creation Date</th></tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"cnt\" rowspan=\"2\">\n");
    fprintf(cgiOut, "<input type=\"radio\" value=\"ena\" name=\"search\" />");
    fprintf(cgiOut, "</th>\n");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "Enabled Date is<br />between Start Date:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    /* set second time 3 months (90 days) into the past: 86400s/d*90d=7776000s */
    expiration = now - 7776000;
    expiration_tm = *gmtime(&expiration);
    strftime(membio_buf, sizeof(membio_buf), "%d.%m.%Y", &expiration_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"9\" name=\"ena_startdate\" value=\"%s\" /> ", membio_buf);
    strftime(membio_buf, sizeof(membio_buf), "%H:%M", &expiration_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"3\" name=\"ena_starttime\" value=\"%s\" />", membio_buf);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "and End Date<br />[default now]:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    strftime(membio_buf, sizeof(membio_buf), "%d.%m.%Y", &start_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"9\" name=\"ena_enddate\" value=\"%s\" /> ", membio_buf);
    strftime(membio_buf, sizeof(membio_buf), "%H:%M", &start_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"3\" name=\"ena_endtime\" value=\"%s\" />", membio_buf);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"desc\" colspan=\"4\">\n");
    fprintf(cgiOut, "Search for certificates that become valid between the selected start and end date. ");
    fprintf(cgiOut, "By default, the search is pre-set to show certificates created in the past 3 months.");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "</tr>\n");

    /* Search for Revocation Date */
    fprintf(cgiOut, "<tr><th colspan=\"5\">Search by Revocation Date</th></tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"cnt\" rowspan=\"2\">\n");
    fprintf(cgiOut, "<input type=\"radio\" value=\"rev\" name=\"search\" />");
    fprintf(cgiOut, "</th>\n");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "Revocation Date is<br />between Start Date:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    /* set second time 3 months (90 days) into the past: 86400s/d*90d=7776000s */
    expiration = now - 7776000;
    expiration_tm = *gmtime(&expiration);
    strftime(membio_buf, sizeof(membio_buf), "%d.%m.%Y", &expiration_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"9\" name=\"rev_startdate\" value=\"%s\" /> ", membio_buf);
    strftime(membio_buf, sizeof(membio_buf), "%H:%M", &expiration_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"3\" name=\"rev_starttime\" value=\"%s\"/>", membio_buf);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "and End Date<br />[now]:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    strftime(membio_buf, sizeof(membio_buf), "%d.%m.%Y", &start_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"9\" name=\"rev_enddate\" value=\"%s\" /> ", membio_buf);
    strftime(membio_buf, sizeof(membio_buf), "%H:%M", &start_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"3\" name=\"rev_endtime\" value=\"%s\" />", membio_buf);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"desc\" colspan=\"4\">\n");
    fprintf(cgiOut, "Search for certificates that have been revoked between the selected start and end date. ");
    fprintf(cgiOut, " By default, the search is pre-set to show certificates revoked in the past 3 months.");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "</tr>\n");

    /* Search for Serial Number */
    fprintf(cgiOut, "<tr><th colspan=\"5\">Search by Serial Number</th></tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"cnt\" rowspan=\"2\">\n");
    fprintf(cgiOut, "<input type=\"radio\" value=\"ser\" name=\"search\" />");
    fprintf(cgiOut, "</th>\n");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "Serial Number is<br />between Start Serial:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    fprintf(cgiOut, "<input type=\"text\" size=\"14\" name=\"startserial\" ");
    fprintf(cgiOut, "value=\"%s\" style=\"text-align:right;\" />", startserstr);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "and End Serial<br />[max 10e11]:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    fprintf(cgiOut, "<input type=\"text\" size=\"14\" name=\"endserial\" ");
    fprintf(cgiOut, "value=\"%s\" style=\"text-align:right;\" />", endserstr);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"desc\" colspan=\"4\">\n");
    fprintf(cgiOut, "Search for certificates whose serial number is between the given ");
    fprintf(cgiOut, "start and end serial number in decimal format. To find a particular certificate, set start and end serial to be equal.");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "</tr>\n");

    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th colspan=\"5\">");
    fprintf(cgiOut, "<input type=\"submit\" value=\"Search Certificates\" />");
    fprintf(cgiOut, "</th>");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "</table>\n");
    fprintf(cgiOut, "</form>\n");
    pagefoot();

  }
  else {
  
  /* ------------------------------------------------------------------- *
   * check if we got the CGI form data                                   *
   * --------------------------------------------------------------------*/
    if ( cgiFormString("search", search, sizeof(search))
                                                     != cgiFormSuccess )
      int_error("Error retrieving CGI form search type.");
    else {
      if (strcmp(search, "dn") == 0) {
        if ( cgiFormString("field", field, sizeof(field))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form DN search field information.");

        if ( cgiFormString("dnvalue", dnvalue, sizeof(dnvalue))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form DN search dnvalue information.");
        snprintf(title, sizeof(title), "Search Certs by Subject");
        snprintf(subtitle, sizeof(subtitle), "Certificates with DN %s=%s", field, dnvalue);
      }
      else if (strcmp(search, "exp") == 0) {
        if ( cgiFormString("exp_startdate", exp_startdate, sizeof(exp_startdate))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form expiration start date.");

        if ( cgiFormString("exp_starttime", exp_starttime, sizeof(exp_starttime))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form expiration start time.");

        if ( cgiFormString("exp_enddate", exp_enddate, sizeof(exp_enddate))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form expiration end date.");

        if ( cgiFormString("exp_endtime", exp_endtime, sizeof(exp_endtime))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form expiration end time.");

        strncat(exp_startstr, exp_startdate, sizeof(exp_startstr)-1);
        strncat(exp_startstr, " ", 1); /* add a space between date and time */
        strncat(exp_startstr, exp_starttime, sizeof(exp_startstr)-strlen(exp_startstr)-1);
        strncat(exp_endstr, exp_enddate, sizeof(exp_endstr)-1);
        strncat(exp_endstr, " ", 1); /* add a space between date and time */
        strncat(exp_endstr, exp_endtime, sizeof(exp_endstr)-strlen(exp_endstr)-1);
        snprintf(title, sizeof(title), "Search Certs by Expiration");
        snprintf(subtitle, sizeof(subtitle), "Certificates with expiration between %s and %s", exp_startstr, exp_endstr);
      }
      else if (strcmp(search, "ena") == 0) {
        if ( cgiFormString("ena_startdate", ena_startdate, sizeof(ena_startdate))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form enable start date.");

        if ( cgiFormString("ena_starttime", ena_starttime, sizeof(ena_starttime))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form enable start time.");

        if ( cgiFormString("ena_enddate", ena_enddate, sizeof(ena_enddate))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form enable end date.");

        if ( cgiFormString("ena_endtime", ena_endtime, sizeof(ena_endtime))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form enable end time.");

        strncat(ena_startstr, ena_startdate, sizeof(ena_startstr)-1);
        strncat(ena_startstr, " ", 1); /* add a space between date and time */
        strncat(ena_startstr, ena_starttime, sizeof(ena_startstr)-strlen(ena_startstr)-1);
        strncat(ena_endstr, ena_enddate, sizeof(ena_endstr)-1);
        strncat(ena_endstr, " ", 1); /* add a space between date and time */
        strncat(ena_endstr, ena_endtime, sizeof(ena_endstr)-strlen(ena_endstr)-1);
        snprintf(title, sizeof(title), "Search Certs by Start Date");
        snprintf(subtitle, sizeof(subtitle), "Certificates with start date between %s and %s", ena_startstr, ena_endstr);
      }
      else if (strcmp(search, "rev") == 0) {
        if ( cgiFormString("rev_startdate", rev_startdate, sizeof(rev_startdate))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form enable start date.");

        if ( cgiFormString("rev_starttime", rev_starttime, sizeof(rev_starttime))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form enable start time.");

        if ( cgiFormString("rev_enddate", rev_enddate, sizeof(rev_enddate))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form enable end date.");

        if ( cgiFormString("rev_endtime", rev_endtime, sizeof(rev_endtime))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form enable end time.");

        strncat(rev_startstr, rev_startdate, sizeof(rev_startstr)-1);
        strncat(rev_startstr, " ", 1); /* add a space between date and time */
        strncat(rev_startstr, rev_starttime, sizeof(rev_startstr)-strlen(rev_startstr)-1);
        strncat(rev_endstr, rev_enddate, sizeof(rev_endstr)-1);
        strncat(rev_endstr, " ", 1); /* add a space between date and time */
        strncat(rev_endstr, rev_endtime, sizeof(rev_endstr)-strlen(rev_endstr)-1);
        snprintf(title, sizeof(title), "Search Revoked Certificates");
        snprintf(subtitle, sizeof(subtitle), "Certificates revoked between %s and %s", rev_startstr, rev_endstr);
      }
      else if (strcmp(search, "ser") == 0) {
        if ( cgiFormString("startserial", startserstr, sizeof(startserstr))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form start serial value.");

        if ( cgiFormString("endserial", endserstr, sizeof(endserstr))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form end serial value.");
        snprintf(title, sizeof(title), "Search Certs by Serial Number");
        snprintf(subtitle, sizeof(subtitle), "Certificates with serial number between %s and %s", startserstr, endserstr);
      }
      else int_error("Error CGI form retrieving a valid search type.");
    }

/* -------------------------------------------------------------------------- *
 * We got CGI arguments, first we get a list of .pem files from the cert dir  *
 * ---------------------------------------------------------------------------*/
  certcounter = scandir(CACERTSTORE, &certstore_files, file_select, hexsort);
  // It can happen that our search does not return any certs. This is not an error.
  //if(certcounter<=0) int_error("Error: No certificate files found.");

/* -------------------------------------------------------------------------- *
 * calculate how many pages we get with MAXCERTDISPLAY                         *
 * ---------------------------------------------------------------------------*/

  if(certcounter<=MAXCERTDISPLAY) pagecounter = 1;
  else {
    disp_calc = div(certcounter, MAXCERTDISPLAY);
    /* if the count of certs divided by MAXCERTDISPLAY has no remainder */
    if(disp_calc.rem == 0) pagecounter = disp_calc.quot;
    /* with a remainder, we must prepare an extra page for the rest */
    else pagecounter = disp_calc.quot +1;
  }

/* -------------------------------------------------------------------------- *
 * Check if we have been subsequently called with a pagenumber & sort request *
 * ---------------------------------------------------------------------------*/

  if(cgiFormInteger("page", &pagenumber, 1) == cgiFormSuccess)
    if(pagenumber > pagecounter || pagenumber <=0)
      int_error("Error: Page does not exist.");

  if(cgiFormString("sort", sorting, sizeof(sorting)) != cgiFormSuccess)
      strncpy(sorting, "desc", sizeof(sorting));

/* -------------------------------------------------------------------------- *
 * now we know how many certs we have in total and we can build the page(s).  *
 * For every MAXCERTDISPLAY certs we start a new page and cycle through by    *
 * calling ourself with the requested certs in range.                         *
 * ---------------------------------------------------------------------------*/

  if(strcmp(sorting, "asc") == 0) {

    if(certcounter <= MAXCERTDISPLAY) {
       dispmaxlines = certcounter;
       tempcounter = 0;
    }
    else
      if(pagenumber == pagecounter &&
             ( pagecounter * MAXCERTDISPLAY) - certcounter != 0) {

        tempcounter = (pagecounter * MAXCERTDISPLAY) - MAXCERTDISPLAY;
        dispmaxlines = certcounter - ((pagecounter-1) * MAXCERTDISPLAY);
      }
      else {

        tempcounter = (pagenumber * MAXCERTDISPLAY) - MAXCERTDISPLAY;
        dispmaxlines = MAXCERTDISPLAY;
      }
  }

  if(strcmp(sorting, "desc") == 0) {

    if(certcounter <= MAXCERTDISPLAY) {
       dispmaxlines = certcounter;
       tempcounter = certcounter;
    }
    else
      if(pagenumber == pagecounter &&
             ( pagecounter * MAXCERTDISPLAY) - certcounter != 0) {

        tempcounter = certcounter - ((pagecounter-1) * MAXCERTDISPLAY);
        dispmaxlines = certcounter - ((pagecounter-1) * MAXCERTDISPLAY);
      }
      else {

       tempcounter = certcounter - (pagenumber*MAXCERTDISPLAY) + MAXCERTDISPLAY;
       dispmaxlines = MAXCERTDISPLAY;
      }
  }

/* -------------------------------------------------------------------------- *
 * start the html output                                                      *
 * ---------------------------------------------------------------------------*/

  pagehead(title);

  //debugging only:
  //printf("Number of certs: %d\n", certcounter);
  //printf("Num tempcounter: %d\n", tempcounter);
  //printf("Number of pages: %d\n", pagecounter);
  //printf("Div Quotient: %d\n", disp_calc.quot);
  //printf("Div Remainder: %d\n", disp_calc.rem);
  //fprintf(cgiOut, "</BODY></HTML>\n");
  //exit(0);

/* -------------------------------------------------------------------------- *
 * start the form output                                                      *
 * ---------------------------------------------------------------------------*/

   fprintf(cgiOut, "<h3>%s</h3>\n", subtitle);
   fprintf(cgiOut, "<p></p>\n");
   fprintf(cgiOut, "<table>\n");
   fprintf(cgiOut, "<tr>\n");
   fprintf(cgiOut, "<th width=\"20\">");
   fprintf(cgiOut, "#");
   fprintf(cgiOut, "</th>\n");
   fprintf(cgiOut, "<th width=\"495\">");
   fprintf(cgiOut, "Certificate Subject Information");
   fprintf(cgiOut, "</th>\n");
   fprintf(cgiOut, "<th width=\"60\" colspan=\"2\">");
   fprintf(cgiOut, "Expires");
   fprintf(cgiOut, "</th>\n");
   fprintf(cgiOut, "<th width=\"65\">");
   fprintf(cgiOut, "Action");
   fprintf(cgiOut, "</th>\n");
   fprintf(cgiOut, "</tr>\n");

  /* if our search did not return any certs, we display a note instead */
  if(certcounter<=0) {
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"even\" colspan=\"5\">");
    fprintf(cgiOut, "Could not find any certificates for the given search criteria.");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "</tr>\n");
  }

  for(dispcounter=0; dispcounter < dispmaxlines; dispcounter++) {

    /* zero certificate values and flags */
    certvalidity = 0;
    percent = 0;
    available_secs = 0;
    remaining_secs = 0;
    cert = X509_new();
    certsubject = X509_NAME_new();

    if(strcmp(sorting, "desc") == 0) tempcounter--;

    snprintf(certfilestr, sizeof(certfilestr), "%s/%s",
                           CACERTSTORE, certstore_files[tempcounter]->d_name);

    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th rowspan=\"2\">");
    fprintf(cgiOut, "%d", tempcounter+1);
    fprintf(cgiOut, "</th>\n");

    oddline_calc = div(tempcounter+1, 2);
    if(oddline_calc.rem)
      fprintf(cgiOut, "<td rowspan=\"2\" class=\"odd\">");
    else
      fprintf(cgiOut, "<td rowspan=\"2\" class=\"even\">");

    if ( (certfile = fopen(certfilestr, "r")) != NULL) {
      PEM_read_X509(certfile, &cert, NULL, NULL);

      /* ---------------------------------------------------------- *
       * Display the subject data. Use the UTF-8 flag to show       *
       * Japanese Kanji. This also needs the separator flag to work *
       * ---------------------------------------------------------- */
      certsubject = X509_get_subject_name(cert);
      X509_NAME_print_ex_fp(cgiOut, certsubject, 0,
         ASN1_STRFLGS_UTF8_CONVERT|XN_FLAG_SEP_CPLUS_SPC);

      /* store certificate start date for later eval */
      start_date = X509_get_notBefore(cert);

      /* store certificate expiration date for later eval */
      expiration_date = X509_get_notAfter(cert);

      /* check the start and end dates in the cert */
      if (X509_cmp_current_time (X509_get_notBefore (cert)) >= 0)
        /* flag the certificate as not valid yet */
        certvalidity = 0;
      else
      if (X509_cmp_current_time (X509_get_notAfter (cert)) <= 0)
        /* flag the certificate as expired */
        certvalidity = 0;
      else 
        /* flag the certificate is still valid */
        certvalidity = 1;

      fclose(certfile);
    }
    else 
       fprintf(cgiOut, "Error: Can't open certificate file %s for reading.",
                                                                 certfilestr);
    fprintf(cgiOut, "</td>\n");

    if(certvalidity == 0) {

      /* expiration bar display column */
      fprintf(cgiOut, "<th rowspan=\"2\">\n");
      fprintf(cgiOut, "<table class=\"led\">\n");
      fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "</table>\n");
      fprintf(cgiOut, "</th>\n");

      /* remaining days before expiration column */
      fprintf(cgiOut, "<th class=\"exnok\" rowspan=\"2\">");
      fprintf(cgiOut, "Inval.<br />/Expd");
      fprintf(cgiOut, "</th>\n");
    }

    if(certvalidity == 1) {

      /* ------ START get the certificate lifetime in seconds ------ */
      /* copy the start date into a string */
      membio = BIO_new(BIO_s_mem());
      ASN1_TIME_print(membio, start_date);
      BIO_gets(membio, membio_buf, sizeof(membio_buf));
      BIO_free(membio);

      /* parse the start date string into a time struct */
      memset (&start_tm, '\0', sizeof(start_tm));
      strptime(membio_buf, "%h %d %T %Y %z", &start_tm);
      start = mktime(&start_tm);

      /* ------ START get the certificate remaining time in seconds ------ */
      /* copy the expiration date into a string */
      membio = BIO_new(BIO_s_mem());
      ASN1_TIME_print(membio, expiration_date);
      BIO_gets(membio, membio_buf, sizeof(membio_buf));
      BIO_free(membio);
  
      /* parse the expiration date string into a time struct */
      memset (&expiration_tm, '\0', sizeof(expiration_tm));
      strptime(membio_buf, "%h %d %T %Y %z", &expiration_tm);
  
      /* get the current time */
      expiration = mktime(&expiration_tm);
  
      /* get the time difference between expiration time and current time */
      remaining_secs = difftime(expiration, now);
      /* ------ END get the certificate remaining time in seconds ------ */

      /* get the time difference between start and expiration time */
      available_secs = difftime(expiration, start);
      /* ------ END get the certificate lifetime in seconds ------ */
  
      /* ------ START calculate percentage of lifetime left ------ */
      /* remaining_secs *100                                       */
      /* ------------------- = X, rounded down with floor()        */
      /* available_secs                                            */
      percent = floor((remaining_secs*100)/available_secs);
      /* ------ END calculate percentage of lifetime left   ------ */
  
      /* expiration bar display column */
      fprintf(cgiOut, "<th rowspan=\"2\">");
      fprintf(cgiOut, "<table class=\"led\">\n");
      if (percent >= 90) fprintf(cgiOut, "  <tr><td class=\"led\" bgcolor=#00FF00></td></tr>\n");
      else fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      if (percent >= 80) fprintf(cgiOut, "  <tr><td class=\"led\" bgcolor=#00FF33></td></tr>\n");
      else fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      if (percent >= 70) fprintf(cgiOut, "  <tr><td class=\"led\" bgcolor=#99FF33></td></tr>\n");
      else fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      if (percent >= 60) fprintf(cgiOut, "  <tr><td class=\"led\" bgcolor=#FFFF00></td></tr>\n");
      else fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      if (percent >= 50) fprintf(cgiOut, "  <tr><td class=\"led\" bgcolor=#FFCC00></td></tr>\n");
      else fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      if (percent >= 40) fprintf(cgiOut, "  <tr><td class=\"led\" bgcolor=#FF9900></td></tr>\n");
      else fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      if (percent >= 30) fprintf(cgiOut, "  <tr><td class=\"led\" bgcolor=#FF6600></td></tr>\n");
      else fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      if (percent >= 20) fprintf(cgiOut, "  <tr><td class=\"led\" bgcolor=#FF3300></td></tr>\n");
      else fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      if (percent >= 10) fprintf(cgiOut, "  <tr><td class=\"led\" bgcolor=#FF0000></td></tr>\n");
      else fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "</table>\n");
      fprintf(cgiOut, "</th>");
  
      /* remaining days before expiration column */
      //fprintf(cgiOut, membio_buf);
      if (percent < 10) fprintf(cgiOut, "<th class=\"exnok\" rowspan=\"2\">\n");
      else fprintf(cgiOut, "<th class=\"exok\" rowspan=\"2\">\n");
      if(floor(remaining_secs/63072000) > 0) fprintf(cgiOut, "%.f<br />years", remaining_secs/31536000);
      else if(floor(remaining_secs/86400) > 0 ) fprintf(cgiOut, "%.f<br />days", remaining_secs/86400);
      else if(floor(remaining_secs/3600) > 0 ) fprintf(cgiOut, "%.f<br />hours", remaining_secs/3600);
      else if(floor(remaining_secs/60) > 0 ) fprintf(cgiOut, "%.f<br />mins", remaining_secs/60);
      else fprintf(cgiOut, "%.f<br />secs", remaining_secs);
      fprintf(cgiOut, "</th>\n");
    }

    /* action column */
    fprintf(cgiOut, "<th>");
    fprintf(cgiOut, "<form action=\"getcert.cgi\" method=\"post\">\n");
    fprintf(cgiOut, "<input type=\"hidden\" name=\"cfilename\" ");
    fprintf(cgiOut, "value=\"%s\" />\n", certstore_files[tempcounter]->d_name);
    fprintf(cgiOut, "<input type=\"hidden\" name=\"format\" value=\"pem\" />\n");
    fprintf(cgiOut, "<input class=\"getcert\" type=\"submit\" value=\"Detail\" />\n");
    fprintf(cgiOut, "</form>\n");
    fprintf(cgiOut, "</th>\n");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th>");
    fprintf(cgiOut, "<form action=\"getcert.cgi\" method=\"post\">\n");
    fprintf(cgiOut, "<input type=\"hidden\" name=\"cfilename\" ");
    fprintf(cgiOut, "value=\"%s\" />\n", certstore_files[tempcounter]->d_name);
    fprintf(cgiOut, "<input type=\"hidden\" name=\"format\" value=\"text\" />\n");
    fprintf(cgiOut, "<input class=\"getcert\" type=\"submit\" value=\"Renew\" />\n");
    fprintf(cgiOut, "</form>");
    fprintf(cgiOut, "</th>\n");
    fprintf(cgiOut, "</tr>\n");

    if(strcmp(sorting, "asc") == 0) tempcounter++;
  }


  fprintf(cgiOut, "<tr>\n");
  fprintf(cgiOut, "<th colspan=\"5\">");
  fprintf(cgiOut, "Total # of certs: %d | ", certcounter);
  fprintf(cgiOut, "Page %d of %d", pagenumber, pagecounter);
  fprintf(cgiOut, "</th>");
  fprintf(cgiOut, "</tr>");
  fprintf(cgiOut, "</table>\n");

  fprintf(cgiOut, "<p></p>\n");

  fprintf(cgiOut, "<table>\n");

  fprintf(cgiOut, "<tr>\n");
  fprintf(cgiOut, "<th>");
  fprintf(cgiOut, "<form action=\"certsearch.cgi\" method=\"post\">");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"sort\" ");
  fprintf(cgiOut, "value=\"desc\" />\n");
  resubmit();
  fprintf(cgiOut, "<input type=\"submit\" name=\"sort\"");
  fprintf(cgiOut, " value=\"Latest Certs first\" />");
  fprintf(cgiOut, "</form>");
  fprintf(cgiOut, "</th>\n");

  fprintf(cgiOut, "<th>");
  fprintf(cgiOut, "<form action=\"certsearch.cgi\" method=\"post\">");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"sort\" ");
  fprintf(cgiOut, "value=\"asc\">\n");
  resubmit();
  fprintf(cgiOut, "<input type=\"submit\" name=\"sort\"");
  fprintf(cgiOut, " value=\"Oldest Certs first\">");
  fprintf(cgiOut, "</form>");
  fprintf(cgiOut, "</th>\n");

  // filler 1
  fprintf(cgiOut, "<th width=\"15\">");
  fprintf(cgiOut, "&nbsp;");
  fprintf(cgiOut, "</th>\n");

  // goto page 1
  fprintf(cgiOut, "<th width=\"5\">");
  fprintf(cgiOut, "<form action=\"certsearch.cgi\" method=\"post\">");
  resubmit();
  fprintf(cgiOut, "<input type=\"submit\" value=\"&lt;&lt;\" />");
  fprintf(cgiOut, "</form>");
  fprintf(cgiOut, "</th>\n");

  // goto page before
  fprintf(cgiOut, "<th width=\"5\">");
  fprintf(cgiOut, "<form action=\"certsearch.cgi\" method=\"post\">");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"certcounter\" ");
  fprintf(cgiOut, "value=\"");
  fprintf(cgiOut, "%d", certcounter);
  fprintf(cgiOut, "\" />\n");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"pagecounter\" ");
  fprintf(cgiOut, "value=\"");
  fprintf(cgiOut, "%d", pagecounter);
  fprintf(cgiOut, "\" />\n");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"page\" ");
  fprintf(cgiOut, "value=\"");
  tempcounter = 0;
  if(pagenumber > 1) tempcounter = pagenumber - 1;
  else tempcounter = 1;
  fprintf(cgiOut, "%d", tempcounter);
  fprintf(cgiOut, "\" />\n");
  resubmit();
  fprintf(cgiOut, "<input type=\"submit\" value=\"&lt; 1\">");
  fprintf(cgiOut, "</form>");
  fprintf(cgiOut, "</th>\n");

  // goto page after
  fprintf(cgiOut, "<th width=\"5\">");
  fprintf(cgiOut, "<form action=\"certsearch.cgi\" method=\"post\">");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"certcounter\" ");
  fprintf(cgiOut, "value=\"");
  fprintf(cgiOut, "%d", certcounter);
  fprintf(cgiOut, "\" />\n");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"pagecounter\" ");
  fprintf(cgiOut, "value=\"");
  fprintf(cgiOut, "%d", pagecounter);
  fprintf(cgiOut, "\" />\n");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"page\" ");
  fprintf(cgiOut, "value=\"");
  tempcounter = 0;
  if(pagecounter > pagenumber) tempcounter = pagenumber + 1;
  else tempcounter = pagecounter;
  fprintf(cgiOut, "%d", tempcounter);
  fprintf(cgiOut, "\" />\n");
  resubmit();
  fprintf(cgiOut, "<input type=\"submit\" value=\"1 &gt;\" />");
  fprintf(cgiOut, "</form>");
  fprintf(cgiOut, "</th>\n");

  // goto last page
  fprintf(cgiOut, "<th width=\"5\">");
  fprintf(cgiOut, "<form action=\"certsearch.cgi\" method=\"post\">");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"certcounter\" ");
  fprintf(cgiOut, "value=\"");
  fprintf(cgiOut, "%d", certcounter);
  fprintf(cgiOut, "\" />\n");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"pagecounter\" ");
  fprintf(cgiOut, "value=\"");
  fprintf(cgiOut, "%d", pagecounter);
  fprintf(cgiOut, "\" />\n");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"page\" ");
  fprintf(cgiOut, "value=\"");
  fprintf(cgiOut, "%d", pagecounter);
  fprintf(cgiOut, "\" />\n");
  resubmit();
  fprintf(cgiOut, "<input type=\"submit\" value=\"&gt;&gt;\" />");
  fprintf(cgiOut, "</form>");
  fprintf(cgiOut, "</th>\n");

  // goto page number
  fprintf(cgiOut, "<th width=\"120\">\n");
  fprintf(cgiOut, "<form class=\"setpage\" action=\"certsearch.cgi\" method=\"post\">\n");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"certcounter\" ");
  fprintf(cgiOut, "value=\"");
  fprintf(cgiOut, "%d", certcounter);
  fprintf(cgiOut, "\" />\n");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"pagecounter\" ");
  fprintf(cgiOut, "value=\"");
  fprintf(cgiOut, "%d", pagecounter);
  fprintf(cgiOut, "\" />\n");
  resubmit();
  fprintf(cgiOut, "<input class=\"goto\" type=\"submit\" value=\"Goto\" />\n");
  fprintf(cgiOut, "&nbsp; &nbsp;");
  fprintf(cgiOut, "<input class=\"page\" type=\"text\" name=\"page\" ");
  fprintf(cgiOut, "value=\"%d\" />\n", pagecounter);
  fprintf(cgiOut, "</form>\n");
  fprintf(cgiOut, "</th>\n");

  fprintf(cgiOut, "</tr>\n");
  fprintf(cgiOut, "</table>\n");

/* ---------------------------------------------------------------------------*
 * end the html output                                                        *
 * ---------------------------------------------------------------------------*/

  pagefoot();
}
  return(0);
}
예제 #2
0
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )    
{ 
	int			i,j,m,n;
    int			ifield, jstruct, *classIDflags;
    int			NStructElems, nfields, ndim, nsignal, nvals;
	const char  *field_name, *str;
	const		mxArray *field_array_ptr;
	double		dbl;
	float		*leadSnds[MAXCARRIERS], *lagSnds[MAXCARRIERS];
	float		*locations, *azimuths, *rove, *scalesLead, *scalesLag, *attensLead, *tmp;

	div_t div_result;

	InfoStruct recInfo;

    /* Check for proper number of arguments */    
    if (nrhs != 9)
		mexErrMsgTxt("9 input arguments required)."); 
	else if(!mxIsStruct(prhs[0]))
		mexErrMsgTxt("Input1 must be a structure.");

	// deal with the structure (arg0)
    nfields = mxGetNumberOfFields(prhs[0]);
    NStructElems = mxGetNumberOfElements(prhs[0]);

    /* check each field. */
	for(ifield=0; ifield<nfields; ifield++) 
	{
		field_name = mxGetFieldNameByNumber(prhs[0], ifield);
		field_array_ptr = mxGetFieldByNumber(prhs[0], 0, ifield); 

	    if (field_array_ptr == NULL)
			mexPrintf(".%s is empty\n", field_name);
		else
		{
			str = mxArrayToString(field_array_ptr);
			dbl = mxGetScalar(field_array_ptr);
			if(strncmp("FN1", field_name, 3) == 0)
				strncpy(recInfo.outFN1, str, MAX_FILENAME_LEN);

			if (strncmp("FN2",field_name, 3) ==0)
				strncpy(recInfo.outFN2, str, MAX_FILENAME_LEN);

			if (strncmp("record",field_name, 6) ==0)
				recInfo.record = (unsigned int) dbl;
		
			if (strncmp("latten",field_name, 6) ==0)
				recInfo.latten = (float) dbl;

			if (strncmp("ratten",field_name, 6) ==0)
				recInfo.ratten = (float) dbl;

			if (strncmp("n_trials",field_name,8) ==0)
				recInfo.n_trials = (unsigned int) dbl;

			if (strncmp("decimateFactor",field_name, 14) ==0)
				recInfo.decimateFactor = (unsigned int) dbl;

			if (strncmp("buf_pts",field_name, 7) ==0)
				recInfo.buf_pts = (long) dbl;

			if (strncmp("nptsTotalPlay",field_name, 13) ==0)
				recInfo.nptsTotalPlay = (long) dbl;

			if (strncmp("ISI",field_name, 3) ==0)
				recInfo.ISI = (unsigned int) dbl;

			if (strncmp("max_signal_jitter",field_name, 17) ==0)
				recInfo.max_signal_jitter = (unsigned int) dbl;

			if (strncmp("num_carriers",field_name, 12) ==0)
				recInfo.num_carriers = (unsigned int) dbl;

			if (strncmp("n_speakers",field_name, 10) ==0)
				recInfo.n_speakers = (unsigned int) dbl;

			if (strncmp("sound_onset",field_name, 11) ==0)
				recInfo.sound_onset = (long) dbl;
			
			if (strncmp("trials_to_show",field_name, 14) ==0)
				recInfo.trials_to_show = (long) dbl;

			if (strncmp("hab_loc",field_name, 7) ==0)
				recInfo.hab_loc = (float) dbl;

			if (strncmp("test_trial_freq",field_name, 15) ==0)
				recInfo.test_trial_freq = (float) dbl;
		}
	}


// check buf_pts = (n * 2^decimateFactor);
	div_result = div( recInfo.buf_pts, pow(2,recInfo.decimateFactor) );
    if(div_result.rem)
	{
		recInfo.buf_pts = pow(2,recInfo.decimateFactor) * (div_result.quot +1);
		mexPrintf("buf_pts and decimateFactor incompatable. buf_pts increased to %d \n",recInfo.buf_pts);
	}

// check nptsTotalPlay = (n * buf_pts)
	div_result = div( recInfo.nptsTotalPlay, recInfo.buf_pts );
    if(div_result.rem)
	{
		recInfo.nptsTotalPlay = recInfo.buf_pts * (div_result.quot +1);
		mexPrintf("buf_pts and totalpts incompatable. nptsTotalPlay increased to %d \n",recInfo.nptsTotalPlay);
	}
	div_result = div( recInfo.nptsTotalPlay, (recInfo.buf_pts * (recInfo.ISI+1)) );	
	recInfo.n_trials = (int) div_result.quot +1;

	// get LEAD and LAG sounds (should be <= 50)
	// matlab arrays should be buf_pts x num_carriers

	// LEAD
	tmp=(float *) mxGetPr(prhs[1]);
	m=mxGetM(prhs[1]); n=mxGetN(prhs[1]);
	if(recInfo.buf_pts != m || recInfo.num_carriers  != n) {
			mexPrintf("array is %i x %i",m,n);
			mexErrMsgTxt("Sound arrays must be buf_pts x num_carriers");
	}
	for(i=0;i<recInfo.num_carriers;++i)
		leadSnds[i] = &tmp[i*recInfo.buf_pts];

    // LEAD
	tmp=(float *) mxGetPr(prhs[2]);
	m=mxGetM(prhs[2]); n=mxGetN(prhs[2]);
	if(recInfo.buf_pts != m || recInfo.num_carriers != n) {
			mexPrintf("array is %i x %i",m,n);
			mexErrMsgTxt("Sound arrays must be buf_pts x num_carriers");
	}
	for(i=0;i<recInfo.num_carriers;++i)
		lagSnds[i] = &tmp[i*recInfo.buf_pts];

	
	// locations is a 1 x n (n>=n_trials) array of spkr positions to switch between (0-3)
	nsignal = mxGetN(prhs[3]);
	if ( mxGetM(prhs[3])!=1 || nsignal < recInfo.n_trials)
		mexErrMsgTxt("locations must be a 1 x n (n > n_trials), row vector.");
	locations = (float*) mxGetPr(prhs[3]);

	/* azimuths is a 1 x N array of azimuths (N = no. of speakers used) */
	azimuths = (float*) mxGetPr(prhs[4]);
   
	// rove is a 1 x n (n>=n_trials) array of sound IDs for carrier roving
	nsignal = mxGetN(prhs[5]);
	if ( mxGetM(prhs[5])!=1 || nsignal < recInfo.n_trials)
		mexErrMsgTxt("rove sequence must be a 1 x n (n > n_trials), row vector.");
	rove = (float*) mxGetPr(prhs[5]);

	/* scalesLead is a 1 x (# lag speakers) array of scales for the lead speaker */
	nvals = mxGetN(prhs[6]);
	if ( mxGetM(prhs[6])!=1 || nvals != (recInfo.n_speakers - 1) )
		mexErrMsgTxt("scales for lead speaker must by 1 x (# lag speakers), row vector.");
	scalesLead = (float*) mxGetPr(prhs[6]);

	/* scalesLag is a 1 x (# lag speakers) array of scales for the lag speakers */
	nvals = mxGetN(prhs[7]);
	if ( mxGetM(prhs[7])!=1 || nvals != (recInfo.n_speakers - 1) )
		mexErrMsgTxt("scales for lag speaker must by 1 x (# lag speakers), row vector.");
	scalesLag = (float*) mxGetPr(prhs[7]);

	/* attensLead is a 1 x (# lag speakers) array of attens for the lead speaker */
	nvals = mxGetN(prhs[8]);
	if ( mxGetM(prhs[8])!=1 || nvals != (recInfo.n_speakers - 1) )
		mexErrMsgTxt("attens for the lead speaker must be a 1 x (# lag speakers), row vector.");
	attensLead = (float*) mxGetPr(prhs[8]);

    /* The double_buffer subroutine */
	double_buffer( &recInfo, leadSnds, lagSnds, locations, azimuths, rove, scalesLead, scalesLag, attensLead, nsignal);

	return;   
}
예제 #3
0
파일: MatLab4.cpp 프로젝트: lonnell/trick
int MatLab4LocateParam( char *file_name , char *param_name , char *time_name ) {

        int len ;
        int temp ;
        int endian ;
        int mat_size ;
        int mat_type ;
        int my_byte_order ;
        div_t div_result ;
        int row , column , imaginary ;
        char * temp_ptr ;
        bool param_found , time_found ;
        FILE *fp ;
        bool swap = false ;
        int size ;
        int y_field_num , time_field_num ;
        int max_offset , offset = 0 ;

        TRICK_GET_BYTE_ORDER(my_byte_order) ;

        if ((fp = fopen(file_name , "r")) == 0 ) {
           std::cerr << "ERROR:  Couldn't open \"" << file_name << "\": " << std::strerror(errno) << std::endl;
           exit(-1) ;
        }

        // we use fseek calls to move around so I need to know the max offset of the file
        fseek( fp , 0 , SEEK_END ) ;
        max_offset = ftell(fp) ;
        rewind( fp ) ;

        // get field_num from param_name
        temp_ptr = rindex(param_name, '[') ;
        if ( temp_ptr != NULL ) {
                sscanf(&temp_ptr[1] , "%d" , &y_field_num ) ;
        }
        else {
                y_field_num = 0 ;
        }

        // get field_num from time_name
        temp_ptr = rindex(param_name, '[') ;
        if ( temp_ptr != NULL ) {
                sscanf(&temp_ptr[1] , "%d" , &time_field_num ) ;
        }
        else {
                time_field_num = 0 ;
        }

        param_found = time_found = false ;
        while ( offset < max_offset ) {

                // read the type in
                fread( &temp , 4 , 1 , fp ) ;
                if ( !strncmp( (char *)&temp , "MATL" , 4 )) {
                        return(0) ;
                }

                // byte swap it if it looks like we need to
                if ( temp & 0xFFFF0000 ) {
                        temp = trick_byteswap_int(temp) ;
                }

                div_result = div(temp , 1000) ;
                endian = div_result.quot ;
                temp = div_result.rem ;

                switch ( endian ) {
                        case 0:
                                swap = ( my_byte_order == TRICK_LITTLE_ENDIAN ) ? 0 : 1 ;
                                break ;
                        case 1:
                                swap = ( my_byte_order == TRICK_BIG_ENDIAN ) ? 0 : 1 ;
                                break ;
                        default:
                                fprintf(stderr,"Unknown endianness!\n") ;
                                fclose(fp) ;
                                return(0) ;
                                break ;
                }

                div_result = div( temp , 10 ) ;
                mat_size = div_result.quot ;
                mat_type = div_result.rem ;
                switch ( mat_size ) {
                        case 0:
                                size = 8 ;
                                break ;
                        case 1:
                                size = 4 ;
                                break ;
                        case 2:
                                size = 4 ;
                                break ;
                        case 3:
                                size = 2 ;
                                break ;
                        case 4:
                                size = 2 ;
                                break ;
                        case 5:
                                size = 1 ;
                                break ;
                }

                fread( &row , 4 , 1 , fp ) ;
                if ( swap ) { row = trick_byteswap_int(row) ; }

                fread( &column , 4 , 1 , fp ) ;
                if ( swap ) { column = trick_byteswap_int(column) ; }

                fread( &imaginary , 4 , 1 , fp ) ;
                if ( swap ) { imaginary = trick_byteswap_int(imaginary) ; }

                fread( &len , 4 , 1 , fp ) ;
                if ( swap ) { len = trick_byteswap_int(len) ; }

                temp_ptr = new char[len +1] ;
                fread( temp_ptr , len , 1 , fp ) ;

                if ( ! strncmp( temp_ptr , param_name , len ) && y_field_num < column ) {
                        param_found = true ;
                }

                if ( ! strncmp( temp_ptr , time_name , len ) && time_field_num < column ) {
                        time_found = true ;
                }

                if ( mat_type != 0 ) {
                        fprintf(stderr,"Unknown matrix type for %s\n", temp_ptr) ;
                }

                if ( param_found && time_found ) {
                        fclose(fp) ;
                        delete temp_ptr ;
                        return(1) ;
                }

                delete temp_ptr ;

                // skip to next parameter
                fseek( fp ,  row * column * size * ( 1 + imaginary ) , SEEK_CUR ) ;
                offset = ftell(fp) ;

        }

        fclose(fp) ;
        return(0) ;
}
예제 #4
0
ll incexc(vector<int> v, int i, int left, int lcmt){
    if(left==0) return div(lcmt);
    if(i==v.size()) return 0;
    return (incexc(v, i+1, left, lcmt)+
           ((left>0)? incexc(v, i+1, left-1, lcm(lcmt, v[i])) :0)) % MOD;
}
예제 #5
0
int main(void)
{

    char choice='x';
    int a,b, exit=0;
    float fa,fb;

    do {
        printf("> ");
        fflush(stdin);
        scanf("%1s", &choice);
        switch(choice) {
            case '+':
                scanf("%d %d", &a, &b);
                printf("# %d\n",add(a,b));
                break;

            case '-':
                scanf("%d %d", &a, &b);
                printf("# %d\n",sub(a,b));
                break;

            case '/':
                scanf("%f %f", &fa, &fb);
                printf("# %.2f\n",div(fa, fb));
                break;

            case 'd':
                scanf("%d %d", &a, &b);
                printf("# %d\n",iDiv(a,b));
                break;

            case 'm':
                scanf("%d %d", &a, &b);
                printf("# %d\n",mod(a,b));
                break;

            case '*':
                scanf("%d %d", &a, &b);
                printf("# %d\n",mul(a,b));
                break;

            case '^':
                scanf("%d %d", &a,&b);
                printf("# %lld\n",nthPower(a, b));
                break;

            case '!':
                scanf("%d", &a);
                printf("# %lld\n",fact(a));
                break;

            case 's':
                scanf("%d", &a);
                printf("# %d\n",sum(a));
                break;

            case 'a':
                scanf("%d", &a);
                printf("# %.2f\n",avg(a));
                break;

            case 'c':
                scanf("%d %d", &a, &b);
                printf("# %lld\n",binom(a,b));
                break;

            case 'p':
                scanf("%d", &a);
                if(prime(a)) printf("# y\n");
                    else printf("# n\n");
                break;

            case 'q':
                exit = 1;
                break;

            default:printf("Unknown arguement: %c\n", choice);
        }
    } while(!exit);

    return 0;

}
예제 #6
0
파일: zaFont.cpp 프로젝트: cubezone/zaOS
int  zaFont::load_font(char * instr,int len)
{

		char * pin  = NULL;
		char * pout = NULL;
		char *p = NULL;

		char* inbuf = pin ; // m_filepos,  file head
		char* outbuf = pout;

		if (len==0)// utf8,
		{
			int ll= strlen(instr);
			size_t inbytesleft= ll+1;
			size_t outbytesleft = inbytesleft*2;

			pin = (char *)malloc(inbytesleft);
			pout = (char *)malloc(outbytesleft);

			inbuf = pin ; // m_filepos,  file head
			outbuf = pout;

			fprintf(stderr,"zaFont::load_font load begin length  %d\n",ll);
			strcpy(pin,instr);

			iconv_t tt;
			tt = iconv_open("UTF-16LE","UTF-8");
			int ret = iconv(tt,&inbuf,&inbytesleft,&outbuf,&outbytesleft);
			if ( ret < 0)
			{
				fprintf(stderr,"zaFont::load_font load error  errno %d\n",errno);
				throw CException(__FILE__,__LINE__,"zaFont::load_font convert error ,filename %s","NULL");
			}
			fprintf(stderr,"zaFont::load_font sucess.%d--%d:\n",ll*2,outbytesleft);
			iconv_close(tt);
			len = ll*2- outbytesleft;
			p= pout;
		}
		else
			p = instr;

			FT_Library library;
		    FT_Face face;
		    int c;
		    int i, j;
		    font_t* font = NULL;

		    if(FT_Init_FreeType(&library)) {
		        fprintf(stderr, "Error loading Freetype library\n");
		        return NULL;
		    }

		    if (FT_New_Face(library, m_path,0,&face)) {
		        fprintf(stderr, "Error loading font %s\n", m_path);
		        return NULL;
		    }

		    if(FT_Set_Char_Size ( face, m_size * 64, m_size * 64, m_dpi, m_dpi)) {
		        fprintf(stderr, "Error initializing character parameters\n");
		        return NULL;
		    }

		    unsigned int charcode = 0;

for (int cci =0 ; cci < len ; cci +=2)
{

charcode = ((unsigned char)*(p+1))*256+(unsigned char)*p ;
if (charcode == 601)
{
	charcode --;
	charcode ++;
}
if (this->m_map.find(charcode)==m_map.end())
{

		    font = (font_t*) malloc(sizeof(font_t));
		    font->initialized = 0;

		    glGenTextures(1, &(font->font_texture));

		    //Let each glyph reside in 32x32 section of the font texture
		    int segment_size_x = 0, segment_size_y = 0;
		    int num_segments_x = 1;//16
		    int num_segments_y = 1;//8

		    FT_GlyphSlot slot;
		    FT_Bitmap bmp;
		    int glyph_width, glyph_height;

		    //First calculate the max width and height of a character in a passed font
		    for(c = 0; c < 1; c++) {
		    	//
		        if(FT_Load_Char(face,0x4E2D+charcode-0x4E2D , FT_LOAD_RENDER)) {
		            fprintf(stderr, "FT_Load_Char failed\n");
		            free(font);
		            return NULL;
		        }

		        slot = face->glyph;
		        bmp = slot->bitmap;

		        //glyph_width = nextp2(bmp.width);
		        //glyph_height = nextp2(bmp.rows);

		        glyph_width = bmp.width;
		        glyph_height = bmp.rows;

		        if (glyph_width > segment_size_x) {
		            segment_size_x = glyph_width;
		        }

		        if (glyph_width > m_max_x)
		        	m_max_x = glyph_width;

		        if (glyph_height > segment_size_y) {
		            segment_size_y = glyph_height;
		        }

		        if (glyph_height > m_max_y)
		 		     m_max_y = glyph_height;
		    }

		    int font_tex_width = nextp2(num_segments_x * segment_size_x);
		    int font_tex_height = nextp2(num_segments_y * segment_size_y);

		    int bitmap_offset_x = 0, bitmap_offset_y = 0;

		    GLubyte* font_texture_data = (GLubyte*) malloc(sizeof(GLubyte) * 2 * font_tex_width * font_tex_height);
		    memset((void*)font_texture_data, 0, sizeof(GLubyte) * 2 * font_tex_width * font_tex_height);

		    if (!font_texture_data) {
		        fprintf(stderr, "Failed to allocate memory for font texture\n");
		        free(font);
		        return NULL;
		    }

		    // Fill font texture bitmap with individual bmp data and record appropriate size, texture coordinates and offsets for every glyph
		    for(c = 0; c < 1; c++)
		    {
		    	   if(FT_Load_Char(face,0x4E2D+charcode-0x4E2D , FT_LOAD_RENDER)) {
		            fprintf(stderr, "FT_Load_Char failed\n");
		            free(font);
		            return NULL;
		        }

		        slot = face->glyph;
		        bmp = slot->bitmap;

		        glyph_width = nextp2(bmp.width);
		        glyph_height = nextp2(bmp.rows);

		        div_t temp = div(c, num_segments_x);

		        bitmap_offset_x = segment_size_x * temp.rem;
		        bitmap_offset_y = segment_size_y * temp.quot;

		        for (j = 0; j < glyph_height; j++) {
		            for (i = 0; i < glyph_width; i++) {
		                font_texture_data[2 * ((bitmap_offset_x + i) + (j + bitmap_offset_y) * font_tex_width) + 0] =
		                font_texture_data[2 * ((bitmap_offset_x + i) + (j + bitmap_offset_y) * font_tex_width) + 1] =
		                    (i >= bmp.width || j >= bmp.rows)? 0 : bmp.buffer[i + bmp.width * j];
		            }
		        }

		        font->advance[c] = (float)(slot->advance.x >> 6);
		        font->tex_x1[c] = (float)bitmap_offset_x / (float) font_tex_width;
		        font->tex_x2[c] = (float)(bitmap_offset_x + bmp.width) / (float)font_tex_width;
		        font->tex_y1[c] = (float)bitmap_offset_y / (float) font_tex_height;
		        font->tex_y2[c] = (float)(bitmap_offset_y + bmp.rows) / (float)font_tex_height;
		        font->width[c] = bmp.width;
		        font->height[c] = bmp.rows;
		        font->offset_x[c] = (float)slot->bitmap_left;
		        font->offset_y[c] =  (float)((slot->metrics.horiBearingY-face->glyph->metrics.height) >> 6);
		    }


		    glBindTexture(GL_TEXTURE_2D, font->font_texture);
		    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);

		    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, font_tex_width, font_tex_height, 0, GL_LUMINANCE_ALPHA , GL_UNSIGNED_BYTE, font_texture_data);

		  //  fprintf(stderr, "charcode %d %d\n",charcode, cci);
		    fflush(stderr);
		    free(font_texture_data);
		    font->initialized = 1;
m_map[charcode] = font;
}
p += 2;
}
예제 #7
0
파일: nand.c 프로젝트: Styden/ibex
int
read_llb(h2fmi_read_boot_page_t read_page, int offset, int size, unsigned char *buf)
{
    int rv = 0;
    int page = div(offset, LLB_PAGE_SIZE); /*offset / LLB_PAGE_SIZE*/
    int start = offset - page * LLB_PAGE_SIZE; /*offset % LLB_PAGE_SIZE*/
#if 0
    unsigned char *tmp = malloc_(4096);
    if (!tmp) {
        return -1;
    }

    for (page += 2; size > 0; page++) {
        int chunk = size;
        if (chunk > LLB_PAGE_SIZE - start) {
            chunk = LLB_PAGE_SIZE - start;
        }

        rv = read_page(0, page, tmp);
        if (rv) {
            break;
        }

        memcpy(buf, tmp + start, chunk);

        start = 0;
        buf += chunk;
        size -= chunk;
    }
#else  /* XXX more efficient, but should be used ONLY if read_page reads exactly LLB_PAGE_SIZE bytes */
    unsigned char *tmp = NULL;

    page += 2;
    if (start) {
        int chunk = LLB_PAGE_SIZE - start;
        if (!(tmp = malloc_(LLB_PAGE_SIZE))) return -1;
        rv = read_page(0, page, tmp);
        if (rv) {
            goto err;
        }
        memcpy(buf, tmp + start, chunk);
        buf += chunk;
        size -= chunk;
        page++;
    }

    for (; size >= LLB_PAGE_SIZE; page++) {
        rv = read_page(0, page, buf);
        if (rv) {
            goto err;
        }
        buf += LLB_PAGE_SIZE;
        size -= LLB_PAGE_SIZE;
    }

    if (size) {
        if (!tmp && !(tmp = malloc_(LLB_PAGE_SIZE))) return -1;
        rv = read_page(0, page, tmp);
        if (rv == 0) {
            memcpy(buf, tmp, size);
        }
    }

  err:
#endif

    free_(tmp);
    return rv;
}
예제 #8
0
 bigint& operator %=(const bigint& x){ div(x); return *this; }
예제 #9
0
// decode header
void flexframesync_decode_header(flexframesync _q)
{
#if DEMOD_HEADER_SOFT
    // soft decoding operates on 'header_mod' array directly;
    // no need to pack bits
#else
    // pack 256 1-bit header symbols into 32 8-bit bytes
    unsigned int num_written;
    liquid_pack_bytes(_q->header_mod, FLEXFRAME_H_SYM,
                      _q->header_enc, FLEXFRAME_H_ENC,
                      &num_written);
    assert(num_written==FLEXFRAME_H_ENC);
#endif 

#if DEBUG_FLEXFRAMESYNC_PRINT
    unsigned int i;
    // print header (encoded)
    printf("header rx (enc) : ");
    for (i=0; i<FLEXFRAME_H_ENC; i++)
        printf("%.2X ", _q->header_enc[i]);
    printf("\n");
#endif

    // unscramble header and run packet decoder
#if DEMOD_HEADER_SOFT
    // soft demodulation operates on header_mod directly
    unscramble_data_soft(_q->header_mod, FLEXFRAME_H_ENC);
    _q->header_valid =
    packetizer_decode_soft(_q->p_header, _q->header_mod, _q->header);
#else
    unscramble_data(_q->header_enc, FLEXFRAME_H_ENC);
    _q->header_valid =
    packetizer_decode(_q->p_header, _q->header_enc, _q->header);
#endif

    // return if header is invalid
    if (!_q->header_valid)
        return;

    // first several bytes of header are user-defined
    unsigned int n = FLEXFRAME_H_USER;

    // first byte is for expansion/version validation
    if (_q->header[n+0] != FLEXFRAME_VERSION) {
        fprintf(stderr,"warning: flexframesync_decode_header(), invalid framing version\n");
        _q->header_valid = 0;
        return;
    }

    // strip off payload length
    unsigned int payload_dec_len = (_q->header[n+1] << 8) | (_q->header[n+2]);
    _q->payload_dec_len = payload_dec_len;

    // strip off modulation scheme/depth
    unsigned int mod_scheme = _q->header[n+3];

    // strip off CRC, forward error-correction schemes
    //  CRC     : most-significant 3 bits of [n+4]
    //  fec0    : least-significant 5 bits of [n+4]
    //  fec1    : least-significant 5 bits of [n+5]
    unsigned int check = (_q->header[n+4] >> 5 ) & 0x07;
    unsigned int fec0  = (_q->header[n+4]      ) & 0x1f;
    unsigned int fec1  = (_q->header[n+5]      ) & 0x1f;

    // validate properties
    if (mod_scheme == 0 || mod_scheme >= LIQUID_MODEM_NUM_SCHEMES) {
        fprintf(stderr,"warning: flexframesync_decode_header(), invalid modulation scheme\n");
        _q->header_valid = 0;
        return;
    }
    if (check >= LIQUID_CRC_NUM_SCHEMES) {
        fprintf(stderr,"warning: flexframesync_decode_header(), decoded CRC exceeds available\n");
        _q->header_valid = 0;
        return;
    }
    if (fec0 >= LIQUID_FEC_NUM_SCHEMES) {
        fprintf(stderr,"warning: flexframesync_decode_header(), decoded FEC (inner) exceeds available\n");
        _q->header_valid = 0;
        return;
    }
    if (fec1 >= LIQUID_FEC_NUM_SCHEMES) {
        fprintf(stderr,"warning: flexframesync_decode_header(), decoded FEC (outer) exceeds available\n");
        _q->header_valid = 0;
        return;
    }

    // configure payload receiver
    if (_q->header_valid) {
        // recreate modem
        _q->ms_payload    = mod_scheme;
        _q->bps_payload   = modulation_types[mod_scheme].bps;
        _q->demod_payload = modem_recreate(_q->demod_payload, _q->ms_payload);

        // set new packetizer properties
        _q->check  = check;
        _q->fec0   = fec0;
        _q->fec1   = fec1;

        // recreate packetizer object
        _q->p_payload = packetizer_recreate(_q->p_payload,
                                            _q->payload_dec_len,
                                            _q->check,
                                            _q->fec0,
                                            _q->fec1);

        // re-compute payload encoded message length
        _q->payload_enc_len = packetizer_get_enc_msg_len(_q->p_payload);

        // re-compute number of modulated payload symbols
        div_t d = div(8*_q->payload_enc_len, _q->bps_payload);
        _q->payload_mod_len = d.quot + (d.rem ? 1 : 0);
        
        // re-allocate buffers accordingly
        // (give encoded a few extra bytes to compensate for repacking)
        _q->payload_mod = (unsigned char*) realloc(_q->payload_mod, (_q->payload_mod_len  )*sizeof(unsigned char));
        _q->payload_enc = (unsigned char*) realloc(_q->payload_enc, (_q->payload_enc_len+8)*sizeof(unsigned char));
        _q->payload_dec = (unsigned char*) realloc(_q->payload_dec, (_q->payload_dec_len  )*sizeof(unsigned char));

        if (_q->payload_mod == NULL || _q->payload_enc == NULL || _q->payload_dec == NULL) {
            fprintf(stderr,"error: flexframesync_decode_header(), could not re-allocate payload arrays\n");
            _q->header_valid = 0;
            return;
        }
    }
    
#if DEBUG_FLEXFRAMESYNC_PRINT
    // print results
    printf("flexframesync_decode_header():\n");
    printf("    header crc      : %s\n", _q->header_valid ? "pass" : "FAIL");
    printf("    check           : %s\n", crc_scheme_str[check][1]);
    printf("    fec (inner)     : %s\n", fec_scheme_str[fec0][1]);
    printf("    fec (outer)     : %s\n", fec_scheme_str[fec1][1]);
    printf("    mod scheme      : %s\n", modulation_types[mod_scheme].name);
    printf("    payload dec len : %u\n", _q->payload_dec_len);
    printf("    payload enc len : %u\n", _q->payload_enc_len);
    printf("    payload mod len : %u\n", _q->payload_mod_len);

    printf("    user data       :");
    for (i=0; i<FLEXFRAME_H_USER; i++)
        printf(" %.2x", _q->header[i]);
    printf("\n");
#endif
}
예제 #10
0
/**************************
//Paillier HE system
//len: length of params p,q
**************************/
void Paillier(int len=512){
  ZZ n, n2, p, q, g, lamda;
  ZZ p1, q1, p1q1;
  ZZ miu;
  
  ZZ m1, m2;
  ZZ BSm, HEm; //baseline and HE result
  ZZ c, c1, c2, cm1, cm2, r;

  //key gen
  start = std::clock();

  GenPrime(p, len);
  GenPrime(q, len);
  mul(n, p, q);
  mul(n2, n, n);

  sub(p1,p,1);
  sub(q1,q,1);
  GCD(lamda,p1,q1);
  mul(p1q1,p1,q1);
  div(lamda, p1q1, lamda);

  RandomBnd(g, n2);

  PowerMod(miu,g,lamda,n2);
  sub(miu, miu, 1);
  div(miu,miu,n); //should add 1?
  InvMod(miu, miu, n);
  
  duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
  cout<<"Pailler Setup:"<< duration <<'\n';

  //Enc
  start = std::clock();
  RandomBnd(m1,n);
  RandomBnd(m2,n);

  RandomBnd(r,n); //enc m1
  PowerMod(c1, g,m1,n2);
  PowerMod(c2, r,n,n2);
  MulMod(cm1, c1,c2, n2);

  RandomBnd(r,n); //enc m2
  PowerMod(c1, g,m2,n2);
  PowerMod(c2, r,n,n2);
  MulMod(cm2, c1,c2, n2);

  duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
  cout<<"Pailler Enc:"<< duration/2 <<'\n';

  //Evaluation
  start = std::clock();
  c=cm1;
  for(int i=0; i<TIMES; i++)
  	MulMod(c,c,cm2,n2);
  duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
  cout<<"Pailler Eval:"<< duration <<'\n';

  //c=cm2;
  //Dec  
  start = std::clock();
  PowerMod(c,c,lamda,n2);
  sub(c,c,1);
  div(c,c,n); //should add 1?
  MulMod(HEm, c, miu, n);  

  duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
  cout<<"Pailler Dec:"<< duration <<'\n';

  //baseline
  BSm=m1;
  for(int i=0; i<TIMES; i++)
  	AddMod(BSm,BSm,m2,n);

  assert(BSm==HEm);
}
예제 #11
0
 bigint& operator /=(const bigint& x){ return *this = div(x); }
예제 #12
0
int main()
{
	char buffer[150];
	char command[50];
	
	char fileName2[50];
	char result[13000];
	char fileName1[25];
	char fileName1Tmp[25];
	char terminateString[3];
	int i, j, c;
	terminateString[0] = 0xd;
	terminateString[1] = 0xa;
	terminateString[2] = '\0';
	


	while(1)
	{

		interrupt(0x21, 0, "Shell:>\0", 0, 0);
		interrupt(0x21, 1, buffer, 0, 0);
		
		
		i = 0; j = 0;
		//read the command from the buffer
		while(buffer[i] != ' ' && buffer[i] != 0xd)
			command[j++] = buffer[i++];
		command[j] = '\0';

		j = 0;
		//make the pointer point to first character of fileName1 in the buffer
		if(buffer[i] == ' ')
			++i;
		//read fileName1 from the buffer
		while(buffer[i] != ' ' && buffer[i] != 0xd)
		{
			fileName1[j] = buffer[i];
			fileName1Tmp[j++] = buffer[i++];

		}
		fileName1[j] = '\0';
		fileName1Tmp[j] = '\0';

		j = 0;
		//make the pointer point to first character of fileName2 in the buffer
		if(buffer[i] == ' ')
			++i;
		//read fileName2 from the buffer
		while(buffer[i] != ' ' && buffer[i] != 0xd)
			fileName2[j++] = buffer[i++];
		fileName2[j] = '\0';
		
		

		//process view command
		if(equal("view\0", command))
		{
			//check if the file name is entered
			if(fileName1[0] == '\0')
			{
				interrupt(0x21, 0, "No file entered", 0, 0);
				interrupt(0x21, 0, terminateString, 0, 0);
				continue;
			}
			
			interrupt(0x21, 3, fileName1, result, 0);
			//check if the file exists or not
			if(equal("Error!\0", result))
			{
				interrupt(0x21, 0, "File not found", 0, 0);
				interrupt(0x21, 0, terminateString, 0, 0);
			}
			else
			{
				//print the file followed by a new line and carriage return
				interrupt(0x21, 0, result, 0, 0);
				interrupt(0x21, 0, terminateString, 0, 0);
			}
		}
		//process the execute command
		else if(equal("execute\0", command))
		{
			//check if the file name is entered
			if(fileName1[0] == '\0')
			{
				interrupt(0x21, 0, "No file entered", 0, 0);
				interrupt(0x21, 0, terminateString, 0, 0);
				continue;
			}
			//read the file to check if file exists or not
			interrupt(0x21, 3, fileName1, result, 0);
			if(equal("Error!\0", result))
			{
				interrupt(0x21, 0, "File not found", 0, 0);
				interrupt(0x21, 0, terminateString, 0, 0);
			}
			else
				interrupt(0x21, 4, fileName1, 0x2000, 0);
			
		}
		//process the delete command
		else if(equal("delete\0", command))
		{
			//check if the file name is entered
			if(fileName1[0] == '\0')
			{
				interrupt(0x21, 0, "No file entered", 0, 0);
				interrupt(0x21, 0, terminateString, 0, 0);
				continue;
			}
			//read the file to check if the file exists or not
			interrupt(0x21, 3, fileName1, result, 0);
			if(equal("Error!\0", result))
			{
				interrupt(0x21, 0, "File not found", 0, 0);
				interrupt(0x21, 0, terminateString, 0, 0);
			}
			else{
				interrupt(0x21, 7, fileName1, 0, 0);	
			}
		}
		//process the copy command
		else if(equal("copy\0", command))
		{
			//check if the file 1 name is entered
			if(fileName1[0] == '\0')
			{
				interrupt(0x21, 0, "File 1 not entered", 0, 0);
				interrupt(0x21, 0, terminateString, 0, 0);
				continue;
			}
			//check if the file 2 name is entered
			else if(fileName2[0] == '\0')
			{
				interrupt(0x21, 0, "File 2 not entered", 0, 0);
				interrupt(0x21, 0, terminateString, 0, 0);
				continue;
			}
			//read the file
			interrupt(0x21, 3, fileName1, result, 0);
			//check if the file exists
			if(equal("Error!\0", result))
			{
				interrupt(0x21, 0, "File not found", 0, 0);
				interrupt(0x21, 0, terminateString, 0, 0);
			}
			else{
				//count the number of sectors
				for(j = 0; result[j] != '\0'; j++);
				j = div(j+511,512);

				interrupt(0x21, 8, fileName2, result, j);	
			}
		}
		//process the dir command
		else if(equal("dir\0", command))
		{
			interrupt(0x21,9,result,0,0);
			interrupt(0x21, 0, result, 0, 0);
			interrupt(0x21, 0, terminateString, 0, 0);

		}
		//process the create command
		else if(equal("create\0", command))
		{
			//check if the file name is entered
			if(fileName1[0] == '\0')
			{
				interrupt(0x21, 0, "No name entered", 0, 0);
				interrupt(0x21, 0, terminateString, 0, 0);
				continue;
			}
			else
			{
				c=0;
				//read the first line into the buffer
				interrupt(0x21, 1, buffer, 0, 0);
				//terminate the loop if the first character in the line is 0xd (carriage return)
				while(buffer[0] != 0xd )
				{
					//copy the buffer into the result
					for (j = 0; buffer[j] != '\0'; ++j)
					{
						result[c++] = buffer[j];
					}
					//read the new line into the buffer
					interrupt(0x21, 1, buffer, 0, 0);
				}
				
				result[c-2] = '\0';
				interrupt(0x21,8,fileName1,result,1);
			}

		}
		else
		{
			//no valid command is entered
			interrupt(0x21, 0, "Bad command", 0, 0);
			interrupt(0x21, 0, terminateString, 0, 0);
		}



	}
}
예제 #13
0
int parse_args(int argc, char **argv, arguments_t *a) {

  int i;
  time_t systime;
  unsigned long long curr_time;
 
#ifndef _MSC_VER
  char *ep;
#endif

  unsigned int tmp_max_sb_len;
  unsigned int tmp_es_len;
  char *tmp_addr;
  unsigned char fec_enc;
  char *tmp_base_dir;
  char *tmp_repair;
  BOOL repair;
  unsigned long long tmp_tsi;
  unsigned long long duration;
  char *loss_ratio2;
  div_t div_max_k;
  div_t div_max_n;
 
  time(&systime);
  curr_time = systime + 2208988800U;
  
  tmp_tsi = DEF_TSI;					 /* transport session identifier */
  tmp_max_sb_len = 0;
  tmp_es_len = 0;
  tmp_addr = NULL;
  fec_enc = DEF_FEC;
  tmp_base_dir = NULL;
  tmp_repair = NULL;
  repair = FALSE;
  loss_ratio2 = NULL;
  duration = 0;

  a->toi = 0;							/* transport object identifier */
  a->cont = FALSE;					 /* continuous transmission */
  a->rx_automatic = FALSE;				 /* download files defined in IDT automatically */
  a->rx_object = FALSE;
  a->file_table_output = FALSE;
  a->log_fd = -1;
  a->complete_fdt = 0;
  a->send_session_close_packets = 1;
  a->name_incomplete_objects = FALSE;

#ifdef _MSC_VER
  a->open_file = FALSE;					 /* open received file automatically */
#endif

  memset(a->sdp_file, 0, MAX_PATH_LENGTH);
  memset(a->file_path, 0, MAX_PATH_LENGTH);  /* file(s) or directory to send */
  memset(a->fdt_file, 0, MAX_PATH_LENGTH);
  strcpy(a->fdt_file, DEF_FDT);				 /* fdt file (fdt based send) */
 
  a->alc_a.cc_id = DEF_CC;				/* congestion control */
  a->alc_a.mode = RECEIVER;				/* sender or receiver? */			
  a->alc_a.port = DEF_MCAST_PORT;				 /* local port number for base channel */
  a->alc_a.nb_channel = DEF_NB_CHANNEL;			 /* number of channels */
  a->alc_a.intface = NULL;					 /* interface */
  a->alc_a.intface_name = NULL;				 /* interface name/index for IPv6 multicast join */
  a->alc_a.addr_family = DEF_ADDR_FAMILY;
  a->alc_a.addr_type = 0;
  a->alc_a.es_len = DEF_SYMB_LENGTH;				 /* encoding symbol length */
  a->alc_a.max_sb_len = DEF_MAX_SB_LEN;			 /* source block length */
  a->alc_a.tx_rate = DEF_TX_RATE;				 /* transmission rate in kbit/s */
  a->alc_a.ttl = DEF_TTL;					 /* time to live  */
  a->alc_a.nb_tx = DEF_TX_NB;					 /* nb of time to send the file/directory */
  a->alc_a.simul_losses = FALSE;				 /* simulate packet losses */
  a->alc_a.loss_ratio1 = P_LOSS_WHEN_OK;
  a->alc_a.loss_ratio2 = P_LOSS_WHEN_LOSS;
  a->alc_a.fec_ratio = DEF_FEC_RATIO;				 /* FEC ratio percent */	
  a->alc_a.fec_enc_id = DEF_FEC_ENC_ID;			 /* FEC Encoding */
  a->alc_a.fec_inst_id = DEF_FEC_INST_ID; 
  a->alc_a.rx_memory_mode = 1;
  a->alc_a.verbosity = 1;  
  a->alc_a.use_fec_oti_ext_hdr = 0;				 /* include fec oti extension header to flute header */
  a->alc_a.encode_content = 0;				 /* encode content */
  a->alc_a.src_addr = NULL;
  a->alc_a.optimize_tx_rate = FALSE;
  a->alc_a.calculate_session_size = FALSE;
  a->alc_a.half_word = FALSE;
  a->alc_a.accept_expired_fdt_inst = FALSE;

#ifdef SSM
  a->alc_a.use_ssm = FALSE;					 /* use source specific multicast */
#endif
  
  if(strstr(argv[0], "repair_sender")) {
    a->alc_a.mode = SENDER;
    repair = TRUE;
  }
  else {
    a->alc_a.mode = RECEIVER;
  }

  for(i = 1; i < argc ; i++) {
    if(argv[i][0] == '-') {
      
      switch(argv[i][1])
	{
	case 'A':  /* automatic download */
	  if(strlen(argv[i]) > 2) {
	    return -1;
	  }
	  a->rx_automatic = TRUE;
	  break;
	case 'a':  /* address family */
	  if(strlen(argv[i]) > 3) {
	    if(!(strcmp(&argv[i][3], "IPv4"))) {
	      a->alc_a.addr_family = PF_INET;
	    }
	    else if(!(strcmp(&argv[i][3], "IPv6"))) {
	      a->alc_a.es_len = MAX_SYMB_LENGTH_IPv6_FEC_ID_0_3_130;
	      a->alc_a.addr_family = PF_INET6;
	    }
	  }
	  else {
	    return -1;
	  }
	  break;
	case 'B':  /* base directory for downloaded files */
	  if(strlen(argv[i]) > 3) {
	    tmp_base_dir = &argv[i][3];
	  }
	  else {
	    return -1;
	  }
	  break;
	case 'b':  /* rx_memory_mode */
	  if(strlen(argv[i]) > 3) {
	    a->alc_a.rx_memory_mode = (unsigned char)atoi(&argv[i][3]);

	    if(a->alc_a.rx_memory_mode > 2) {
	      printf("Possible values for option -b are: 0, 1, or 2\n");
	      fflush(stdout);
	      return -1;
	    }
	  }
	  else {                         
	    return -1;
	  }
	  break;
	case 'C':  /* Continuous transmission */
	  if(strlen(argv[i]) > 2) {
	    return -1;
	  }
	  a->cont = TRUE;
	  break;
	case 'c':  /* number of channels */
	  if(strlen(argv[i]) > 3) {
	    a->alc_a.nb_channel = (unsigned char)atoi(&argv[i][3]);
	    
	    if(a->alc_a.nb_channel > MAX_CHANNELS_IN_SESSION) {
	      printf("Channel number set to maximum value: %i\n", MAX_CHANNELS_IN_SESSION);
	      a->alc_a.nb_channel = MAX_CHANNELS_IN_SESSION;
	    }
	    else if(a->alc_a.nb_channel == 0) {
	      printf("Channel number set to 1\n");
	      a->alc_a.nb_channel = 1;
	    }
	  }
	  else {
	    return -1;
	  }
	  break;
	case 'D':  /* session duration time */
	  if(strlen(argv[i]) > 3) {
#ifdef _MSC_VER			  
	    duration = _atoi64(&argv[i][3]);
	    
	    if(duration > (unsigned long long)0xFFFFFFFFFFFFFFFF) {
	      printf("Duration: %I64u too big (max=%I64u)\n", duration, (unsigned long long)0xFFFFFFFFFFFFFFFF);
	      fflush(stdout);
	      return -1;
	    }
#else
	    duration = strtoull(&argv[i][3], &ep, 10);
	    
	    if(&argv[i][3] == '\0' || *ep != '\0') {
	      printf("Duration not a number\n");
	      fflush(stdout);
	      return -1;
	    }
	    
	    if(errno == ERANGE && duration == 0xFFFFFFFFFFFFFFFFULL) {
	      printf("Duration too big for unsigned long long (64 bits)\n");
	      fflush(stdout);
	      return -1;
	    }
#endif	
	  }
	  else {
	    return -1;
	  }
	  break;
	case 'd':  /* sdp file */
	  if(strlen(argv[i]) <= 3) {
		return -1;
	  }
	  else if(strlen(argv[i]) >= MAX_PATH_LENGTH) {
	    printf("\nFile path for SDP file too long\n");
		return -1;
	  }
	  else {
	    memset(a->sdp_file, 0, MAX_PATH_LENGTH);
	    strcpy(a->sdp_file, &argv[i][3]);
	  }
	  break;
	case 'E':  /* Accept Expired FDT Instances */
	  if(strlen(argv[i]) > 2) {
	    return -1;
	  }
	  a->alc_a.accept_expired_fdt_inst = TRUE;
	  break;
	case 'e':  /* Use fec oti extension header */
	  if(strlen(argv[i]) > 3) {
	    a->alc_a.use_fec_oti_ext_hdr = (unsigned char)atoi(&argv[i][3]);
	    
	    if(a->alc_a.use_fec_oti_ext_hdr > 1) {
	      printf("Possible values for option -e are: 0, or 1\n");
	      fflush(stdout);
	      return -1;
	    }
	  }
	  else {                         
	    return -1;
	  }
	  break;
	case 'F':  /* files or directories to send/receive */
	  if(strlen(argv[i]) <= 3) {
		return -1;
	  }
	  else if(strlen(argv[i]) >= MAX_PATH_LENGTH) {
	    printf("\nFile path for files or directories too long\n");
		return -1;
	  }
	  else {
	    memset(a->file_path, 0, MAX_PATH_LENGTH);
	    strcpy(a->file_path, &argv[i][3]);
	  }
	  memset(a->fdt_file, 0, MAX_PATH_LENGTH);
	  break;
	case 'f':  /* fdt based send */
	  if(strlen(argv[i]) <= 3) {
		return -1;
	  }
	  else if(strlen(argv[i]) >= MAX_PATH_LENGTH) {
	    printf("\nFile path for FDT file too long\n");
		return -1;
	  }
	  else {
	    memset(a->fdt_file, 0, MAX_PATH_LENGTH);
	    strcpy(a->fdt_file, &argv[i][3]);
	  }
	  memset(a->file_path, 0, MAX_PATH_LENGTH);
	  break;
	case 'G':  /* Calculate session size but do not send anything */
		if(strlen(argv[i]) > 2) {			
			return -1;			
		}	
		a->alc_a.calculate_session_size = TRUE;          
		break;
	case 'H':  /* use half-word */
	  if(strlen(argv[i]) > 2) {
	    return -1;
	  }
	  a->alc_a.half_word = TRUE;
	  break;
	case 'h':  /* help/usage */
	  return -1;
	  break;
	case 'I':  /* local interface name/index for IPv6 multicast join */
	  if(strlen(argv[i]) > 3) {
	    a->alc_a.intface_name = &argv[i][3];
	  }
	  else {
	    return -1;
	  }
	  break;
	case 'i':  /* local interface to use */
	  if(strlen(argv[i]) > 3) {
	    a->alc_a.intface = &argv[i][3];
	  }
	  else {
	    return -1;
	  }
	  break;
	//Malek El Khatib 14.05.2014
	//Start
	//User could customize name of output log file
	case 'J':  /* local interface to use */
		if(strlen(argv[i]) <= 3) {
			return -1;
		}
		else if(strlen(argv[i]) >= MAX_PATH_LENGTH) {
			printf("\nFile path for log file too long\n");
			return -1;
		}
		else {
			logFile=&argv[i][3];
		}
		break;
	//End
    case 'K':  /* 'repair_sender.conf' */
	  if(strlen(argv[i]) <= 3) {
		return -1;
	  }
	  else if(strlen(argv[i]) >= MAX_PATH_LENGTH) {
		printf("\nFile path for repair sender configuration file too long\n");
		return -1;
	  }
	  else {
		tmp_repair = &argv[i][3];
	  }
	  break;
	case 'k':  /* Complete FDT */
	  if(strlen(argv[i]) > 3) {
            a->complete_fdt = (unsigned short)atoi(&argv[i][3]);
          }
          else {
            return -1;
          }
          break;
	case 'L':  /* sbl length */
	  if(strlen(argv[i]) > 3) {
	    tmp_max_sb_len = (unsigned int)atoi(&argv[i][3]);
	  }
	  else {
	    return -1;
	  }
	  break;
	case 'l':  /*  encoding symbol length */
	  if(strlen(argv[i]) > 3) {
	    tmp_es_len = (unsigned short)atoi(&argv[i][3]);						
	  }
	  else {
	    return -1;
	  }
	  break;
#ifdef SSM
	case 'M':  /* use source specific multicast */
	  if(strlen(argv[i]) > 2) {
	    return -1;
	  }
	  a->alc_a.use_ssm = TRUE;
	  break;
	case 'm':  /* Multicast group for base channel */
	  if(strlen(argv[i]) > 3) {
	    tmp_addr = &argv[i][3];
	  }
	  else {
	    return -1;
	  }
	  break;
#endif
	case 'N':
	  if(strlen(argv[i]) > 2) {
	    return -1;
	  }
	  a->name_incomplete_objects = TRUE;
	  break;
	case 'n':  /* tx loops */
	  if(strlen(argv[i]) > 3) {
	    a->alc_a.nb_tx = (unsigned short)atoi(&argv[i][3]);
	  }
	  else {
	    return -1;
	  }
	  break;
#ifdef _MSC_VER
	case 'O':  /* automatic opening */
	  if(strlen(argv[i]) > 2) {
	    return -1;
	  }
	  a->open_file = TRUE;
	  break;
#endif
	case 'o':  /* toi */
	  if(strlen(argv[i]) > 3) {
#ifdef _MSC_VER			  
	    a->toi = _atoi64(&argv[i][3]);
	    
	    if(a->toi > (unsigned long long)0xFFFFFFFFFFFFFFFF) {
	      printf("TOI: %I64u too big (max=%I64u)\n", a->toi, (unsigned long long)0xFFFFFFFFFFFFFFFF);
	      fflush(stdout);
	      return -1;
	    }
#else	    
	    a->toi = strtoull(&argv[i][3], &ep, 10);
	    
	    if(&argv[i][3] == '\0' || *ep != '\0') {
	      printf("TOI not a number\n");
	      fflush(stdout);
	      return -1;
	    }
	    
	    if(errno == ERANGE && a->toi == 0xFFFFFFFFFFFFFFFFULL) {
	      printf("TOI too big for unsigned long long (64 bits)\n");
	      fflush(stdout);
	      return -1;
	    }
#endif
	    a->rx_object = 1;
	  }
	  else {
	    return -1;
	  }
	  break;
	case 'P':  /* simulate packet losses */
	  if(strlen(argv[i]) >= 2) {
	    a->alc_a.simul_losses = TRUE;
	  }
	  if(strlen(argv[i]) > 3) {
	    a->alc_a.loss_ratio1 = atof(strtok(&argv[i][3], ","));
	    loss_ratio2 = strtok(NULL, "\0");
	    if(loss_ratio2 == NULL) {
	      return -1;
	    }
	    a->alc_a.loss_ratio2 = atof(loss_ratio2);
	  }
	  if(strlen(argv[i]) == 3) {
	    return -1;
	  }
	  break;
	case 'p':  /* Port number for base channel*/
	  if(strlen(argv[i]) > 3) {
	    a->alc_a.port = &argv[i][3];

	    assert(atoi(a->alc_a.port) > 0);
	    assert(atoi(a->alc_a.port) <= 0xFFFF);
	  }
	  else {
	    return -1;
	  }
	  break;
	case 'q':  /* Send session close packets */
          if(strlen(argv[i]) > 3) {
            a->send_session_close_packets = atoi(&argv[i][3]);
          }
          else {
            return -1;
          }
          break;
	//Malek El Khatib 16.7.2014
	//Start
	case 'Q':  /* Send/Receive FDT after object */
	  if(strlen(argv[i]) > 2) {
	    return -1;
	  }
	  sendFDTAfterObj = TRUE;
	  break;
	//END
#ifdef USE_FILE_REPAIR
	case 'R':  /* 'apd.xml' or 'flute.conf' */
	  if(strlen(argv[i]) == 3) {
		return -1;
	  }
	  else if(strlen(argv[i]) >= MAX_PATH_LENGTH) {
		printf("\nFile path for repair configuration file too long\n");
		return -1;
	  }
	  else if(strlen(argv[i]) == 2) {
	    repair = TRUE;
	  }
	  else {
		repair = TRUE;
		tmp_repair = &argv[i][3];
	  }
	  break;
#endif
	case 'r':  /* Transmission rate in kbits/s */
	  if(strlen(argv[i]) > 3) {      
	    a->alc_a.tx_rate = (unsigned int)atoi(&argv[i][3]);
	  }
	  else {
	    return -1;
	  }
	  break;
	  
	case 'S':  /* sender */
	  if(strlen(argv[i]) > 2) {
	    return -1;
	  }
	  a->alc_a.mode = SENDER;
	  a->toi = FDT_TOI;
	  break;
	case 's':  /* first alc session identifier */
	  if(strlen(argv[i]) > 3) {
	    a->alc_a.src_addr = &argv[i][3];
	  }
	  else {
	    return -1;
	  }
	  break;
	case 'T':  /* ttl */
	  if(strlen(argv[i]) > 3) {
	    a->alc_a.ttl = (unsigned char)atoi(&argv[i][3]);
	  }
	  else {
	    return -1;
	  }
	  break;
	case 't':  /* second alc session identifier */
	  if(strlen(argv[i]) > 3) {
#ifdef _MSC_VER			  
	    tmp_tsi = _atoi64(&argv[i][3]);
#else	    
	    tmp_tsi = strtoull(&argv[i][3], &ep, 10);
	    
	    if(&argv[i][3] == '\0' || *ep != '\0') {                   
	      printf("TSI not a number\n");
	      fflush(stdout);
	      return -1;
	    }
	    
	    if(errno == ERANGE && tmp_tsi == 0xFFFFFFFFFFFFFFFFULL) {   
	      printf("TSI too big for unsigned long long (64 bits)\n");
	      fflush(stdout);
	      return -1;
	    }
#endif 
#ifdef _MSC_VER
	    if(tmp_tsi > (unsigned long long)0xFFFFFFFFFFFF) {
	      printf("TSI: %I64u too big (max=%I64u)\n", tmp_tsi, (unsigned long long)0xFFFFFFFFFFFF);
#else
	      if(tmp_tsi > 0xFFFFFFFFFFFFULL) {
		printf("TSI: %llu too big (max=%llu)\n", tmp_tsi, 0xFFFFFFFFFFFFULL);
#endif
		fflush(stdout);
		return -1;
	      }
	    }
	    else {
	      return -1;
	    }
	    break;
	  case 'U':  /* unicast address */                    
	    if(strlen(argv[i]) > 2) {
	      return -1;
	    }
	    a->alc_a.addr_type = 1;
	    break;
	  case 'V': /* redirect stderr and stdout into given file */
	    if (strlen(argv[i]) > 3) {
#ifdef _MSC_VER
	      a->log_fd = _open(&argv[i][3], _O_RDWR | _O_CREAT | _O_TRUNC, 0666);
#else 
	      a->log_fd = open(&argv[i][3], O_RDWR | O_CREAT | O_TRUNC, 0666);
#endif
	      
	      if(a->log_fd < 0) {
		
		printf("Log file: %s cannot be opened\n", &argv[i][3]);
		fflush(stdout);
		return -1;
	      }
	      
#ifdef _MSC_VER
	      _dup2(a->log_fd, _fileno(stdout));
	      _dup2(a->log_fd, _fileno(stderr));
#else
	      dup2(a->log_fd, fileno(stdout));
	      dup2(a->log_fd, fileno(stderr));
#endif
	    }
	    break;
	  case 'v':  /* verbosity level */
	    if(strlen(argv[i]) > 3) {
	      a->alc_a.verbosity = atoi(&argv[i][3]);
	      
	      if(a->alc_a.verbosity > 4) {
		printf("Possible values for option -v are: 0, 1, 2, 3, or 4\n");
		fflush(stdout);
		return -1;
	      }
	    }
	    else {
	      return -1;
	    }
	    break;
	  case 'W':  /* File table output */
	    if(strlen(argv[i]) > 2) {
	      return -1;
	    }
	    a->file_table_output = TRUE;
	    break;
	  case 'w':  /* congestion control */
	    if(strlen(argv[i]) > 3) {
	      a->alc_a.cc_id = (unsigned char)atoi(&argv[i][3]);
	      
	      if(a->alc_a.cc_id > 1) {
		printf("Possible values for option -w are: 0, or 1\n");
		fflush(stdout);
		return -1;
	      }
	    }
	    else {
	      return -1;
	    }
	    break;
	  case 'X':  /* FEC ratio percent */
	    if(strlen(argv[i]) > 3) {
	      a->alc_a.fec_ratio = (unsigned short)atoi(&argv[i][3]);
	    }
	    else {
	      return -1;
	    }
	    break;
	  case 'x':  /* fec encoding */
	    if(strlen(argv[i]) > 3) {
	      fec_enc = (unsigned char)atoi(&argv[i][3]);

	      if(fec_enc > 3) {
            printf("Possible values for option -x are: 0, 1, 2 or 3\n");
			fflush(stdout);
            return -1;
	      }
	    }
	    else {
	      return -1;
	    }
	    break;
		//Malek El Khatib 16.04.2014
		//START
		//Add file to indicate absolute sending times
	  case 'y':
		  if(strlen(argv[i]) <= 3) {
			  return -1;
		  }
		  else if(strlen(argv[i]) >= MAX_PATH_LENGTH) {
			  printf("\nFile path for input file too long\n");
			  return -1;
		  }
		  else {
			  sendingTimesFile=&argv[i][3];
		  }
		  break;
		//End
      //Indicate the number of es per packet. Zero indicates that file -y:str is used which determines the chunks to send at a time. Maximum data per packet will then be used
	  case 'Y':
		  if(strlen(argv[i]) > 3) {
			  numEncSymbPerPacket = strtoul(&argv[i][3], &ep, 10);
			  if(&argv[i][3] == '\0' || *ep != '\0') {                   
				  printf("Number of Encoding Symbols per packet is not a number or not a valid number\n");
				  fflush(stdout);
				  return -1;
			  }
		  }
		  else {
			  return -1;
		  }
		  break;
      //END
	  case 'Z':  /* optimize transmission rate (use more CPU) */
	    if(strlen(argv[i]) > 2) {
	      return -1;
	    }
	    a->alc_a.optimize_tx_rate = TRUE;
	    break;
	  case 'z':  /* encode content */
	    if(strlen(argv[i]) > 3) {
	      a->alc_a.encode_content = (unsigned char)atoi(&argv[i][3]);
	      
	      if(a->alc_a.encode_content > 3) {
		printf("Possible values for option -z are: 0, 1, 2 or 3\n");
		fflush(stdout);
		return -1;
	      }
	    }
	    else {
	      return -1;
	    }
	    break;
	  default:
	    return -1;
	    break;
	  }
	}
      else {
	return -1;
      }
    }
    
    if(tmp_addr == NULL) {
      if(a->alc_a.addr_family == PF_INET) {
	tmp_addr = DEF_MCAST_IPv4_ADDR;
      }
      else if(a->alc_a.addr_family == PF_INET6) {
	tmp_addr = DEF_MCAST_IPv6_ADDR;
      }
    }
    a->alc_a.addr = tmp_addr;
    
    if(fec_enc == 1) {
      a->alc_a.fec_enc_id = SIMPLE_XOR_FEC_ENC_ID;
      
      if(a->alc_a.addr_family == PF_INET) {
		a->alc_a.es_len = MAX_SYMB_LENGTH_IPv4_FEC_ID_2_128_129;
      }
      else if(a->alc_a.addr_family == PF_INET6) {
		a->alc_a.es_len = MAX_SYMB_LENGTH_IPv6_FEC_ID_2_128_129;
      }
    }
    else if(fec_enc == 2) {
      a->alc_a.fec_enc_id = SB_SYS_FEC_ENC_ID;
      a->alc_a.fec_inst_id = REED_SOL_FEC_INST_ID;
      
      if(a->alc_a.addr_family == PF_INET) {
		a->alc_a.es_len = MAX_SYMB_LENGTH_IPv4_FEC_ID_2_128_129;
      }
      else if(a->alc_a.addr_family == PF_INET6) {
		a->alc_a.es_len = MAX_SYMB_LENGTH_IPv6_FEC_ID_2_128_129;
      }
    }
    else if(fec_enc == 3) {
      a->alc_a.fec_enc_id = RS_FEC_ENC_ID;
    }
    
    if(a->alc_a.mode == RECEIVER) {
      a->alc_a.tsi = tmp_tsi;
      
      memset(a->alc_a.base_dir, 0, MAX_PATH_LENGTH);
      
      if(tmp_base_dir == NULL) {
	    strcpy(a->alc_a.base_dir, DEF_BASE_DIR);
      }
      else {
	    strcpy(a->alc_a.base_dir, tmp_base_dir);
      }
      
      a->alc_a.start_time = curr_time;

	  if(duration == 0) {
		  a->alc_a.stop_time = curr_time + DEF_RECEIVER_TIMEOUT;
	  }
	  else {
		  a->alc_a.stop_time = curr_time + duration;
	  }
      
#ifdef USE_FILE_REPAIR
      if(repair) {
	    memset(a->repair, 0, MAX_PATH_LENGTH);
	
	    if(tmp_repair == NULL) {
	      strcpy(a->repair, DEF_APD_CONF_FILE);
	    }
	    else {
	     strcpy(a->repair, tmp_repair);
	    }
      }
      else {
	    memset(a->repair, 0, MAX_PATH_LENGTH);
      }
#endif
      
    }
    else {
      if(((a->alc_a.half_word == FALSE) && (tmp_tsi > 0xFFFFFFFF))) {
	    printf("TSI too big for unsigned long (32 bits)\n");
	    fflush(stdout);
	    return -1;
      }
      else {
	    a->alc_a.tsi = tmp_tsi;
      }
      
      memset(a->alc_a.base_dir, 0, MAX_PATH_LENGTH);
      
      if(tmp_base_dir != NULL) {
	    strcpy(a->alc_a.base_dir, tmp_base_dir);
      }
      
      a->alc_a.start_time = curr_time;

	  if(duration == 0) {
        a->alc_a.stop_time = curr_time + DEF_SESSION_DURATION;
	  }
	  else {
        a->alc_a.stop_time = curr_time + duration;
	  }

#ifdef USE_FILE_REPAIR
      if(repair) {
	    memset(a->repair, 0, MAX_PATH_LENGTH);
	
	    if(tmp_repair == NULL) {
	      strcpy(a->repair, DEF_FLUTE_CONF_FILE);
	    }
	    else {
	     strcpy(a->repair, tmp_repair);
	    }
      }
      else {
	    memset(a->repair, 0, MAX_PATH_LENGTH);
      }
#else
      if(repair) {
	    memset(a->repair, 0, MAX_PATH_LENGTH);
	
	    if(tmp_repair == NULL) {
	      strcpy(a->repair, DEF_REPAIR_SENDER_CONF_FILE);
	    }
	    else {
	      strcpy(a->repair, tmp_repair);
	    }
      }
      else {
	    memset(a->repair, 0, MAX_PATH_LENGTH);
      }
#endif
    }
    
    if(tmp_max_sb_len != 0) {
      if(a->alc_a.fec_enc_id == COM_NO_C_FEC_ENC_ID) {
	
	if(tmp_max_sb_len > MAX_SB_LEN_NULL_FEC) {
	  printf("Maximum source block length set to maximum value: %i\n", MAX_SB_LEN_NULL_FEC);
	  fflush(stdout);
	  tmp_max_sb_len = MAX_SB_LEN_NULL_FEC;
	}
	a->alc_a.max_sb_len = tmp_max_sb_len;
      }
      
      else if(a->alc_a.fec_enc_id == SIMPLE_XOR_FEC_ENC_ID) {
	if(tmp_max_sb_len > MAX_SB_LEN_SIMPLE_XOR_FEC) {
	  printf("Maximum source block length set to maximum value: %i\n", MAX_SB_LEN_SIMPLE_XOR_FEC);
	  fflush(stdout);
	  tmp_max_sb_len = MAX_SB_LEN_SIMPLE_XOR_FEC;
	}
	a->alc_a.max_sb_len = tmp_max_sb_len;
      }
      
      else if(((a->alc_a.fec_enc_id == RS_FEC_ENC_ID) || ((a->alc_a.fec_enc_id == SB_SYS_FEC_ENC_ID)
	       && (a->alc_a.fec_inst_id == REED_SOL_FEC_INST_ID)))) {
	
	div_max_n = div((tmp_max_sb_len * (100 + a->alc_a.fec_ratio)), 100);
	
	if(div_max_n.quot > MAX_N_REED_SOLOMON) {
	  
	  div_max_k = div((MAX_N_REED_SOLOMON * 100), (100 + a->alc_a.fec_ratio));
	  
	  printf("Maximum source block length set to maximum value: %i\n", div_max_k.quot);
	  fflush(stdout);
	  tmp_max_sb_len = div_max_k.quot;
	}
	a->alc_a.max_sb_len = tmp_max_sb_len;
      }
    }
    
    if(tmp_es_len != 0) {
      if(a->alc_a.addr_family == PF_INET) {
	if(((a->alc_a.fec_enc_id == COM_NO_C_FEC_ENC_ID)
	    || (a->alc_a.fec_enc_id == RS_FEC_ENC_ID)
	    || (a->alc_a.fec_enc_id == COM_FEC_ENC_ID))) {
	  if(tmp_es_len > MAX_SYMB_LENGTH_IPv4_FEC_ID_0_3_130) {
	    printf("Encoding symbol length set to maximum value: %i\n",
		   MAX_SYMB_LENGTH_IPv4_FEC_ID_0_3_130);
	    fflush(stdout);
	    tmp_es_len = MAX_SYMB_LENGTH_IPv4_FEC_ID_0_3_130;
	  }
	}
	else if(((a->alc_a.fec_enc_id == SIMPLE_XOR_FEC_ENC_ID) ||
		 (a->alc_a.fec_enc_id == SB_LB_E_FEC_ENC_ID) ||
		 (a->alc_a.fec_enc_id == SB_SYS_FEC_ENC_ID))) {
	  if(tmp_es_len > MAX_SYMB_LENGTH_IPv4_FEC_ID_2_128_129) {
	    printf("Encoding symbol length set to maximum value: %i\n",
		   MAX_SYMB_LENGTH_IPv4_FEC_ID_2_128_129);
	    fflush(stdout);
	    tmp_es_len = MAX_SYMB_LENGTH_IPv4_FEC_ID_2_128_129;
	  }	
	}
      }
      else if(a->alc_a.addr_family == PF_INET6) {	
	if(((a->alc_a.fec_enc_id == COM_NO_C_FEC_ENC_ID)
	    || (a->alc_a.fec_enc_id == RS_FEC_ENC_ID)
	    || (a->alc_a.fec_enc_id == COM_FEC_ENC_ID))) {
	  if(tmp_es_len > MAX_SYMB_LENGTH_IPv6_FEC_ID_0_3_130) {
	    printf("Encoding symbol length set to maximum value: %i\n",
		   MAX_SYMB_LENGTH_IPv6_FEC_ID_0_3_130);
	    fflush(stdout);
	    tmp_es_len = MAX_SYMB_LENGTH_IPv6_FEC_ID_0_3_130;
	  }
	}
	else if(((a->alc_a.fec_enc_id == SIMPLE_XOR_FEC_ENC_ID) ||
		 (a->alc_a.fec_enc_id == SB_LB_E_FEC_ENC_ID) ||
		 (a->alc_a.fec_enc_id == SB_SYS_FEC_ENC_ID))) {
	  if(tmp_es_len > MAX_SYMB_LENGTH_IPv6_FEC_ID_2_128_129) {
	    printf("Encoding symbol length set to maximum value: %i\n",
		   MAX_SYMB_LENGTH_IPv6_FEC_ID_2_128_129);
	    fflush(stdout);
	    tmp_es_len = MAX_SYMB_LENGTH_IPv6_FEC_ID_2_128_129;
	  }	
	}
      }
      
      a->alc_a.es_len = tmp_es_len;
    }

    if(((((a->rx_automatic == TRUE) || (a->alc_a.mode == SENDER)))
	&& (a->file_table_output == TRUE))) {
      a->alc_a.verbosity = -1;
    }
    
    return 0;
  }
예제 #14
0
파일: stdlib.c 프로젝트: cartman300/picoc
void StdlibDiv(struct ParseState *Parser, struct Value *ReturnValue, struct Value **Param, int NumArgs)
{
    ReturnValue->Val->Integer = div(Param[0]->Val->Integer, Param[1]->Val->Integer);
}
예제 #15
0
/* ceil_DIV(a,b) :=  ceil(a / b)  in _int_ arithmetic : */
static R_INLINE
int ceil_DIV(int a, int b)
{
    div_t div_res = div(a, b);
    return div_res.quot + ((div_res.rem != 0) ? 1 : 0);
}
예제 #16
0
void __CLRCALL_PURE_OR_CDECL _MP_Rem(_MP_arr u, _Max_type v0)
	{	// divide multi-word value by value, leaving remainder in u
	_Max_type v[2];
	v[0] = v0 & mask;
	v[1] = v0 >> shift;
	const int n = limit(v, 2);
	const int m = limit(u, _MP_len) - n;

	// Knuth, vol. 2, p. 272, Algorithm D
	// D1: [Normalize.]
	_Max_type d = max / (v[n - 1] + 1);
	if (d != 1)
		{	// scale numerator and divisor
		mul(u, _MP_len, d);
		mul(v, n, d);
		}
	// D2: [Initialize j.]
	for (int j = m; 0 <= j; --j)
		{	// D3: [Calculate qh.]
		_Max_type qh = ((u[j + n] << shift) + u[j + n - 1]) / v[n - 1];
		if (qh == 0)
			continue;
		_Max_type rh = ((u[j + n] << shift) + u[j + n - 1]) % v[n - 1];
		for (;;)
			if (qh < max && qh * v[n - 2] <= (rh << shift) + u[j + n - 2])
				break;
			else
				{	// reduce tentative value and retry
				--qh;
				rh += v[n - 1];
				if (max <= rh)
					break;
				}
		// D4: [Multiply and subtract.]
		_Max_type k = 0;
		int i;
		for (i = 0; i < n; ++i)
			{	// multiply and subtract
			u[j + i] -= qh * v[i] + k;
			k = u[j + i] >> shift;
			if (k)
				k = max - k;
			u[j + i] &= mask;
			}
		for (; k != 0 && j + i < _MP_len; ++i)
			{	// propagate borrow
			u[j + i] -= k;
			k = u[j + i] >> shift;
			if (k)
				k = max - k;
			u[j + i] &= mask;
			}
		// D5: [Test remainder.]
		if (k != 0)
			{	// D6: [Add back.]
			--qh;
			add(u + j, n + 1, v, n);
			}
		// D7: [Loop on j.]
		}
	// D8: [Unnormalize.]
	if (d != 1)
		div(u, d);
	}
예제 #17
0
static void
find_empty_segs (PixelRegion  *maskPR,
		 gint          scanline,
		 gint          empty_segs[],
		 gint          max_empty,
		 gint         *num_empty,
		 BoundaryType  type,
		 gint          x1,
		 gint          y1,
		 gint          x2,
		 gint          y2)
{
  uint8_t* data;
  int x;
  int start, end;
  int val, last;
  int endx, l_num_empty;
  div_t d;

  data  = NULL;
  start = 0;
  end   = 0;

  *num_empty = 0;

  if (scanline < 0 || scanline >= maskPR->h)
    {
      empty_segs[(*num_empty)++] = 0;
      empty_segs[(*num_empty)++] = G_MAXINT;
      return;
    }

  if (type == WithinBounds)
    {
      if (scanline < y1 || scanline >= y2)
	{
	  empty_segs[(*num_empty)++] = 0;
	  empty_segs[(*num_empty)++] = G_MAXINT;
	  return;
	}

      start = x1;
      end = x2;
    }
  else if (type == IgnoreBounds)
    {
      start = 0;
      end = maskPR->w;
      if (scanline < y1 || scanline >= y2)
	x2 = -1;
    }

  /*   tilex = -1; */
  empty_segs[(*num_empty)++] = 0;
  last = -1;

  l_num_empty = *num_empty;

  d = div (start, 8);
  data = ((uint8_t*)maskPR->line[scanline])+d.quot;

  for (x = start; x < end;)
    {
      endx = end;
      if (type == IgnoreBounds && (endx > x1 || x < x2))
	{
	  for (; x < endx; x++)
	    {
	      if (*data & (1<<d.rem))
		if (x >= x1 && x < x2)
		  val = -1;
		else
		  val = 1;
	      else
		val = -1;
	      
	      _image_bitmap_next_bit(d, data);

	      if (last != val)
		empty_segs[l_num_empty++] = x;
	      
	      last = val;
	    }
	}
      else
	{
	  for (; x < endx; x++)
	    {
	      if (*data & (1<<d.rem))
		val = 1;
	      else
		val = -1;
	      
	      _image_bitmap_next_bit(d, data);

	      if (last != val)
		empty_segs[l_num_empty++] = x;

	      last = val;
	    }
	}
    }
  *num_empty = l_num_empty;

  if (last > 0)
    empty_segs[(*num_empty)++] = x;

  empty_segs[(*num_empty)++] = G_MAXINT;
}
예제 #18
0
// ============================================================================================
void	TestLauncher::run()
{
	bool res = false;
	int bsize = audioDeviceSettings->getBufferSize();
	unsigned int deviceChan = audioDeviceSettings->getOutputChannels();
	int nbuff;
	int remsamples;
	double progressMax;

	releaseAudioData();

	for (int i = 0; i<stimCount; i++)
	{
                if (threadShouldExit())
                    break;
		
			/* Create input stream for the audio file */
			File af(getCurrentTest()->soundFiles[i]);
			wavReader = audioFormatManager.createReaderFor( af );

			dbgOut( L"Loading file " + af.getFullPathName() ); 	

			if (wavReader == NULL)
			{
				lastError = L"Unable to create reader for  " + getCurrentTest()->soundFiles[i];
				return ;
	
			}

			/* get length and number of channels */
			if (wavReader->numChannels > deviceChan)
			{
				lastError = L"The number of audio channels in stimuli files exceeds available device outputs.";
				return ;
			}

			chanCount = wavReader->numChannels;
			samplesCount = static_cast<unsigned int> ( wavReader->lengthInSamples );
			
			/* adjust to the integer number of audio buffers */
			nbuff = div(samplesCount,bsize).quot;
			remsamples = div(samplesCount,bsize).rem;
			
			if (remsamples > 0)
			{
				samplesCount = bsize*(nbuff+1);
				progressMax = stimCount*(nbuff+1);
			}
			else
			{
				progressMax = stimCount*nbuff;
			}
				

			/* create audio data buffers */
			currentData = new int* [chanCount];
			if (currentData == NULL)
			{
				lastError = L"Unable to allocate " + String(2*chanCount*sizeof(float*) + L"b of memory." );
				return ;
			}

			/* create an array of pointers to data buffers */
			for (int ch = 0; ch < chanCount; ch++)
			{
				currentData[ch] = new int[samplesCount];
				if (currentData[ch] == NULL)
				{
					lastError = L"Unable to allocate " + String(samplesCount*sizeof(float*) + L"b of memory." );
					/* clean up (data is massive) */
					for (int k = 0; k<ch; k++)
					{
						delete [] currentData[k];
					}
					delete [] currentData;
					releaseAudioData();
					return ;
				}
				/* clear memory */
				//zeromem(currentData[ch], sizeof(int)*samplesCount);
			}
			/* add array to audioStimData */
			audioStimData.add(currentData);

			/* read file in memory */			
			for (int k=0; k<nbuff; k++)
			{
				res = wavReader->readSamples( currentData, chanCount, bsize*k, bsize*k, bsize);
				if (!res)
				{
					releaseAudioData();
					lastError = L"Unable to read data from file " + getCurrentTest()->soundFiles[i];
					return ;
				}

				/* update progress bar */
				setProgress((i*nbuff + k)/progressMax);
			}
			/* read the last buffer and zero pad */
			if (remsamples > 0)
			{
				/* zero-padding is done by AudioFormatReader */
				res = wavReader->readSamples( currentData, chanCount, bsize*nbuff, bsize*nbuff, bsize);
				if (!res)
				{
					releaseAudioData();
					lastError = L"Unable to read data from file " + getCurrentTest()->soundFiles[i];
					return ;
				}
			}

			/* clean up */
			delete wavReader;
	}

	/*for (int k = 0; k<chanCount; k++)
	{		
		debugBuffer(getAudioData(0,k,48000), bsize*5, L"audio") + String(k));
	}*/

	setProgress(1.0);
	wait(500);
}
예제 #19
0
//------------------------------------------------------------------------------
//  const Rmatrix operator/(const Rmatrix &m) const
//------------------------------------------------------------------------------
Rmatrix Rmatrix::operator/( const Rmatrix &m) const
{ 
   #ifdef DEBUG_DIVIDE
   MessageInterface::ShowMessage
      (wxT("Rmatrix::operator/() entered this=%s, m=%s\n"), this->ToString().c_str(),
       m.ToString().c_str());
   #endif
   
   if ((isSizedD == false) || (m.IsSized() == false))
      throw TableTemplateExceptions::UnsizedTable();
   
   bool oneByOneDivideMatrix = false;
   bool matrixDivideOneByOne = false;
   
   #ifdef DEBUG_DIVIDE
   MessageInterface::ShowMessage
      (wxT("   rowsD=%d, colsD=%d, m.rowsD=%d, m.colsD=%d\n"), rowsD, colsD, m.rowsD, m.colsD);
   #endif
   
   if (rowsD == 1 && colsD == 1)
      oneByOneDivideMatrix = true;
   else if (m.rowsD == 1 && m.colsD == 1)
      matrixDivideOneByOne = true;
   
   #ifdef DEBUG_DIVIDE
   MessageInterface::ShowMessage
      (wxT("   oneByOneDivideMatrix=%d, matrixDivideOneByOne=%d\n"),
       oneByOneDivideMatrix, matrixDivideOneByOne);
   #endif
   
   if (oneByOneDivideMatrix)
   {
      Rmatrix div(m.rowsD, m.colsD);
      Real oneByOne = GetElement(0, 0);
      
      for (int i = 0; i < m.rowsD; i++)
         for (int j = 0; j < m.colsD; j++)
            div(i, j) = oneByOne / m.GetElement(i, j);
      
      #ifdef DEBUG_DIVIDE
      MessageInterface::ShowMessage
         (wxT("Rmatrix::operator/() returning OneByOne/Matrix %s\n"), div.ToString().c_str());
      #endif
      return div;
   }
   else if (matrixDivideOneByOne)
   {
      Rmatrix div(rowsD, colsD);
      Real oneByOne = m.GetElement(0, 0);
      
      for (int i = 0; i < rowsD; i++)
         for (int j = 0; j < colsD; j++)
            div(i, j) = GetElement(i, j) / oneByOne;
      
      #ifdef DEBUG_DIVIDE
      MessageInterface::ShowMessage
         (wxT("Rmatrix::operator/() returning Matrix/OneByOne %s\n"), div.ToString().c_str());
      #endif
      return div;
   }
   else
      return (*this)*m.Inverse();
}
예제 #20
0
static int dom_decomp_2d(const int Nx, const int Ny,
			 const int Np, int *pNGx, int *pNGy){

  int rx, ry, I, rxs, rx_min, rx_max;
  int rx0=1, ry0=1, I0=0, init=1;
  div_t dv;

  /* Compute the ideal decomposition, truncated to an integer, which
     minimizes the amount of communication. */
  rxs = (int)sqrt((double)(Nx*Np)/(double)(Ny > 2*nghost ? Ny - 2*nghost : 1));

  /* Constrain the decomposition */
  rx_max = Nx < Np ? Nx : Np; /* Require ry >= 1 and rx <= Nx */
  if(Ny < Np){ /* Require rx >= 1 and ry <= Ny */
    dv = div(Np, Ny);
    /* rx_min = the smallest integer >= Np/Ny */
    rx_min = dv.quot + (dv.rem > 0 ? 1 : 0);
  }
  else rx_min = 1;

  /* printf("rx_min = %d, rx_max = %d\n",rx_min, rx_max); */

  /* Constrain rxs to fall in this domain */
  rxs = rxs > rx_min ? rxs : rx_min;
  rxs = rxs < rx_max ? rxs : rx_max;

  /* Search down for a factor of Np */
  for(rx=rxs; rx>=rx_min; rx--){
    dv = div(Np,rx);
    if(dv.rem == 0){
      rx0 = rx;
      ry0 = dv.quot;
      I0 = (rx0 - 1)*Ny + (ry0 - 1)*(Nx + 2*nghost*rx0);
      init = 0;
      break;
    }
  }

  /* Search up for a factor of Np */
  for(rx=rxs+1; rx<=rx_max; rx++){
    dv = div(Np,rx);
    if(dv.rem == 0){
      ry = dv.quot;
      I = (rx - 1)*Ny + (ry - 1)*(Nx + 2*nghost*rx);

      if(init || I < I0){
	rx0 = rx;
	ry0 = ry;
	I0  = I;
	init = 0;
      }
      break;
    }
  }

  if(init) return 1; /* Error locating a solution */

  /* printf("Minimum messaging decomposition has: rx = %d, ry = %d, I = %d\n",
     rx0, ry0, I0); */

  *pNGx = rx0;
  *pNGy = ry0;

  return 0;
}
예제 #21
0
font_t* bbutil_load_font(const char* path, int point_size, int dpi) {
    FT_Library library;
    FT_Face face;
    int c;
    int i, j;
    font_t* font;

    if (!initialized) {
        fprintf(stderr, "EGL has not been initialized\n");
        return NULL;
    }

    if (!path){
        fprintf(stderr, "Invalid path to font file\n");
        return NULL;
    }

    if(FT_Init_FreeType(&library)) {
        fprintf(stderr, "Error loading Freetype library\n");
        return NULL;
    }
    if (FT_New_Face(library, path,0,&face)) {
        fprintf(stderr, "Error loading font %s\n", path);
        return NULL;
    }

    if(FT_Set_Char_Size ( face, point_size * 64, point_size * 64, dpi, dpi)) {
        fprintf(stderr, "Error initializing character parameters\n");
        return NULL;
    }

    font = (font_t*) malloc(sizeof(font_t));
    font->initialized = 0;

    glGenTextures(1, &(font->font_texture));

    //Let each glyph reside in 32x32 section of the font texture
    int segment_size_x = 0, segment_size_y = 0;
    int num_segments_x = 16;
    int num_segments_y = 8;

    FT_GlyphSlot slot;
    FT_Bitmap bmp;
    int glyph_width, glyph_height;

    //First calculate the max width and height of a character in a passed font
    for(c = 0; c < 128; c++) {
        if(FT_Load_Char(face, c, FT_LOAD_RENDER)) {
            fprintf(stderr, "FT_Load_Char failed\n");
            free(font);
            return NULL;
        }

        slot = face->glyph;
        bmp = slot->bitmap;

        //glyph_width = nextp2(bmp.width);
        //glyph_height = nextp2(bmp.rows);

        glyph_width = bmp.width;
        glyph_height = bmp.rows;

        if (glyph_width > segment_size_x) {
            segment_size_x = glyph_width;
        }

        if (glyph_height > segment_size_y) {
            segment_size_y = glyph_height;
        }
    }

    int font_tex_width = nextp2(num_segments_x * segment_size_x);
    int font_tex_height = nextp2(num_segments_y * segment_size_y);

    int bitmap_offset_x = 0, bitmap_offset_y = 0;

    GLubyte* font_texture_data = (GLubyte*) malloc(sizeof(GLubyte) * 2 * font_tex_width * font_tex_height);
    memset((void*)font_texture_data, 0, sizeof(GLubyte) * 2 * font_tex_width * font_tex_height);

    if (!font_texture_data) {
        fprintf(stderr, "Failed to allocate memory for font texture\n");
        free(font);
        return NULL;
    }

    // Fill font texture bitmap with individual bmp data and record appropriate size, texture coordinates and offsets for every glyph
    for(c = 0; c < 128; c++) {
        if(FT_Load_Char(face, c, FT_LOAD_RENDER)) {
            fprintf(stderr, "FT_Load_Char failed\n");
            free(font);
            return NULL;
        }

        slot = face->glyph;
        bmp = slot->bitmap;

        glyph_width = nextp2(bmp.width);
        glyph_height = nextp2(bmp.rows);

        div_t temp = div(c, num_segments_x);

        bitmap_offset_x = segment_size_x * temp.rem;
        bitmap_offset_y = segment_size_y * temp.quot;

        for (j = 0; j < glyph_height; j++) {
            for (i = 0; i < glyph_width; i++) {
                font_texture_data[2 * ((bitmap_offset_x + i) + (j + bitmap_offset_y) * font_tex_width) + 0] =
                font_texture_data[2 * ((bitmap_offset_x + i) + (j + bitmap_offset_y) * font_tex_width) + 1] =
                    (i >= bmp.width || j >= bmp.rows)? 0 : bmp.buffer[i + bmp.width * j];
            }
        }

        font->advance[c] = (float)(slot->advance.x >> 6);
        font->tex_x1[c] = (float)bitmap_offset_x / (float) font_tex_width;
        font->tex_x2[c] = (float)(bitmap_offset_x + bmp.width) / (float)font_tex_width;
        font->tex_y1[c] = (float)bitmap_offset_y / (float) font_tex_height;
        font->tex_y2[c] = (float)(bitmap_offset_y + bmp.rows) / (float)font_tex_height;
        font->width[c] = bmp.width;
        font->height[c] = bmp.rows;
        font->offset_x[c] = (float)slot->bitmap_left;
        font->offset_y[c] =  (float)((slot->metrics.horiBearingY-face->glyph->metrics.height) >> 6);
    }

    glBindTexture(GL_TEXTURE_2D, font->font_texture);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, font_tex_width, font_tex_height, 0, GL_LUMINANCE_ALPHA , GL_UNSIGNED_BYTE, font_texture_data);

    int err = glGetError();

    free(font_texture_data);

    FT_Done_Face(face);
    FT_Done_FreeType(library);

    if (err != 0) {
        fprintf(stderr, "GL Error 0x%x", err);
        free(font);
        return NULL;
    }

    font->initialized = 1;
    return font;
}
예제 #22
0
파일: BigInt.cpp 프로젝트: ADJA/algos
 BigInt operator / (int number) {
     return div(number);
 }
예제 #23
0
void init_mesh(MeshS *pM)
{
  int nblock,num_domains,nd,nl,level,maxlevel=0,nd_this_level;
  int nDim,nDim_test,dim;
  int *next_domainid;
  char block[80];
  int ncd,ir,irefine,l,m,n,roffset;
  int i,Nx[3],izones;
  div_t xdiv[3];  /* divisor with quot and rem members */
  Real root_xmin[3], root_xmax[3];  /* min/max of x in each dir on root grid */
  int Nproc_Comm_world=1,nproc=0,next_procID;
  SideS D1,D2;
  DomainS *pD, *pCD;
#ifdef MPI_PARALLEL
  int ierr,child_found,groupn,Nranks,Nranks0,max_rank,irank,*ranks;
  MPI_Group world_group;

/* Get total # of processes, in MPI_COMM_WORLD */
  ierr = MPI_Comm_size(MPI_COMM_WORLD, &Nproc_Comm_world);
#endif

/* Start by initializing some quantaties in Mesh structure */

  pM->time = 0.0;
  pM->nstep = 0;
  pM->outfilename = par_gets("job","problem_id");

/*--- Step 1: Figure out how many levels and domains there are. --------------*/
/* read levels of each domain block in input file and calculate max level */

  num_domains = par_geti("job","num_domains");
#ifndef STATIC_MESH_REFINEMENT
  if (num_domains > 1) 
    ath_error("[init_mesh]: num_domains=%d; for num_domains > 1 configure with --enable-smr\n",num_domains);
#endif

  for (nblock=1; nblock<=num_domains; nblock++){
    sprintf(block,"domain%d",nblock);
    if (par_exist(block,"level") == 0)
      ath_error("[init_mesh]: level does not exist in block %s\n",block);
    level = par_geti(block,"level");
    maxlevel = MAX(maxlevel,level);
  }

/* set number of levels in Mesh, and allocate DomainsPerLevel array */

  pM->NLevels = maxlevel + 1;  /* level counting starts at 0 */

  pM->DomainsPerLevel = (int*)calloc_1d_array(pM->NLevels,sizeof(int));
  if (pM->DomainsPerLevel == NULL)
    ath_error("[init_mesh]: malloc returned a NULL pointer\n");

/* Now figure out how many domains there are at each level */

  for (nl=0; nl<=maxlevel; nl++){
    nd_this_level=0;
    for (nblock=1; nblock<=num_domains; nblock++){
      sprintf(block,"domain%d",nblock);
      if (par_geti(block,"level") == nl) nd_this_level++; 
    }

/* Error if there are any levels with no domains.  Else set DomainsPerLevel */

    if (nd_this_level == 0) {
      ath_error("[init_mesh]: Level %d has zero domains\n",nl);
    } else {
      pM->DomainsPerLevel[nl] = nd_this_level;
    }
  }

/*--- Step 2: Set up root level.  --------------------------------------------*/
/* Find the <domain> block in the input file corresponding to the root level,
 * and set root level properties in Mesh structure  */

  if (pM->DomainsPerLevel[0] != 1)
    ath_error("[init_mesh]: Level 0 has %d domains\n",pM->DomainsPerLevel[0]);

  for (nblock=1; nblock<=num_domains; nblock++){
    sprintf(block,"domain%d",nblock);
    level = par_geti(block,"level");
    if (level == 0){
      root_xmin[0] = par_getd(block,"x1min");
      root_xmax[0] = par_getd(block,"x1max");
      root_xmin[1] = par_getd(block,"x2min");
      root_xmax[1] = par_getd(block,"x2max");
      root_xmin[2] = par_getd(block,"x3min");
      root_xmax[2] = par_getd(block,"x3max");
      Nx[0] = par_geti(block,"Nx1");
      Nx[1] = par_geti(block,"Nx2");
      Nx[2] = par_geti(block,"Nx3");

/* number of dimensions of root level, to test against all other inputs */
      nDim=0;
      for (i=0; i<3; i++) if (Nx[i]>1) nDim++;
      if (nDim==0) ath_error("[init_mesh] None of Nx1,Nx2,Nx3 > 1\n");

/* some error tests of root grid */

      for (i=0; i<3; i++) {
        if (Nx[i] < 1) {
          ath_error("[init_mesh]: Nx%d in %s must be >= 1\n",(i+1),block);
        }
        if(root_xmax[i] < root_xmin[i]) {
          ath_error("[init_mesh]: x%dmax < x%dmin in %s\n",(i+1),block);
        }
      }
      if (nDim==1 && Nx[0]==1) {
        ath_error("[init_mesh]:1D requires Nx1>1: in %s Nx1=1,Nx2=%d,Nx3=%d\n",
        block,Nx[1],Nx[2]);
      }
      if (nDim==2 && Nx[2]>1) {ath_error(
        "[init_mesh]:2D requires Nx1,Nx2>1: in %s Nx1=%d,Nx2=%d,Nx3=%d\n",
        block,Nx[0],Nx[1],Nx[2]);
      }

/* Now that everything is OK, set root grid properties in Mesh structure  */

      for (i=0; i<3; i++) {
        pM->Nx[i] = Nx[i];
        pM->RootMinX[i] = root_xmin[i];
        pM->RootMaxX[i] = root_xmax[i];
        pM->dx[i] = (root_xmax[i] - root_xmin[i])/(Real)(Nx[i]);
      }

/* Set BC flags on root domain */

      pM->BCFlag_ix1 = par_geti_def(block,"bc_ix1",0);
      pM->BCFlag_ix2 = par_geti_def(block,"bc_ix2",0);
      pM->BCFlag_ix3 = par_geti_def(block,"bc_ix3",0);
      pM->BCFlag_ox1 = par_geti_def(block,"bc_ox1",0);
      pM->BCFlag_ox2 = par_geti_def(block,"bc_ox2",0);
      pM->BCFlag_ox3 = par_geti_def(block,"bc_ox3",0);
    }
  }

/*--- Step 3: Allocate and initialize domain array. --------------------------*/
/* Allocate memory and set pointers for Domain array in Mesh.  Since the
 * number of domains nd depends on the level nl, this is a strange array
 * because it is not [nl]x[nd].  Rather it is nl pointers to nd[nl] Domains.
 * Compare to the calloc_2d_array() function in ath_array.c
 */
      
  if((pM->Domain = (DomainS**)calloc((maxlevel+1),sizeof(DomainS*))) == NULL){
    ath_error("[init_mesh] failed to allocate memory for %d Domain pointers\n",
     (maxlevel+1));
  }

  if((pM->Domain[0]=(DomainS*)calloc(num_domains,sizeof(DomainS))) == NULL){
    ath_error("[init_mesh] failed to allocate memory for Domains\n");
  }

  for(nl=1; nl<=maxlevel; nl++)
    pM->Domain[nl] = (DomainS*)((unsigned char *)pM->Domain[nl-1] +
      pM->DomainsPerLevel[nl-1]*sizeof(DomainS));

/* Loop over every <domain> block in the input file, and initialize each Domain
 * in the mesh hierarchy (the Domain array), including the root level Domain  */

  next_domainid = (int*)calloc_1d_array(pM->NLevels,sizeof(int));
  for(nl=0; nl<=maxlevel; nl++) next_domainid[nl] = 0;

  for (nblock=1; nblock<=num_domains; nblock++){
    sprintf(block,"domain%d",nblock);

/* choose nd coordinate in Domain array for this <domain> block according
 * to the order it appears in input */

    nl = par_geti(block,"level");
    if (next_domainid[nl] > (pM->DomainsPerLevel[nl])-1)
      ath_error("[init_mesh]: Exceeded available domain ids on level %d\n",nl);
    nd = next_domainid[nl];
    next_domainid[nl]++;
    irefine = 1;
    for (ir=1;ir<=nl;ir++) irefine *= 2;   /* C pow fn only takes doubles !! */

/* Initialize level, number, input <domain> block number, and total number of
 * cells in this Domain */

    pM->Domain[nl][nd].Level = nl;
    pM->Domain[nl][nd].DomNumber = nd;
    pM->Domain[nl][nd].InputBlock = nblock;

    pM->Domain[nl][nd].Nx[0] = par_geti(block,"Nx1");
    pM->Domain[nl][nd].Nx[1] = par_geti(block,"Nx2");
    pM->Domain[nl][nd].Nx[2] = par_geti(block,"Nx3");

/* error tests: dimensions of domain */

    nDim_test=0;
    for (i=0; i<3; i++) if (pM->Domain[nl][nd].Nx[i]>1) nDim_test++;
    if (nDim_test != nDim) {
      ath_error("[init_mesh]: in %s grid is %dD, but in root level it is %dD\n",
      block,nDim_test,nDim);
    }
    for (i=0; i<3; i++) {
      if (pM->Domain[nl][nd].Nx[i] < 1) {
        ath_error("[init_mesh]: %s/Nx%d = %d must be >= 1\n",
          block,(i+1),pM->Domain[nl][nd].Nx[i]);
      }
    }
    if (nDim==1 && pM->Domain[nl][nd].Nx[0]==1) {ath_error(
      "[init_mesh]: 1D requires Nx1>1 but in %s Nx1=1,Nx2=%d,Nx3=%d\n",
      block,pM->Domain[nl][nd].Nx[1],pM->Domain[nl][nd].Nx[2]);
    }
    if (nDim==2 && pM->Domain[nl][nd].Nx[2]>1) {ath_error(
      "[init_mesh]:2D requires Nx1,Nx2 > 1 but in %s Nx1=%d,Nx2=%d,Nx3=%d\n",
      block,pM->Domain[nl][nd].Nx[0],pM->Domain[nl][nd].Nx[1],
      pM->Domain[nl][nd].Nx[2]);
    }
    for (i=0; i<nDim; i++) {
      xdiv[i] = div(pM->Domain[nl][nd].Nx[i], irefine);
      if (xdiv[i].rem != 0){
        ath_error("[init_mesh]: %s/Nx%d = %d must be divisible by %d\n",
          block,(i+1),pM->Domain[nl][nd].Nx[i],irefine);
      }
    }

/* Set cell size based on level of domain, but only if Ncell > 1 */

    for (i=0; i<3; i++) {
      if (pM->Domain[nl][nd].Nx[i] > 1) {
        pM->Domain[nl][nd].dx[i] = pM->dx[i]/(Real)(irefine);
      } else {
        pM->Domain[nl][nd].dx[i] = pM->dx[i];
      }
    }

/* Set displacement of Domain from origin. By definition, root level has 0
 * displacement, so only read for levels other than root  */

    for (i=0; i<3; i++) pM->Domain[nl][nd].Disp[i] = 0;
    if (nl != 0) {  
      if (par_exist(block,"iDisp") == 0)
        ath_error("[init_mesh]: iDisp does not exist in block %s\n",block);
      pM->Domain[nl][nd].Disp[0] = par_geti(block,"iDisp");

/* jDisp=0 if problem is only 1D */
      if (pM->Nx[1] > 1) {
        if (par_exist(block,"jDisp") == 0)
          ath_error("[init_mesh]: jDisp does not exist in block %s\n",block);
        pM->Domain[nl][nd].Disp[1] = par_geti(block,"jDisp");
      }

/* kDisp=0 if problem is only 2D */
      if (pM->Nx[2] > 1) {
        if (par_exist(block,"kDisp") == 0)
          ath_error("[init_mesh]: kDisp does not exist in block %s\n",block);
        pM->Domain[nl][nd].Disp[2] = par_geti(block,"kDisp");
      }
    }

    for (i=0; i<nDim; i++) {
      xdiv[i] = div(pM->Domain[nl][nd].Disp[i], irefine);
      if (xdiv[i].rem != 0){
        ath_error("[init_mesh]: %s/Disp%d = %d must be divisible by %d\n",
          block,(i+1),pM->Domain[nl][nd].Disp[i],irefine);
      }
    }

/* Use cell size and displacement from origin to compute min/max of x1/x2/x3 on
 * this domain.  Ensure that if Domain touches root grid boundary, the min/max
 * of this Domain are set IDENTICAL to values in root grid  */

    for (i=0; i<3; i++){

      if (pM->Domain[nl][nd].Disp[i] == 0) {
        pM->Domain[nl][nd].MinX[i] = root_xmin[i];
      } else { 
        pM->Domain[nl][nd].MinX[i] = root_xmin[i] 
          + ((Real)(pM->Domain[nl][nd].Disp[i]))*pM->Domain[nl][nd].dx[i];
      }

      izones= (pM->Domain[nl][nd].Disp[i] + pM->Domain[nl][nd].Nx[i])/irefine;
      if(izones == pM->Nx[i]){
        pM->Domain[nl][nd].MaxX[i] = root_xmax[i];
      } else {
        pM->Domain[nl][nd].MaxX[i] = pM->Domain[nl][nd].MinX[i] 
          + ((Real)(pM->Domain[nl][nd].Nx[i]))*pM->Domain[nl][nd].dx[i];
      }

      pM->Domain[nl][nd].RootMinX[i] = root_xmin[i];
      pM->Domain[nl][nd].RootMaxX[i] = root_xmax[i];
    }

  }  /*---------- end loop over domain blocks in input file ------------------*/
    
/*--- Step 4: Check that domains on the same level are non-overlapping. ------*/
/* Compare the integer coordinates of the sides of Domains at the same level.
 * Print error if Domains overlap or touch. */

  for (nl=maxlevel; nl>0; nl--){     /* start at highest level, and skip root */
  for (nd=0; nd<(pM->DomainsPerLevel[nl])-1; nd++){
    for (i=0; i<3; i++) {
      D1.ijkl[i] = pM->Domain[nl][nd].Disp[i];
      D1.ijkr[i] = pM->Domain[nl][nd].Disp[i] + pM->Domain[nl][nd].Nx[i];
    }

    for (ncd=nd+1; ncd<(pM->DomainsPerLevel[nl]); ncd++) {
      for (i=0; i<3; i++) {
        D2.ijkl[i] = pM->Domain[nl][ncd].Disp[i];
        D2.ijkr[i] = pM->Domain[nl][ncd].Disp[i] + pM->Domain[nl][ncd].Nx[i];
      }

      if (D1.ijkl[0] <= D2.ijkr[0] && D1.ijkr[0] >= D2.ijkl[0] &&
          D1.ijkl[1] <= D2.ijkr[1] && D1.ijkr[1] >= D2.ijkl[1] &&
          D1.ijkl[2] <= D2.ijkr[2] && D1.ijkr[2] >= D2.ijkl[2]){
          ath_error("Domains %d and %d at same level overlap or touch\n",
          pM->Domain[nl][nd].InputBlock,pM->Domain[nl][ncd].InputBlock);
      }
    }
  }}

/*--- Step 5: Check for illegal geometry of child/parent Domains -------------*/

  for (nl=0; nl<maxlevel; nl++){
  for (nd=0; nd<pM->DomainsPerLevel[nl]; nd++){
    pD = (DomainS*)&(pM->Domain[nl][nd]);  /* set ptr to this Domain */

    for (i=0; i<3; i++) {
      D1.ijkl[i] = pD->Disp[i];
      D1.ijkr[i] = pD->Disp[i] + pD->Nx[i];
    }

    for (ncd=0; ncd<pM->DomainsPerLevel[nl+1]; ncd++){
      pCD = (DomainS*)&(pM->Domain[nl+1][ncd]);  /* set ptr to potential child*/

      for (i=0; i<3; i++) {
        D2.ijkl[i] = pCD->Disp[i]/2;
        D2.ijkr[i] = 1;
        if (pCD->Nx[i] > 1) D2.ijkr[i] = (pCD->Disp[i] + pCD->Nx[i])/2;
      }

      if (D1.ijkl[0] <= D2.ijkr[0] && D1.ijkr[0] >= D2.ijkl[0] &&
          D1.ijkl[1] <= D2.ijkr[1] && D1.ijkr[1] >= D2.ijkl[1] &&
          D1.ijkl[2] <= D2.ijkr[2] && D1.ijkr[2] >= D2.ijkl[2]){

/* check for child Domains that touch edge of parent (and are not at edges of
 * root), extends past edge of parent, or are < nghost/2 from edge of parent  */

        for (dim=0; dim<nDim; dim++){
          irefine = 1;
          for (i=1;i<=nl;i++) irefine *= 2; /* parent refinement lev */
          roffset = (pCD->Disp[dim] + pCD->Nx[dim])/(2*irefine) - pM->Nx[dim];

          if (((D2.ijkl[dim] == D1.ijkl[dim]) && (pD->Disp[dim] != 0)) ||
              ((D2.ijkr[dim] == D1.ijkr[dim]) && (roffset != 0))) {
            for (i=0; i<nDim; i++) {
              D1.ijkl[i] /= irefine;  /* report indices scaled to root */
              D1.ijkr[i] /= irefine;
              D2.ijkl[i] /= irefine; 
              D2.ijkr[i] /= irefine;
            }
            ath_error("[init_mesh] child Domain D%d[is,ie,js,je,ks,ke]=[%d %d %d %d %d %d] touches parent D%d[is,ie,js,je,ks,ke]=[%d %d %d %d %d %d]\n",
              pCD->InputBlock,D2.ijkl[0],D2.ijkr[0],D2.ijkl[1],D2.ijkr[1],
              D2.ijkl[2],D2.ijkr[2],pD->InputBlock,D1.ijkl[0],D1.ijkr[0],
              D1.ijkl[1],D1.ijkr[1],D1.ijkl[2],D1.ijkr[2]);
          }

          if ((D2.ijkl[dim] < D1.ijkl[dim]) ||
              (D2.ijkr[dim] > D1.ijkr[dim])) {
            for (i=0; i<nDim; i++) {
              D1.ijkl[i] /= irefine;  /* report indices scaled to root */
              D1.ijkr[i] /= irefine;
              D2.ijkl[i] /= irefine; 
              D2.ijkr[i] /= irefine;
            }
            ath_error("[init_mesh] child Domain D%d[is,ie,js,je,ks,ke]=[%d %d %d %d %d %d] extends past parent D%d[is,ie,js,je,ks,ke]=[%d %d %d %d %d %d]\n",
              pCD->InputBlock,D2.ijkl[0],D2.ijkr[0],D2.ijkl[1],D2.ijkr[1],
              D2.ijkl[2],D2.ijkr[2],pD->InputBlock,D1.ijkl[0],D1.ijkr[0],
              D1.ijkl[1],D1.ijkr[1],D1.ijkl[2],D1.ijkr[2]);
          }

          if (((2*(D2.ijkl[dim]-D1.ijkl[dim]) < nghost) &&
               (2*(D2.ijkl[dim]-D1.ijkl[dim]) > 0     )) ||
              ((2*(D1.ijkr[dim]-D2.ijkr[dim]) < nghost) &&
               (2*(D1.ijkr[dim]-D2.ijkr[dim]) > 0     ))) {
            for (i=0; i<nDim; i++) {
              D1.ijkl[i] /= irefine;  /* report indices scaled to root */
              D1.ijkr[i] /= irefine;
              D2.ijkl[i] /= irefine; 
              D2.ijkr[i] /= irefine;
            }
            ath_error("[init_mesh] child Domain D%d[is,ie,js,je,ks,ke]=[%d %d %d %d %d %d] closer than nghost/2 to parent D%d[is,ie,js,je,ks,ke]=[%d %d %d %d %d %d]\n",
              pCD->InputBlock,D2.ijkl[0],D2.ijkr[0],D2.ijkl[1],D2.ijkr[1],
              D2.ijkl[2],D2.ijkr[2],pD->InputBlock,D1.ijkl[0],D1.ijkr[0],
              D1.ijkl[1],D1.ijkr[1],D1.ijkl[2],D1.ijkr[2]);
          }

        }
      }
    }
  }}

/*--- Step 6: Divide each Domain into Grids, and allocate to processor(s)  ---*/
/* Get the number of Grids in each direction.  These are given either in the
 * <domain?> block in the input file, or by automatic decomposition given the
 * number of processor desired for this domain.   */

  next_procID = 0;  /* start assigning processors to Grids at ID=0 */

  for (nl=0; nl<=maxlevel; nl++){
    for (nd=0; nd<(pM->DomainsPerLevel[nl]); nd++){
      pD = (DomainS*)&(pM->Domain[nl][nd]);  /* set ptr to this Domain */
      sprintf(block,"domain%d",pD->InputBlock);

#ifndef MPI_PARALLEL
      for (i=0; i<3; i++) pD->NGrid[i] = 1;
#else
      nproc = par_geti_def(block,"AutoWithNProc",0);

/* Read layout of Grids from input file */

      if (nproc == 0){
        pD->NGrid[0] = par_geti_def(block,"NGrid_x1",1);
        pD->NGrid[1] = par_geti_def(block,"NGrid_x2",1);
        pD->NGrid[2] = par_geti_def(block,"NGrid_x3",1);
        if (pD->NGrid[0] == 0)
          ath_error("[init_mesh] Cannot enter NGrid_x1=0 in %s\n",block);
        if (pD->NGrid[1] == 0)
          ath_error("[init_mesh] Cannot enter NGrid_x2=0 in %s\n",block);
        if (pD->NGrid[2] == 0)
          ath_error("[init_mesh] Cannot enter NGrid_x3=0 in %s\n",block);
      }

/* Auto decompose Domain into Grids.  To use this option, set "AutoWithNProc"
 * to number of processors desired for this Domain  */

      else if (nproc > 0){
        if(dom_decomp(pD->Nx[0],pD->Nx[1],pD->Nx[2],nproc,
           &(pD->NGrid[0]),&(pD->NGrid[1]),&(pD->NGrid[2])))
           ath_error("[init_mesh]: Error in automatic Domain decomposition\n");

        /* Store the domain decomposition in the par database */
        par_seti(block,"NGrid_x1","%d",pD->NGrid[0],"x1 decomp");
        par_seti(block,"NGrid_x2","%d",pD->NGrid[1],"x2 decomp");
        par_seti(block,"NGrid_x3","%d",pD->NGrid[2],"x3 decomp");

      } else {
        ath_error("[init_mesh] invalid AutoWithNProc=%d in %s\n",nproc,block);
      }
#endif /* MPI_PARALLEL */

/* test for conflicts between number of grids and dimensionality */

      for (i=0; i<3; i++){
        if(pD->NGrid[i] > 1 && pD->Nx[i] <= 1)
          ath_error("[init_mesh]: %s/NGrid_x%d = %d and Nx%d = %d\n",block,
          (i+1),pD->NGrid[i],(i+1),pD->Nx[i]);
      }

/* check there are more processors than Grids needed by this Domain. */

      nproc = (pD->NGrid[0])*(pD->NGrid[1])*(pD->NGrid[2]);
      if(nproc > Nproc_Comm_world) ath_error(
        "[init_mesh]: %d Grids requested by block %s and only %d procs\n"
        ,nproc,block,Nproc_Comm_world); 

/* Build 3D array to store data on Grids in this Domain */

      if ((pD->GData = (GridsDataS***)calloc_3d_array(pD->NGrid[2],pD->NGrid[1],
        pD->NGrid[0],sizeof(GridsDataS))) == NULL) ath_error(
        "[init_mesh]: GData calloc returned a NULL pointer\n");

/* Divide the domain into blocks */

      for (i=0; i<3; i++) {
        xdiv[i] = div(pD->Nx[i], pD->NGrid[i]);
      }

/* Distribute cells in Domain to Grids.  Assign each Grid to a processor ID in
 * the MPI_COMM_WORLD communicator.  For single-processor jobs, there is only
 * one ID=0, and the GData array will have only one element. */

      for(n=0; n<(pD->NGrid[2]); n++){
      for(m=0; m<(pD->NGrid[1]); m++){
      for(l=0; l<(pD->NGrid[0]); l++){
        for (i=0; i<3; i++) pD->GData[n][m][l].Nx[i] = xdiv[i].quot;
        pD->GData[n][m][l].ID_Comm_world = next_procID++;
        if (next_procID > ((Nproc_Comm_world)-1)) next_procID=0;
      }}}

/* If the Domain is not evenly divisible put the extra cells on the first
 * Grids in each direction, maintaining the load balance as much as possible */

      for(n=0; n<(pD->NGrid[2]); n++){
        for(m=0; m<(pD->NGrid[1]); m++){
          for(l=0; l<xdiv[0].rem; l++){
            pD->GData[n][m][l].Nx[0]++;
          }
        }
      }
      xdiv[0].rem=0;

      for(n=0; n<(pD->NGrid[2]); n++){
        for(m=0; m<xdiv[1].rem; m++) {
          for(l=0; l<(pD->NGrid[0]); l++){
            pD->GData[n][m][l].Nx[1]++;
          }
        }
      }
      xdiv[1].rem=0;

      for(n=0; n<xdiv[2].rem; n++){
        for(m=0; m<(pD->NGrid[1]); m++){
          for(l=0; l<(pD->NGrid[0]); l++){
            pD->GData[n][m][l].Nx[2]++;
          }
        }
      }
      xdiv[2].rem=0;

/* Initialize displacements from origin for each Grid */

      for(n=0; n<(pD->NGrid[2]); n++){
        for(m=0; m<(pD->NGrid[1]); m++){
          pD->GData[n][m][0].Disp[0] = pD->Disp[0];
          for(l=1; l<(pD->NGrid[0]); l++){
            pD->GData[n][m][l].Disp[0] = pD->GData[n][m][l-1].Disp[0] + 
                                         pD->GData[n][m][l-1].Nx[0];
          }
        }
      }

      for(n=0; n<(pD->NGrid[2]); n++){
        for(l=0; l<(pD->NGrid[0]); l++){
          pD->GData[n][0][l].Disp[1] = pD->Disp[1];
          for(m=1; m<(pD->NGrid[1]); m++){
            pD->GData[n][m][l].Disp[1] = pD->GData[n][m-1][l].Disp[1] + 
                                         pD->GData[n][m-1][l].Nx[1];
          }
        }
      }

      for(m=0; m<(pD->NGrid[1]); m++){
        for(l=0; l<(pD->NGrid[0]); l++){
          pD->GData[0][m][l].Disp[2] = pD->Disp[2];
          for(n=1; n<(pD->NGrid[2]); n++){
            pD->GData[n][m][l].Disp[2] = pD->GData[n-1][m][l].Disp[2] + 
                                         pD->GData[n-1][m][l].Nx[2];
          }
        }
      }

    }  /* end loop over ndomains */
  }    /* end loop over nlevels */

/* check that total number of Grids was partitioned evenly over total number of
 * MPI processes available (equal to one for single processor jobs) */ 

  if (next_procID != 0)
    ath_error("[init_mesh]:total # of Grids != total # of MPI procs\n");

/*--- Step 7: Allocate a Grid for each Domain on this processor --------------*/

  for (nl=0; nl<=maxlevel; nl++){
    for (nd=0; nd<(pM->DomainsPerLevel[nl]); nd++){
      pD = (DomainS*)&(pM->Domain[nl][nd]);  /* set ptr to this Domain */
      sprintf(block,"domain%d",pD->InputBlock);
      pD->Grid = NULL;

/* Loop over GData array, and if there is a Grid assigned to this proc, 
 * allocate it */

      for(n=0; n<(pD->NGrid[2]); n++){
      for(m=0; m<(pD->NGrid[1]); m++){
      for(l=0; l<(pD->NGrid[0]); l++){
        if (pD->GData[n][m][l].ID_Comm_world == myID_Comm_world) {
          if ((pD->Grid = (GridS*)malloc(sizeof(GridS))) == NULL)
            ath_error("[init_mesh]: Failed to malloc a Grid for %s\n",block);
        }
      }}}
    }
  }

/*--- Step 8: Create an MPI Communicator for each Domain ---------------------*/

#ifdef MPI_PARALLEL
/* Allocate memory for ranks[] array */

  max_rank = 0;
  for (nl=0; nl<=maxlevel; nl++){
  for (nd=0; nd<(pM->DomainsPerLevel[nl]); nd++){
    pD = (DomainS*)&(pM->Domain[nl][nd]);  /* set ptr to this Domain */
    Nranks = (pD->NGrid[0])*(pD->NGrid[1])*(pD->NGrid[2]);
    max_rank = MAX(max_rank, Nranks);
  }}
  ranks = (int*)calloc_1d_array(max_rank,sizeof(int));

/* Extract handle of group defined by MPI_COMM_WORLD communicator */

  ierr = MPI_Comm_group(MPI_COMM_WORLD, &world_group);

  for (nl=0; nl<=maxlevel; nl++){
  for (nd=0; nd<(pM->DomainsPerLevel[nl]); nd++){
    pD = (DomainS*)&(pM->Domain[nl][nd]);  /* set ptr to this Domain */

/* Load integer array with ranks of processes in MPI_COMM_WORLD updating Grids
 * on this Domain.  The ranks of these processes in the new Comm_Domain
 * communicator created below are equal to the indices of this array */

    Nranks = (pD->NGrid[0])*(pD->NGrid[1])*(pD->NGrid[2]);
    groupn = 0;

    for(n=0; n<(pD->NGrid[2]); n++){
    for(m=0; m<(pD->NGrid[1]); m++){
    for(l=0; l<(pD->NGrid[0]); l++){
      ranks[groupn] = pD->GData[n][m][l].ID_Comm_world;
      pD->GData[n][m][l].ID_Comm_Domain = groupn;
      groupn++;
    }}}

/* Create a new group for this Domain; use it to create a new communicator */

    ierr = MPI_Group_incl(world_group,Nranks,ranks,&(pD->Group_Domain));
    ierr = MPI_Comm_create(MPI_COMM_WORLD,pD->Group_Domain,&(pD->Comm_Domain));

  }}

  free_1d_array(ranks);
#endif /* MPI_PARALLEL */

/*--- Step 9: Create MPI Communicators for Child and Parent Domains ----------*/

#if defined(MPI_PARALLEL) && defined(STATIC_MESH_REFINEMENT)
/* Initialize communicators to NULL, since not all Domains use them, and
 * allocate memory for ranks[] array */

  for (nl=0; nl<=maxlevel; nl++){
    for (nd=0; nd<(pM->DomainsPerLevel[nl]); nd++){
      pM->Domain[nl][nd].Comm_Parent = MPI_COMM_NULL;
      pM->Domain[nl][nd].Comm_Children = MPI_COMM_NULL;
    }
  }

  if (maxlevel > 0) {
    ranks = (int*)calloc_1d_array(Nproc_Comm_world,sizeof(int));
  }

/* For each Domain up to (maxlevel-1), initialize communicator with children */

  for (nl=0; nl<maxlevel; nl++){
  for (nd=0; nd<pM->DomainsPerLevel[nl]; nd++){
    pD = (DomainS*)&(pM->Domain[nl][nd]);  /* set ptr to this Domain */
    child_found = 0;

/* Load integer array with ranks of processes in MPI_COMM_WORLD updating Grids
 * on this Domain, in case a child Domain is found.  Set IDs in Comm_Children
 * communicator based on index in rank array, in case child found.  If no
 * child is found these ranks will never be used. */

    Nranks = (pD->NGrid[0])*(pD->NGrid[1])*(pD->NGrid[2]);
    groupn = 0;

    for(n=0; n<(pD->NGrid[2]); n++){
    for(m=0; m<(pD->NGrid[1]); m++){
    for(l=0; l<(pD->NGrid[0]); l++){
      ranks[groupn] = pD->GData[n][m][l].ID_Comm_world;
      pD->GData[n][m][l].ID_Comm_Children = groupn;
      groupn++;
    }}}

/* edges of this Domain */
    for (i=0; i<3; i++) {
      D1.ijkl[i] = pD->Disp[i];
      D1.ijkr[i] = pD->Disp[i] + pD->Nx[i];
    }

/* Loop over all Domains at next level, looking for children of this Domain */

    for (ncd=0; ncd<pM->DomainsPerLevel[nl+1]; ncd++){
      pCD = (DomainS*)&(pM->Domain[nl+1][ncd]);  /* set ptr to potential child*/

/* edges of potential child Domain */
      for (i=0; i<3; i++) {
        D2.ijkl[i] = pCD->Disp[i]/2;
        D2.ijkr[i] = 1;
        if (pCD->Nx[i] > 1) D2.ijkr[i] = (pCD->Disp[i] + pCD->Nx[i])/2;
      }

      if (D1.ijkl[0] < D2.ijkr[0] && D1.ijkr[0] > D2.ijkl[0] &&
          D1.ijkl[1] < D2.ijkr[1] && D1.ijkr[1] > D2.ijkl[1] &&
          D1.ijkl[2] < D2.ijkr[2] && D1.ijkr[2] > D2.ijkl[2]){
        child_found = 1;

/* Child found.  Add child processors to ranks array, but only if they are
 * different from processes currently there (including parent and any previously
 * found children).  Set IDs associated with Comm_Parent communicator, since on 
 * the child Domain this is the same as the Comm_Children communicator on the
 * parent Domain  */

        for(n=0; n<(pCD->NGrid[2]); n++){
        for(m=0; m<(pCD->NGrid[1]); m++){
        for(l=0; l<(pCD->NGrid[0]); l++){
          irank = -1;
          for (i=0; i<Nranks; i++) {
            if(pCD->GData[n][m][l].ID_Comm_world == ranks[i]) irank = i;
          }
          if (irank == -1) {
            ranks[groupn] = pCD->GData[n][m][l].ID_Comm_world;
            pCD->GData[n][m][l].ID_Comm_Parent = groupn;
            groupn++;
            Nranks++;
          } else {
            pCD->GData[n][m][l].ID_Comm_Parent = ranks[irank];
          }
        }}}
      }
    }

/* After looping over all potential child Domains, create a new communicator if
 * a child was found */

    if (child_found == 1) {
      ierr = MPI_Group_incl(world_group, Nranks, ranks, &(pD->Group_Children));
      ierr = MPI_Comm_create(MPI_COMM_WORLD,pD->Group_Children,
        &pD->Comm_Children);

/* Loop over children to set Comm_Parent communicators */

      for (ncd=0; ncd<pM->DomainsPerLevel[nl+1]; ncd++){
        pCD = (DomainS*)&(pM->Domain[nl+1][ncd]);  

        for (i=0; i<3; i++) {
          D2.ijkl[i] = pCD->Disp[i]/2;
          D2.ijkr[i] = 1;
          if (pCD->Nx[i] > 1) D2.ijkr[i] = (pCD->Disp[i] + pCD->Nx[i])/2;
        }

        if (D1.ijkl[0] < D2.ijkr[0] && D1.ijkr[0] > D2.ijkl[0] &&
            D1.ijkl[1] < D2.ijkr[1] && D1.ijkr[1] > D2.ijkl[1] &&
            D1.ijkl[2] < D2.ijkr[2] && D1.ijkr[2] > D2.ijkl[2]){
          pCD->Comm_Parent = pD->Comm_Children;
        }
      }
    }
  }}

#endif /* MPI_PARALLEL & STATIC_MESH_REFINEMENT  */

  free(next_domainid);
  return;
}
예제 #24
0
void PVector::normalize() {
	float m = mag();
	if (m != 0) {
		div(m);
	}
}
예제 #25
0
double_buffer( InfoStruct *recInfo, float *leadSnds[], float *lagSnds[], float *locations, float *azimuths, float *rove, float *scalesLead, float *scalesLag, float *attensLead, int nSignal )
{
FILE	*fptr;
long	seekpos = 0;
float	preloadScale = .2;
int		i, j;

char	OutFNA [MAX_FILENAME_LEN];
char	OutFNB [MAX_FILENAME_LEN];

float	temp;

int		record = recInfo->record;
int		cnt = 1;

unsigned int DEC_FACT = recInfo->decimateFactor;
unsigned int SignalPlayFlag = 0;
unsigned int signalScale = 0, Signalcnt = 0, readflag = 0;
unsigned int MAX_SIGNAL_JITTER = recInfo->max_signal_jitter;
unsigned int NUM_CARRIERS_TO_ROVE = recInfo->num_carriers;
unsigned int rove_id;
unsigned int TRIALS_TO_SHOW = 3;

long	NPTS = recInfo->buf_pts;

/* just for plotting PDR trace in real time */
long	DEC_PTS = ceil(NPTS / pow(2, DEC_FACT));
long	ONSET = ceil(recInfo->sound_onset / pow(2, DEC_FACT));
long	NPTS_totalplay = recInfo->nptsTotalPlay;
long	templ;
long	buffer_cnt=0;
float	HAB_LOC = recInfo->hab_loc;

int		src[3];
float	sf[3];

div_t	div_result;

int		loc;

/* Display output variables: */
int     t0,t1, n;
float	elapsed_time;
float	rem_time;
int		min;
float	sec, cntdown;
char	str[100] = { '\0' };
float	pdrBuffer[DEFAULT_PTS];
int		len;
float	xy[2];

/* select SS1 output */
int		ss_id, out_port;

srand( (unsigned)time( NULL ) );

/* setup session info display */
len = ceil(NPTS * (SRATE/1E3));

// was commented out - put back in on Sep 14, 2009
if (record)
{
	play0_record0(recInfo->outFN1, recInfo->outFN2);
	remove(recInfo->outFN1);
	remove(recInfo->outFN2);
	//remove(recInfo->AD_FN);
}
// end comment out


if(!S2init(0, INIT_SECONDARY, 20000))
	mexErrMsgTxt("S2init failed");

if(!APlock(200, 0))
{
	S2close();
	mexErrMsgTxt("APLock failed");
}

if(!XBlock(200, 0))
{
	APunlock(0);
	S2close();
	mexErrMsgTxt("XBlock failed");
}

trash();
dropall();

// set up buffers
allot16( PLAY_SPEC, 10);
allot16( CHA_SEQ, 10);
allot16( BUF_A1, NPTS);
allot16( BUF_A2, NPTS);
allot16( CHB_SEQ, 10);
allot16( BUF_B1, NPTS);
allot16( BUF_B2, NPTS);

// play specification list
dpush(10);
value(0);
make(0,CHA_SEQ);
make(1,CHB_SEQ);
make(2,0);
qpop16(PLAY_SPEC);

// playsequence for ChanA
dpush(10);
value(0);
make(0,BUF_A1);
make(1,1);
make(2,BUF_A2);
make(3,1);
make(4,0);
qpop16(CHA_SEQ);
// playsequence for ChanB
dpush(10);
value(0);
make(0,BUF_B1);
make(1,1);
make(2,BUF_B2);
make(3,1);
make(4,0);
qpop16(CHB_SEQ);


if (record)			// record eye signal
{
	// set up buffers
	allot16( REC_SPEC, 10);
	allot16( RECCHA_SEQ, 10);
	allot16( RECBUF_A1, NPTS);
	allot16( RECBUF_A2, NPTS);
	allot16( RECCHB_SEQ, 10);
	allot16( RECBUF_B1, NPTS);
	allot16( RECBUF_B2, NPTS);

	temp = ceil(NPTS / pow(2, DEC_FACT));
	allot16( DECBUF_A, temp);
	allot16( DECBUF_B, temp);

	// record specification list
	dpush(10);
	value(0);
	make(0,RECCHA_SEQ);
	make(1,RECCHB_SEQ);
	make(2,0);
	qpop16(REC_SPEC);

	// recordsequence for ChanA
	dpush(10);
	value(0);
	make(0,RECBUF_A1);
	make(1,1);
	make(2,RECBUF_A2);
	make(3,1);
	make(4,0);
	qpop16(RECCHA_SEQ);
	// recordsequence for ChanB
	dpush(10);
	value(0);
	make(0,RECBUF_B1);
	make(1,1);
	make(2,RECBUF_B2);
	make(3,1);
	make(4,0);
	qpop16(RECCHB_SEQ);
}

// allot and load buffers for LEAD SOUNDS
for( j=0; j<NUM_CARRIERS_TO_ROVE; j++ ) {
	allotf( BUF_LEAD(j), NPTS);
	pushf(leadSnds[j], NPTS);
	qpopf(BUF_LEAD(j));
}

// allot and load buffers for LAG SOUNDS
for( j=0; j<NUM_CARRIERS_TO_ROVE; j++ ) {
	allotf( BUF_LAG(j), NPTS);
	pushf(lagSnds[j], NPTS);
	qpopf(BUF_LAG(j));
}

// setup PD1
PD1clear(1);
PD1srate(1,SRATE);
PD1npts(1,-1);

PD1resetDSP(1,0xFFF);
dropall();
PD1clrsched(1);
PD1nstrms(1, 2, record*2);

PD1addsimp(1, IREG[0], DAC[0]);  
PD1specIB (1, IB[0],   IREG[0]);

PD1addsimp(1, IREG[1], DAC[1]);  
PD1specIB (1, IB[1],   IREG[1]);

if (record)
{
	PD1specOB (1, OB[1], ADC[1]);
	PD1specOB (1, OB[0], ADC[0]);
}

PF1freq(1,12000,0);
PF1freq(2,12000,0);

dropall();

/* set LED thresholds */
PD1setIO(1,0.01,9.99,0.01,9.99);

/* setup signal switchers */

/* SWITCH BETWEEN 8 LAG SPEAKERS (Nos. 2, 3, 4, ... 9) */
/* (NOTE: Speaker #1 is reserved for the lead sound) */

SS1clear(1); /* left SS1 (LAG) */
SS1mode(1, QUAD_2_1); /* inputs 1, 3, 5, 7 => outputs A,B,C,D */
SS1select(1,0,1); /* Default Lag Output is A (Hab Location) */

// set attenuation
PA4atten(1,0); /* lead channel */
PA4atten(2,0); /* lag ch */

// ready,set,go!!
dropall();

// nothing to chanA (LEAD)
dpush(NPTS);
value(0);
qpop16(BUF_A1);

dpush(NPTS);
value(0);
qpop16(BUF_A2);
		
// nothing to chanB (LAG)
dpush(NPTS);
value(0);
qpop16(BUF_B1);
				
dpush(NPTS);
value(0);
qpop16(BUF_B2);				
			
seqplay(PLAY_SPEC);
if (record)
	seqrecord(REC_SPEC);
		
PD1arm (1);
pfireall();
PD1go (1);

do
{
 	do{}while (playseg(1)==BUF_A1);		// wait for #1 buffers to finish
	
	t0 = clock();

	SignalPlayFlag = 0;

	if(signalScale >0)
	{
		readflag = 1;
	}
	else if(readflag)
	{
		readflag = 0;
		SignalPlayFlag = 1;
	}
	

	
	/* count down to next test trial */
	cntdown = (recInfo->ISI - cnt)*(NPTS*SRATE/1E6);
	for(i=0; i<(recInfo->n_trials - Signalcnt); i++) {
		if(locations[Signalcnt+i]!=HAB_LOC)
			break;
		cntdown += (recInfo->ISI+1)*(NPTS*SRATE/1E6);

	}
		
		
	/* display session info */
	
	elapsed_time = seekpos*(SRATE/1E6);
	div_result = div( elapsed_time, 60 );
	min = div_result.quot; sec = elapsed_time - (60*min);
	memset(str,'\0',sizeof(str));
	n=sprintf(str,"session.elapsed_time(1)=%i; session.elapsed_time(2)=%.3f;",min,sec);
	mexEvalString(str);
	rem_time = NPTS_totalplay*(SRATE/1E6) - elapsed_time;
	div_result = div( rem_time, 60 );
	min = div_result.quot; sec = rem_time - (60*min);
	memset(str,'\0',sizeof(str));
	n=sprintf(str,"session.rem_time(1)=%i; session.rem_time(2)=%.3f;",min,sec);
	mexEvalString(str);
	div_result = div( cntdown, 60 );
	min = div_result.quot; sec = cntdown - (60*min);
	memset(str,'\0',sizeof(str));
	n=sprintf(str,"session.next_test_trial(1)=%i; session.next_test_trial(2)=%.3f;",min,sec);
	mexEvalString(str);
	mexEvalString("sessionPlots('Update Session Info');");
	
	
	// re-loading #1 playbuffers
	// LEAD to chanA LAG to chanB
	dropall();
	if (cnt==recInfo->ISI)
	{
		// Jitter trial presentation
		if (MAX_SIGNAL_JITTER > 0)
		{
			cnt = ( rand() % (2*MAX_SIGNAL_JITTER+1) ) - MAX_SIGNAL_JITTER; // gives a range of +/- MAX_SIGNAL_JITTER
		} else
		{
			cnt = 0;
		}
		

		loc = locations[Signalcnt];
		/* location series indicates lag speaker # (2, 3, 4, ... 9) */

	
		// set attenuation
		PA4atten(1,attensLead[loc-2]); /* lead channel */
		PA4atten(2,0); /* lag ch */

		SS1clear(1); SS1clear(2);
		if (loc < 6) {
			ss_id = 1; /* use left SS1 */
			out_port = loc - 2; /* decrement by 2 for output selection */
		}
		else {
			ss_id = 2; /* use right SS1 */
			out_port = loc - 6; /* decrement by 6 for output selection */
		}
		
		SS1mode(ss_id, QUAD_2_1); /* inputs 1, 3, 5, 7 => outputs A,B,C,D */
		SS1select(ss_id,out_port,1); /* Chan B (LAG) location ( speakers A...D = 0...3 ) */


		
		/* plot a marker on trial sequence plot */
		memset(str,'\0',sizeof(str));
		n=sprintf(str,"session.trialcnt=%i; session.trialval=%10.1f;sessionPlots('Update Trial Plot');",Signalcnt+1,azimuths[loc-1]);
		mexEvalString(str);
		
		
		rove_id = rove[Signalcnt ++] - 1; /* decrement by 1 for C indexing */
		
		signalScale=scalesLead[loc-2];
		qpushf(BUF_LEAD(rove_id));
		scale(signalScale); /* always scale with first speaker scaling value */
		qpop16(BUF_A1);	

		signalScale=scalesLag[loc-2];
		qpushf(BUF_LAG(rove_id));
		scale(signalScale); /* decrement by 1 to get appropriate speaker scale value */
		qpop16(BUF_B1);

	}
	else
	{
		signalScale = 0;
		cnt++;
		dpush(NPTS);
		value(0);
		qpop16(BUF_A1);

		dpush(NPTS);
		value(0);
		qpop16(BUF_B1);	
	}

	
	if(record)
	{		// downloading  #1 recordbuffers
		qpush16 (RECBUF_A1);    
		decimate (DEC_FACT);
		make(0, SignalPlayFlag);
		make(1, loc);
		qpop16   (DECBUF_A);
		dama2disk16 (DECBUF_A, recInfo->outFN1, 1);

		qpush16 (RECBUF_B1);
		decimate (DEC_FACT);
		// plot PDR trace
		qdup();
		popf(pdrBuffer);
		// store last buffer in matlab variable for plotting
		for(i=0; i<DEC_PTS; i++) {
			memset(str,'\0',sizeof(str));
			n=sprintf(str,"session.last_buffer(%i+1)= %.5f;",i,pdrBuffer[i]);
			mexEvalString(str);
		}
		
		if(SignalPlayFlag) {
			if(locations[Signalcnt-1]==HAB_LOC) {
				mexEvalString("session.test_flag=1;");
			}
			else {
				mexEvalString("session.test_flag=Inf;");
			}
		}
		else {
			mexEvalString("session.test_flag=0;");
		}
		
		// tell sessionPlots to update trace
		mexEvalString("sessionPlots('Update Trace Plot');");
		make(0, SignalPlayFlag);
		make(1, loc);
		qpop16   (DECBUF_B);
		dama2disk16 (DECBUF_B, recInfo->outFN2, 1);
		dropall ();
		
	}
	
	/* processing time */
	
	t1=clock();
	memset(str,'\0',sizeof(str));
	n = sprintf(str,"session.proc_time = [session.proc_time %.3f];",((float) (t1-t0))/CLOCKS_PER_SEC);
	mexEvalString(str);
	mexEvalString("sessionPlots('Update Session Info');");
	
	seekpos += NPTS;
	if(seekpos < NPTS_totalplay)
	{
		// wait for #2 buffers to finish
		do{}while (playseg(1)==BUF_A2);		// wait for #2 buffers to finish

     	t0=clock();
     	
		SignalPlayFlag = 0;
	
		if(signalScale >0)
		{
			readflag = 1;
		}
		else if(readflag)
		{
			readflag = 0;
			SignalPlayFlag = 1;
		}
		
	/* count down to next test trial */
	cntdown = (recInfo->ISI - cnt)*(NPTS*SRATE/1E6);
	for(i=0; i<(recInfo->n_trials - Signalcnt); i++) {
		if(locations[Signalcnt+i]!=HAB_LOC)
			break;
		cntdown += (recInfo->ISI+1)*(NPTS*SRATE/1E6);

	}
		
		
	/* display session info */
	
	elapsed_time = seekpos*(SRATE/1E6);
	div_result = div( elapsed_time, 60 );
	min = div_result.quot; sec = elapsed_time - (60*min);
	memset(str,'\0',sizeof(str));
	n=sprintf(str,"session.elapsed_time(1)=%i; session.elapsed_time(2)=%.3f;",min,sec);
	mexEvalString(str);
	rem_time = NPTS_totalplay*(SRATE/1E6) - elapsed_time;
	div_result = div( rem_time, 60 );
	min = div_result.quot; sec = rem_time - (60*min);
	memset(str,'\0',sizeof(str));
	n=sprintf(str,"session.rem_time(1)=%i; session.rem_time(2)=%.3f;",min,sec);
	mexEvalString(str);
	div_result = div( cntdown, 60 );
	min = div_result.quot; sec = cntdown - (60*min);
	memset(str,'\0',sizeof(str));
	n=sprintf(str,"session.next_test_trial(1)=%i; session.next_test_trial(2)=%.3f;",min,sec);
	mexEvalString(str);
	mexEvalString("sessionPlots('Update Session Info');");

		// reload #2 playbuffers    LEAD to chanA LAG to chanB
		dropall();
		if (cnt==recInfo->ISI)
		{
			if (MAX_SIGNAL_JITTER > 0)
			{
				cnt = ( rand() % (2*MAX_SIGNAL_JITTER+1) ) - MAX_SIGNAL_JITTER; // gives a range of +/- MAX_SIGNAL_JITTER
			} else
			{
				cnt = 0;
			}
			
			loc = locations[Signalcnt];
			/* location series indicates lag speaker # (2, 3, 4, ... 9) */
	
			// set attenuation
			PA4atten(1,attensLead[loc-2]); /* lead channel */
			PA4atten(2,0); /* lag ch */
			
			SS1clear(1); SS1clear(2);
			if (loc < 6) {
				ss_id = 1; /* use left SS1 */
				out_port = loc - 2; /* decrement by 2 for output selection */
			}
			else {
				ss_id = 2; /* use right SS1 */
				out_port = loc - 6; /* decrement by 6 for output selection */
			}
		
			SS1mode(ss_id, QUAD_2_1); /* inputs 1, 3, 5, 7 => outputs A,B,C,D */
			SS1select(ss_id,out_port,1); /* Chan B (LAG) location ( speakers A...D = 0...3 ) */
		
			/* plot a marker on trial sequence plot */
			memset(str,'\0',sizeof(str));
			n=sprintf(str,"session.trialcnt=%i; session.trialval=%10.1f;sessionPlots('Update Trial Plot');",Signalcnt+1,azimuths[loc-1]);
			mexEvalString(str);

			rove_id = rove[Signalcnt ++] - 1; /* decrement by 1 for C indexing */
			
			signalScale=scalesLead[loc-2];
			qpushf(BUF_LEAD(rove_id));
			scale(signalScale); /* always scale with first speaker scaling value */
			qpop16(BUF_A2);	
	
			signalScale=scalesLag[loc-2];
			qpushf(BUF_LAG(rove_id));
			scale(signalScale); /* decrement by 1 to get appropriate speaker scale value */
			qpop16(BUF_B2);

		}
		else
		{
			signalScale = 0;
			cnt++;
			dpush(NPTS);
			value(0);;
			qpop16(BUF_A2);

			dpush(NPTS);
			value(0);
			qpop16(BUF_B2);
		}
		
		
		if (record)
		{		// download #2 recordbuffers
			qpush16 (RECBUF_A2);    
			decimate (DEC_FACT);
			make(0,SignalPlayFlag);
			make(1,loc);
			qpop16	(DECBUF_A);
			dama2disk16 (DECBUF_A, recInfo->outFN1, 1);

			qpush16 (RECBUF_B2);
			decimate (DEC_FACT);
			// plot PDR trace
			qdup();
			popf(pdrBuffer);
			// store last buffer in matlab variable for plotting
			for(i=0; i<DEC_PTS; i++) {
				memset(str,'\0',sizeof(str));
				n=sprintf(str,"session.last_buffer(%i+1)= %.5f;",i,pdrBuffer[i]);
				mexEvalString(str);
			}

			if(SignalPlayFlag) {
				if(locations[Signalcnt-1]==HAB_LOC) {
					mexEvalString("session.test_flag=1;");
				}
				else {
					mexEvalString("session.test_flag=Inf;");
				}
			}
			else {
				mexEvalString("session.test_flag=0;");
			}

			// tell sessionPlots to update trace
			mexEvalString("sessionPlots('Update Trace Plot');");
			make(0,SignalPlayFlag);
			make(1,loc);
			qpop16   (DECBUF_B);
			dama2disk16 (DECBUF_B, recInfo->outFN2, 1);
			dropall ();
		
		}

		if (playseg(1) !=BUF_A1)
		{
			PD1stop(1);
			mexPrintf("got to %d percent of the way\n",seekpos/NPTS_totalplay);
			mexErrMsgTxt(" APcard too slow? or outFNs incorrect?");
		}

		/* processing time */
	
		t1=clock();
		memset(str,'\0',sizeof(str));
		n = sprintf(str,"session.proc_time = [session.proc_time %.3f];",((float) (t1-t0))/CLOCKS_PER_SEC);
		mexEvalString(str);
		mexEvalString("sessionPlots('Update Session Info');");
		
	    seekpos += NPTS;
	}
	if (Signalcnt > nSignal)
		Signalcnt = 0;

} while(seekpos < NPTS_totalplay);

do{}while (playseg(1)==BUF_A1);		/* wait for last 2 buffers to finish */
do{}while (playseg(1)==BUF_A2);



PA4mute(1);
PA4mute(2);

PD1stop(1);
PD1clrIO(1);
PD1clear(1);

mexEvalString("sessionPlots('Finish Session');");

trash();
dropall();

APunlock(0);
XBunlock(0);
S2close();

}
예제 #26
0
int main()
{
    hamming(93);
    div(12913,234);
}
예제 #27
0
파일: MatLab4.cpp 프로젝트: lonnell/trick
MatLab4::MatLab4(char * file_name , char * param_name , char * time_name ) {

        int len ;
        int temp ;
        int endian ;
        int mat_size ;
        int type , size ;
        int mat_type ;
        int my_byte_order ;
        div_t div_result ;
        int row , column , imaginary ;
        char * temp_ptr ;
        bool param_found , time_found ;
        int max_offset , offset = 0 ;

        fileName_ = file_name ;
        TRICK_GET_BYTE_ORDER(my_byte_order) ;

        if ((fp_ = fopen(file_name , "r")) == 0 ) {
           std::cerr << "ERROR:  Couldn't open \"" << file_name << "\": " << std::strerror(errno) << std::endl;
           exit(-1) ;
        }

        // we use fseek calls to move around so I need to know the max offset of the file
        fseek( fp_ , 0 , SEEK_END ) ;
        max_offset = ftell(fp_) ;
        rewind( fp_ ) ;

        // get field_num from param_name
        temp_ptr = rindex(param_name, '[') ;
        if ( temp_ptr != NULL ) {
                sscanf(&temp_ptr[1] , "%d" , &y_value_.field_num_ ) ;
        }
        else {
                y_value_.field_num_ = 0 ;
        }

        // get field_num from time_name
        temp_ptr = rindex(param_name, '[') ;
        if ( temp_ptr != NULL ) {
                sscanf(&temp_ptr[1] , "%d" , &time_value_.field_num_ ) ;
        }
        else {
                time_value_.field_num_ = 0 ;
        }

        param_found = time_found = false ;
        while ( (!param_found || !time_found) && (offset < max_offset)) {

                // read the type in
                fread( &temp , 4 , 1 , fp_ ) ;
                if ( ! strncmp( (char *)&temp , "MATL" , 4 )) {
                        fclose(fp_) ;
                        return ;
                }
                // byte swap it if it looks like we need to
                if ( temp & 0xFFFF0000 ) {
                        temp = trick_byteswap_int(temp) ;
                }

                div_result = div(temp , 1000) ;
                endian = div_result.quot ;
                temp = div_result.rem ;

                switch ( endian ) {
                        case 0:
                                swap_ = ( my_byte_order == TRICK_LITTLE_ENDIAN ) ? 0 : 1 ;
                                break ;
                        case 1:
                                swap_ = ( my_byte_order == TRICK_BIG_ENDIAN ) ? 0 : 1 ;
                                break ;
                        default:
                                fprintf(stderr,"Unknown endianness!\n") ;
                                fclose(fp_) ;
                                return ;
                                break ;
                }

                div_result = div( temp , 10 ) ;
                mat_size = div_result.quot ;
                mat_type = div_result.rem ;
                switch ( mat_size ) {
                        case 0:
                                type = TRICK_DOUBLE ;
                                size = 8 ;
                                break ;
                        case 1:
                                type = TRICK_FLOAT ;
                                size = 4 ;
                                break ;
                        case 2:
                                type = TRICK_INTEGER ;
                                size = 4 ;
                                break ;
                        case 3:
                                type = TRICK_SHORT ;
                                size = 2 ;
                                break ;
                        case 4:
                                type = TRICK_UNSIGNED_SHORT ;
                                size = 2 ;
                                break ;
                        case 5:
                                type = TRICK_CHARACTER ;
                                size = 1 ;
                                break ;
                }

                if ( mat_type != 0 ) {
                        fprintf(stderr,"Unknown matrix type!\n") ;
                        fclose(fp_) ;
                        return ;
                }

                fread( &row , 4 , 1 , fp_ ) ;
                if ( swap_ ) { row = trick_byteswap_int(row) ; }

                fread( &column , 4 , 1 , fp_ ) ;
                if ( swap_ ) { column = trick_byteswap_int(column) ; }

                fread( &imaginary , 4 , 1 , fp_ ) ;
                if ( swap_ ) { imaginary = trick_byteswap_int(imaginary) ; }

                fread( &len , 4 , 1 , fp_ ) ;
                if ( swap_ ) { len = trick_byteswap_int(len) ; }

                temp_ptr = new char[len +1] ;
                fread( temp_ptr , len , 1 , fp_ ) ;

                if ( ! strncmp( temp_ptr , param_name , len ) && y_value_.field_num_ < column ) {
                        y_value_.size_ = size ;
                        y_value_.type_ = type ;
                        y_value_.rows_ = row ;
                        y_value_.columns_ = column ;
                        y_value_.imaginary_ = imaginary ;
                        y_value_.data_offset_ = ftell(fp_) ;
                        param_found = true ;
                }
                if ( ! strncmp( temp_ptr , time_name , len ) && time_value_.field_num_ < column ) {
                        time_value_.size_ = size ;
                        time_value_.type_ = type ;
                        time_value_.rows_ = row ;
                        time_value_.columns_ = column ;
                        time_value_.imaginary_ = imaginary ;
                        time_value_.data_offset_ = ftell(fp_) ;
                        time_found = true ;
                }

                delete temp_ptr ;

                // skip to next parameter
                fseek( fp_ ,  row * column * size * ( 1 + imaginary ) , SEEK_CUR ) ;
                offset = ftell(fp_) ;
        }

        curr_row_ = 0 ;
}
예제 #28
0
  void cf_configuration::handle_config_cmd(char *cmd, const uint32_t &cmd_hash, char *arg,
      char *buf, const unsigned long &linenum)
  {
    char tmp[BUFFER_SIZE];
    int vec_count;
    char *vec[4];
    int port;
    std::vector<std::string> elts;
    std::string host, path, address, port_str;

    switch (cmd_hash)
      {
      case hash_domain_name_weight:
        _domain_name_weight = atof(arg);
        configuration_spec::html_table_row(_config_args,cmd,arg,
                                           "Weight given to the domain names in the simple filter");
        break;

      case hash_record_cache_timeout:
        _record_cache_timeout = atoi(arg);
        configuration_spec::html_table_row(_config_args,cmd,arg,
                                           "Timeout on cached remote records, in seconds");
        break;

      case hash_cf_peer:
        strlcpy(tmp,arg,sizeof(tmp));
        vec_count = miscutil::ssplit(tmp," \t",vec,SZ(vec),1,1);
        div_t divresult;
        divresult = div(vec_count,2);
        if (divresult.rem != 0)
          {
            errlog::log_error(LOG_LEVEL_ERROR,"Wrong number of parameter when specifying static collaborative filtering peer");
            break;
          }
        address = vec[0];
        urlmatch::parse_url_host_and_path(address,host,path);
        miscutil::tokenize(host,elts,":");
        port = -1;
        if (elts.size()>1)
          {
            host = elts.at(0);
            port = atoi(elts.at(1).c_str());
          }
        port_str = (port != -1) ? ":" + miscutil::to_string(port) : "";
        errlog::log_error(LOG_LEVEL_DEBUG,"adding peer %s%s%s with resource %s",
                          host.c_str(),port_str.c_str(),path.c_str(),vec[1]);
        _pl->add(host,port,path,std::string(vec[1]));
        configuration_spec::html_table_row(_config_args,cmd,arg,
                                           "Remote peer address for collaborative filtering");
        break;

      case hash_dead_peer_check:
        _dead_peer_check = atoi(arg);
        configuration_spec::html_table_row(_config_args,cmd,arg,
                                           "Interval of time between two dead peer checks");
        break;

      case hash_dead_peer_retries:
        _dead_peer_retries = atoi(arg);
        configuration_spec::html_table_row(_config_args,cmd,arg,
                                           "Number of retries before marking a peer as dead");
        break;

      case hash_post_url_check:
        _post_url_check = static_cast<bool>(atoi(arg));
        configuration_spec::html_table_row(_config_args,cmd,arg,
                                           "Whether to ping and check on posted URLs");
        break;

      case hash_post_radius:
        _post_radius = static_cast<bool>(atoi(arg));
        configuration_spec::html_table_row(_config_args,cmd,arg,
                                           "Query similarity impact radius of posted URLs");
        break;

      case hash_post_ua:
        _post_url_ua = std::string(arg);
        configuration_spec::html_table_row(_config_args,cmd,arg,
                                           "default 'user-agent' header used to retrieve posted URLs");
        break;

      case hash_stop_words_filtering:
        _stop_words_filtering = static_cast<bool>(atoi(arg));
        configuration_spec::html_table_row(_config_args,cmd,arg,
                                           "Whether to filter similar queries with stop words");
        break;

      default:
        break;
      }
  }
예제 #29
0
 T boundary(const line<T>& o) const {
     if (a == o.a) return b > o.b ? inf : -inf;
     return div(o.b - b, a - o.a);
 }
예제 #30
0
void
ideinit(void)
{
  memdisk = _binary_fs_img_start;
  disksize = div(((uint)_binary_fs_img_end - (uint)_binary_fs_img_start), 512);
}