Esempio n. 1
0
File: exec.c Progetto: asmodz/ganjax
uint8_t run_program(const char *__n){
    uint8_t rc;
    if((rc = load_file(__n, &file_handler)))
        return rc;
        
    if( file_handler.entry.file_size > MAX_BIN_SIZE )
        return EXEC_SIZE_TOO_BIG;
    
    puts_attrib("=================EXECUTOR=================", color_entry(COLOR_GREEN, COLOR_BLACK)); eol();
    load_bin(0, file_handler.entry.file_size);
    return_code = (int)(*raw_bin)();
    eol();
    puts_attrib("=================EXECUTOR=================", color_entry(COLOR_RED, COLOR_BLACK));
    eol(); 
    puts_attrib("RC:", color_entry(COLOR_MAGENTA, COLOR_BLACK)); print_int(return_code, 10, 0);eol();
    puts_attrib("=================EXECUTOR=================", color_entry(COLOR_GREEN, COLOR_BLACK));
    free_file();
    return EXEC_OP_OK;
}
Esempio n. 2
0
int main(int argc, char **argv)
{
	int c;

	while((c = getopt(argc, argv, "s:")) != -1) {
		switch(c) {
			case 's':

			break;
			default:
				abort();
		}
	}

	if(optind >= argc) {
		fprintf(stderr, "Usage: %s [opts] <bin>\n", argv[0]);
		return 1;
	}

	srand(time(NULL));

	load_bin(argv[optind]);

	print_data();
	print_code();

	cpu = malloc(sizeof(VM_CPU));
	
	int i;

	for(i = optind + 1; i < argc; i++) {
		cpu->registers[ARG_REG(i)] = (int)argv[i];	
	}
	
	cpu->stack_size = bin_hdr->stack_size;
	cpu->stack = malloc(sizeof(int) * cpu->stack_size);
	cpu->registers[RESERVED_REG(REG_STACKP)] = cpu->stack_size;
	
	cpu->registers[RESERVED_REG(REG_IP)] = bin_hdr->entry_point;
	print_dbg("Set IP: %d\n", cpu->registers[RESERVED_REG(REG_IP)]);
	cpu->running = 1;
	cycle();
}
Esempio n. 3
0
int load(char *path, long offset) {
    // check for reboot/poweroff
    if (strcasecmp(path, "reboot") == 0) {
        reboot();
    } else if (strcasecmp(path, "shutdown") == 0) {
        poweroff();
    } else {
        const char *ext = get_filename_ext(path);
        if (strcasecmp(ext, "bin") == 0
            || strcasecmp(ext, "dat") == 0) {
            return load_bin(path, offset);
        } else if (strcasecmp(ext, "3dsx") == 0) {
            return load_3dsx(path);
        } else {
            debug("Invalid file: %s\n", path);
            return -1;
        }
    }
    return 0;
}
Esempio n. 4
0
static void
cmd_load(int argc, char **argp, void *data) {
    cpu_instance_t *cpu = ((cmd_data_t *)data)->cpu;
    int words;
    FILE *f;
    int offset = 0;

    if (argc <= 1 || argc > 3) {
        lprintf(LOG_ERROR,
                "Invalid number of parameters for 'load'.\n");
        return;
    }

    f = fopen(argp[1], "r");
    if (f == NULL) {
        lprintf(LOG_ERROR,
                "Failed to input open file: %s\n",
                strerror(errno));
        return;
    }

    if (argc >= 3)
        offset = atoi(argp[2]);

    words = load_bin(f, offset, cpu->core, CPU_CORE_SIZE);
    if (words == -1) {
        lprintf(LOG_ERROR,
                "Failed to load RIM-file...\n"
                "Core might be dirty.\n");
        fclose(f);
        return;
    }

    lprintf(LOG_NORMAL,
            "Loaded %i words from '%s'.\n",
            words, argp[1]);

    fclose(f);
}
Esempio n. 5
0
int main(void)
 {
    char c;
    unsigned char idx[4] = {0, 0, 0, 0};
    unsigned char port, total_ports = 2, valid_ports = 0x3;
    volatile unsigned long i, j;
    int ret = 0;
    u32union delay;

    RCONbits.SWDTEN = 0;

    /* 70 MIPS; 140MHz */
    CLKDIVbits.PLLPRE = 0;
    PLLFBDbits.PLLDIV = 74;
    CLKDIVbits.PLLPOST = 0;

    /* switch clock to FRC oscillator with PLL */
    __builtin_write_OSCCONH(1);
    __builtin_write_OSCCONL(OSCCON | 1);

    /* wait for clock switch to complete */
    while (OSCCONbits.OSWEN == 1);
    /* wait for PLL lock */
    while (OSCCONbits.LOCK != 1);

    ANSELA = 0;
    ANSELB = 0;
    ANSELC = 0;

    TRIS_LED = 0;
    LED = 0;

    /* detect hw revision */
    /* set RB1 internal pull down */
    _TRISB1 = 1;
    _CNPDB1 = 1;
    
    /* hw 0v5 has RB1 connected to RB4 */
    _TRISB4 = 0;
    _LATB4 = 0;
    for (i = 0; i < 100000; i++);
    j = (_RB1 & 1);
    _LATB4 = 1;
    for (i = 0; i < 100000; i++);
    j |= ((_RB1 & 1) << 1);
    
    if (j == 0b10) {
        hw_rev = 0x05;
    } else {
        /* set RB9 internal pull down */
        _TRISB9 = 1;
        _CNPDB9 = 1;

        /* set RA9 internal pull down */
        _TRISA9 = 1;
        _CNPDA9 = 1;

        ANSELBbits.ANSB1 = 1;
        AD1CON3bits.ADCS = 16;
        AD1CON2bits.CHPS = 2;
        AD1CON1bits.ADON = 1;
        AD1CHS0bits.CH0SA = 3;
        AD1CON1bits.SAMP = 1;
        for (i = 0; i < 1000; i++);
        AD1CON1bits.SAMP = 0;
        for (i = 0; i < 10000; i++);

        if (ADC1BUF0 > 400)
            /* hw 0v4 has 1.25V vref on AN3 */
            hw_rev = 0x04;
        else if (_RB9 == 1)
            /* hw 0v3 has external pull-up on RB9 */
            hw_rev = 0x03;
        else if (_RA9 == 1)
            /* hw 0v2 has RB9 floating and RA9 pull-up */
            hw_rev = 0x02;
        else
            /* hw 0v1 has RA9 and RB9 floating */
            hw_rev = 0x01;
        _CNPDB9 = 0;
        _CNPDA9 = 0;
        AD1CON1bits.ADON = 0;
    }
    _CNPDB1 = 0;
    _TRISB4 = 1;
    
    /* weak pull up on serial port rx pins */
    if (hw_rev >= 0x05) {
        _CNPUB12 = 1;
        _CNPUB15 = 1;
        _CNPUC7 = 1;
        _CNPUB7 = 1;
    } else if (hw_rev >= 0x03) {
        _CNPUB11 = 1;
        _CNPUB6 = 1;
        _CNPUB2 = 1;
        _CNPUB13 = 1;
    } else {
        _CNPUB6 = 1;
        _CNPUA4 = 1;
    }

    if (hw_rev >= 0x03) {
        total_ports = 4;
        valid_ports = 0xf;
    }
    
    /* get devid */
    read_flash(0xff0000, &devid);
    
    delay.l = BOOT_DELAY;

    if (delay.b[0] == 0)
        goto_usercode();

    /* Timer setup */
    /* increments every instruction cycle */
    T2CONbits.T32 = 1;
    /* clear timer3 IF */
    IFS0bits.T3IF = 0;
    /* disable timer3 isr */
    IEC0bits.T3IE = 0; 
    /* Convert seconds into timer count value */
    delay.l = ((unsigned long) (FCY)) * ((unsigned long) (delay.b[0]));
    PR3 = delay.w[1];
    PR2 = delay.w[0];
    TMR3HLD = 0x0000;
    TMR2 = 0x0000;
    T2CONbits.TON = 1;

    uart_init();

    while (1) {
        for (port = 0; port < total_ports; port++) {
            if (valid_ports & (1 << port)) {
                used_port = port;
                if (get_char(&c)) {
                    if (c != magic_word_bin[idx[port]])
                        valid_ports &= ~(1 << port);
                    else
                        idx[port]++;

                    if (idx[port] == (sizeof(magic_word_bin)-1)) {
                        ret = 1;
                        break;
                    }
                }
            }
        }

        if (valid_ports == 0)
            ret = 0xff;
        if (_T3IF == 1) {
            ret = 0xff;
        }
        if (ret)
            break;
    }
    T2CONbits.TON = 0;

    LED = 1;
    
    if (ret == 0xff) {
        put_char('*');
        goto_usercode();
    }
    
    put_str((char*) msg);
    put_str((char*) msg_bin);
    load_bin();
    return 0;
}
Esempio n. 6
0
int ClientProc::ReadProblem(parameter_t *param) {


    snprintf(lblname, 1024, "%s.label", param->data);
    snprintf(cntname, 1024, "%s.rowcnt", param->data);
    snprintf(valname, 1024, "%s.value", param->data);
    snprintf(idxname, 1024, "%s.colidx", param->data);
    snprintf(sizename, 1024, "%s.size", param->data);

    _Y = NULL;
    _val = NULL;
    _cnt = NULL;
    _idx = NULL;

    /**
     * get the total #samples
     */
    struct stat file_stat;
    ASSERT(!stat(lblname, &file_stat), "stat %s failed", lblname);

    size_t global_n = file_stat.st_size/sizeof(double);
    if (param->n == 0 || param->n > global_n) {
        param->n = global_n;
    }

    /**
     * check whether there is xxx.size
     */
    _p = 0;
    ix_t tmp_n;
    if (!stat(sizename, &file_stat)) {
        FILE *fd = fopen(sizename, "r");
        ASSERT(fd!=NULL, "fopen failed");
        ASSERT(fscanf(fd, "%u %u", &tmp_n, &_p)==2, "read %s error", sizename);
        fclose(fd);
        ASSERT(tmp_n == (ix_t)global_n, "%s didn't match %s", sizename, lblname);
    }

    /**
     * each node read a part of rows
     */
    size_t *row_os = linspace((size_t)0, param->n, _rank_size);
    size_t start = row_os[_my_rank];
    size_t n = row_os[_my_rank+1] - start;

    /**
     * first check whether there is a cache
     */
    int hit_cache = 0;
    if (param->cache_data != NULL) {
        snprintf(mapname, 1024, "%s.map.%d", param->cache_data, _my_rank);
        char tmpname[1024];
        snprintf(tmpname, 1024, "%s.label.%d", param->cache_data, _my_rank);
        if (!stat(tmpname, &file_stat)) {
            size_t nlbl = file_stat.st_size/sizeof(double);
            if (nlbl == (size_t)n) {
                hit_cache = 1;
                start = 0;
                snprintf(lblname, 1024, "%s.label.%d", param->cache_data, _my_rank);
                snprintf(cntname, 1024, "%s.rowcnt.%d", param->cache_data, _my_rank);
                snprintf(valname, 1024, "%s.value.%d", param->cache_data, _my_rank);
                snprintf(idxname, 1024, "%s.colidx.%d", param->cache_data, _my_rank);
                NOTICE("C[%d], hit training data cache", _my_rank);
            }
        }
    }

// #ifdef _DEBUG_
//     NOTICE("r [%d], row [%lu]->[%lu], entry [%lu]->[%lu]",
//            _my_rank, start, start+n, _cnt[0], _cnt[n]);
// #endif

    /**
     * read
     */
    ASSERT(load_bin(lblname, &_Y, start, n)>0, "load Y failed");
    ASSERT(load_bin(cntname, &_cnt, start, n+1)>0, "load cnt failed");

    uint64_t nnz = _cnt[n] - _cnt[0];
    if (!hit_cache) {
        start = _cnt[0];
    }
    ASSERT(load_bin(idxname, &_idx, start, nnz)>0, "load idx failed");

    _is_binary_feature = 1;
    if (!stat(valname, &file_stat)) {
        ASSERT(load_bin(valname, &_val, start, nnz)>0, "load val failed");
        /**
         * check whether it is binary feature
         */
        for (size_t i = 0; i < nnz; i++)
            if (_val[i] != 1) {
                _is_binary_feature = 0;
                break;
            }
        if (_is_binary_feature)
            DELETE(_val);
    }

    if (_is_binary_feature && !_my_rank) {
        NOTICE("we have binary features");
    }

    /**
     * get #samples, #features
     */
    _n = (uint32_t) n;
    if (_p == 0) {
        ix_t tmp = 0;
        for (size_t i = 0; i < nnz; i++) {
            tmp = max(tmp, _idx[i]);
        }
        ++ tmp;

        ASSERT(!MPI_Allreduce(&tmp, &_p, 1, MPI_UNSIGNED, MPI_MAX, MPI_COMM_WORLD),
               "mpi allreaduce failed");
        if (_my_rank == 0) {
            NOTICE("#samples [%lu], #features [%u] (by scanning data), #nodes [%d]", param->n, _p, _rank_size);
        }

    } else {
        if (_my_rank == 0) {
            NOTICE("#samples [%lu], #features [%u] (by reading .size), #nodes [%d]", param->n, _p, _rank_size);
        }
    }

    /**
     * store caches
     */
    if (param->cache_data != NULL && !hit_cache) {
        snprintf(lblname, 1024, "%s.label.%d", param->cache_data, _my_rank);
        snprintf(cntname, 1024, "%s.rowcnt.%d", param->cache_data, _my_rank);
        snprintf(valname, 1024, "%s.value.%d", param->cache_data, _my_rank);
        snprintf(idxname, 1024, "%s.colidx.%d", param->cache_data, _my_rank);

        ASSERT(save_bin(lblname, _Y, n)>0, "save cache Y failed");
        ASSERT(save_bin(cntname, _cnt, n+1)>0, "save cache cnt failed");
        ASSERT(save_bin(idxname, _idx, nnz)>0, "save cache idx failed");

        if (!_is_binary_feature) {
            ASSERT(save_bin(valname, _val, nnz)>0, "save cache val failed");
        }
        NOTICE("C[%d], save data cache in %s", _my_rank, param->cache_data);
    }

    /**
     * minus the offset
     */
    os_t os = _cnt[0];
    for (ix_t i = 0; i <= _n; i++)
        _cnt[i] -= os;


    /**
     * whether a feature exists in this rank
     */

    ASSERT(bitmap_new(_p, &_fea_map)==0);
    if (hit_cache) {
        if (!stat(mapname, &file_stat)) {
            size_t nmap = file_stat.st_size/sizeof(bitmap_t);
            if (nmap == (size_t)bitmap_size(_fea_map)) {
                NOTICE("C[%d] hit bitmap", _my_rank);
                ASSERT(load_bin(mapname, &_fea_map)>0);
                return 0;
            }
        }
    }

    for (size_t i = 0; i < nnz; i++) {
        ix_t j = _idx[i];
        ASSERT(j < _p, "too large idx [%u], while _p [%u]", j, _p);
        if (!bitmap_test(j, _fea_map))
            bitmap_set(j, _fea_map);
    }

    if (param->cache_data != NULL) {
        ASSERT(save_bin(mapname, _fea_map, bitmap_size(_fea_map))>0);
    }

    return 0;
}
Esempio n. 7
0
int main(int argc, const char *argv[])
{
    ez::ezOptionParser opt;

    opt.overview = "GenEmu -- Sega Genesis Emulator";
    opt.syntax = "genemu [OPTIONS] rom";
    opt.add("",0,0,0,"Display usage instructions.", "-h", "--help");
    opt.add("",0,-1,',',"Apply Game Genie codes [format=ABCD-EFGH]", "--gamegenie", "--gg");
    opt.add("",0,1,0,"Force console type [accepted values: PAL or NTSC]", "--mode", "--type");
    opt.add("",0,-1,',',"Make screenshots on the specified frames and exit", "--screenshots");
    opt.add("",0,1,0,"Load from saved state", "--load");

    opt.parse(argc, argv);
    if (opt.isSet("-h"))
    {
        std::string usage;
        opt.getUsage(usage, 120);
        std::cout << usage;
        return 0;
    }
    std::vector<std::string*> args;
    if (opt.firstArgs.size() >= 2)
    {
        strcpy(romname, opt.firstArgs[1]->c_str());
    }
    else if (opt.lastArgs.size() >= 1)
        strcpy(romname, opt.lastArgs[0]->c_str());
    else
    {
        std::cerr << "ERROR: no ROM specified\n";
        return 2;
    }

    int romsize;
    if (strstr(romname, ".smd"))
        romsize = load_smd(romname);
    else
        romsize = load_bin(romname);
    mem_init(romsize);

#if 0
    uint16_t checksum = 0;
    for (int i=0;i<(romsize-512)/2;i++)
        checksum += m68k_read_memory_16(512+i*2);
    assert(checksum == m68k_read_memory_16(0x18e));
#endif

#if 1
    char buf[256];
    int pc = 0;
    strcpy(buf, argv[1]);
    strcat(buf, ".asm");
    FILE *f = fopen(buf, "w");
    while (pc < romsize) {
        int oplen = m68k_disassemble(buf, pc, M68K_CPU_TYPE_68000);
        fprintf(f, "%06x\t%s\n", pc, buf);
        pc += oplen;
    }
    fclose(f);
#endif

    if (opt.isSet("--mode"))
    {
        std::string mode;
        opt.get("--mode")->getString(mode);
        if (mode == "PAL")
        {
            VERSION_PAL = 1;
            std::cerr << "Forced mode: PAL\n";
        }
        else if (mode == "NTSC")
        {
            VERSION_PAL = 0;
            std::cerr << "Forced mode: NTSC\n";
        }
        else
        {
            std::cerr << "ERROR: invalid mode: " << mode << std::endl;
            return 2;
        }
    }

    std::vector<int> ss_frames;
    int ss_idx = 0;

    hw_init(YM2612_FREQ, VERSION_PAL ? 50 : 60);

    if (!opt.isSet("--screenshots"))
    {
        hw_enable_video(true);
        hw_enable_audio(true);
        gfx_enable(true);
    }
    else
    {
        opt.get("--screenshots")->getInts(ss_frames);
    }

    CPU_M68K.init();
    CPU_Z80.init();

    MASTER_CLOCK = 0;
    CPU_M68K.reset();
    VDP.reset();

    if (opt.isSet("--load"))
    {
        std::string sn;
        opt.get("--load")->getString(sn);
        loadstate(sn.c_str());
    }

    while (hw_poll())
    {
        if (ss_idx < ss_frames.size() && framecounter == ss_frames[ss_idx])
        {
            gfx_enable(true);
        }

        int numscanlines = VDP.num_scanlines();

        uint8_t *screen;
        int pitch;
        hw_beginframe(&screen, &pitch);

        int16_t *audio; int nsamples;
        hw_beginaudio(&audio, &nsamples);
        int audio_index = 0;
        int audio_step = (nsamples << 16) / numscanlines;

        for (int sl=0;sl<numscanlines;++sl)
        {
            CPU_M68K.run(MASTER_CLOCK + VDP_CYCLES_PER_LINE);
            CPU_Z80 .run(MASTER_CLOCK + VDP_CYCLES_PER_LINE);

            vdp_scanline(screen);
            screen += pitch;

            int prev_index = audio_index;
            audio_index += audio_step;
            YM2612Update(audio + ((prev_index+0x8000)>>16)*2, (audio_index-prev_index+0x8000)>>16);

            MASTER_CLOCK += VDP_CYCLES_PER_LINE;
        }

        hw_endaudio();
        hw_endframe();

        if (framecounter == 100 && opt.isSet("--gamegenie"))
        {
            std::vector<std::string> codes;
            opt.get("--gamegenie")->getStrings(codes);
            for (int i=0;i<codes.size();++i)
                mem_apply_gamegenie(codes[i].c_str());
        }

        if (ss_idx < ss_frames.size() && framecounter == ss_frames[ss_idx])
        {
            static char ssname[2048];
            sprintf(ssname, "%s.%d.%s.bmp", romname, framecounter, (VERSION_PAL ? "PAL" : "NTSC"));
            std::cerr << "Saving screenshot " << ssname << std::endl;
            hw_save_screenshot(ssname);

            sprintf(ssname, "%s.%d.%s.gs", romname, framecounter, (VERSION_PAL ? "PAL" : "NTSC"));
            savestate(ssname);

            ++ss_idx;
            if (ss_idx == ss_frames.size())
                break;
        }

        ++framecounter;
        state_poll();
    }

#if 0
    checksum = 0;
    for (int i=0;i<(romsize-512)/2;i++)
        checksum += m68k_read_memory_16(512+i*2);
    assert(checksum == m68k_read_memory_16(0x18e));
#endif

#if 0
    {
    char buf[256];
    int pc = 0xffffee00;
    FILE *f = fopen(buf, "w");
    while (pc <= 0xffffef00) {
        int oplen = m68k_disassemble(buf, pc, M68K_CPU_TYPE_68000);
        fprintf(stdout, "%06x\t%s\n", pc, buf);
        pc += oplen;
    }
    fclose(f);
    }
#endif

    return 0;
}
Esempio n. 8
0
int main (){

  struct func_table_el *main;
  struct band_list_el *head;
  int pos;
  

  /* init main  */
  /*  main = &glbft->funcs[MAIN_FUNC]; */
 
  /* sorry guys, I just ignored ugly parsing work, so things ended with 
     main funcs(program) local variables which are also programs global variables gatehered as members of global object, so we have to give referense to it from main
  */
  /*  main->dt.count = 0; */

  init_stek();

  /* push main func to fnstk  */
  /*  push_to_stek(&fnstk, main);*/  

  


  /* clear input bufer */
  flush_input_bufer();

  /* build execution band  */
  /*build_exec_band(tree->first->next, exec_band, &band_size);  */
  load_bin("prg.esr_bin", exec_band, &band_size);
  //exit(0);
   // print_exec_band(exec_band, band_size);
   // exit(0);

  /* init glb tips area  */
    glbmt = (struct var_table *)malloc(sizeof(struct var_table));
    glbmt->area = (unsigned char *)malloc(exec_band[0].dt_size);
     /* we saved start adrs [0].head_pos during band build  */
    prg_start = exec_band[0].head_pos;
    push_to_stek(&obstk, glbmt->area);

  // printf("returning from execution.\n");
  //     return;

  head = exec_band + prg_start;

 begin:
 loop:
  //  printf("hpos -> %d\t executing \t%d\n", (int)(head - exec_band));
  pos = pre_exec_new(head);

  //  printf("\t %d moved head to \t%d\n", pos);

  if (pos)
    head = exec_band + pos;
  else
    head++;

    /*    head++;*/

    /*    printf("%p\n%p\n%p\n",head, exec_band + band_size, &exec_band[band_size]);*/

    if (head >= exec_band + band_size)
      goto exit; /* end of program, exit  */

    goto loop;

 exit:
    exit(0);

}
Esempio n. 9
0
main(int argc, char**argv) {
	lgopen(argc,argv);
	char *fname_inerr[5];
	int nscores=0;
	int nweights=0;
	double weights[100];
	char *fname_qualify=NULL;
	int nloops=10000;
	int copt=1;
	int i;
	for(i=1;i<argc;i++) {
		int rc=score_argv(argv+i);
		if(rc>0) {
			i+=rc-1;
			continue;
		}
		if(!strcmp(argv[i],"-le"))
			fname_inerr[nscores++]=argv[++i];
		else if(!strcmp(argv[i],"-lew"))
			weights[nweights++]=atof(argv[++i]);
		else if(!strcmp(argv[i],"-se"))
			fname_outerr=argv[++i];
		else if(!strcmp(argv[i],"-sq"))
			fname_qualify=argv[++i];
		else if(!strcmp(argv[i],"-l"))
			nloops=atoi(argv[++i]);
		else if(!strcmp(argv[i],"-c"))
			copt^=1;
		else if(!strcmp(argv[i],"-a"))
			aopt=1;
		else if(!strcmp(argv[i],"-lm"))
			load_model=1;
		else if(!strcmp(argv[i],"-sm"))
			save_model=1;
		else {
			lg("Unrecognized argument %d %s ?\n",i,argv[i]);
			lg("-le <fname> - load precomputed error file.\n");
			lg("-lew <weight> - In case of several -le, use wrights, instead of fit\n");
			lg("-se <fname> - store resulted error file.\n");
			lg("-l <n> - number of training loops to perform\n");
			lg("-a - Perform training also on probe data\n");
			lg("-c - Dont clip scores to be between 0...4\n");
			lg("-sq <fname> - write qualifying submission to file.\n");
			lg("-lm - load precomputed model.\n");
			lg("-sm - save computed model.\n");
			exit(0);
		}
	}
	if(fname_qualify && !aopt)
		lg("WARNING: -sq without -a\n");
	if(fname_qualify && !copt)
		lg("WARNING: -sq with -c\n");
	if(nweights && nscores && nweights!=nscores)
		lg("Number of weights %d (-lew) does not match number of files %d (-le)\n",nweights,nscores);
	
	load_bin(useridx_path,useridx,sizeof(useridx));
	{
		int count[4],u,k;
		ZERO(count);
		for(u=0;u<NUSERS;u++)
			for(k=1;k<4;k++)
				count[k]+=useridx[u][k];
		lg("Train=%d Probe=%d Qualify=%d\n",count[1],count[2],count[3]);
	}	
	load_bin(userent_path,userent,sizeof(userent));
	if(nscores) {
		if(nscores==1)
			load_bin(fname_inerr[0],err,sizeof(err));
		else if(nweights)
			loadmix(fname_inerr,nscores,weights);
		else
			loadmix(fname_inerr,nscores,NULL);
	} else {
		int i;
		for(i=0;i<NENTRIES;i++)
			err[i]=(userent[i]>>USER_LMOVIEMASK)&7;
		globalavg();
	}
	if(copt) cliperr();
	rmse_print(copt);
	
	// if(nloops)
	{
		score_setup();
		if(copt) cliperr();
		rmse_print(copt);
	}
	
	int loop;
	int rc=1;
	for(loop=0;loop<nloops;loop++) {
		lg("Loop %d\n",loop);
		clock_t t0=clock();
		if(!score_train(loop))
			break;
		lg("%f sec\n",(clock()-t0)/((double)CLOCKS_PER_SEC));
		if(copt && !dontclip) cliperr();
		dontclip=0;
		rmse_print(copt);
	}

	if(fname_outerr) dump_bin(fname_outerr,err,sizeof(err));

	if(fname_qualify) {
		FILE *fp=fopen(fname_qualify,"w");
		char *qualify_path="data/qualify.bin";
		unsigned int *qualify=malloc(NQUALIFY_SIZE*4);
		load_bin(qualify_path,qualify,NQUALIFY_SIZE*4);
		unsigned int *q=qualify;
		while (q<(qualify+NQUALIFY_SIZE)) {
			int m=*q++;
			fprintf(fp,"%d:\n",m+1);
			int l=*q++;
			int j;
			for(j=0;j<l;j++) {
				int u=*q++;
				int base2=useridx[u][0]+useridx[u][1]+useridx[u][2];
				int d2=+useridx[u][3];
				int k;
				for(k=0;k<d2;k++) {
					if((userent[base2+k]&USER_MOVIEMASK) == m)
						break;
					//lg("%d\n",userent[base2+k]&USER_MOVIEMASK);
				}
				if(k==d2) error("Bad qualify %d %d\n",m,u);
				fprintf(fp,"%.1f\n",8.-err[base2+k]);
			}
		}
		fclose(fp);
	}
}