uilogic.c 34.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
#include "viewer.h"
#include "uilogic.h"
#include "status.h"
#include "gameticket.h"
#include "pagetop.h"
#include "pagegpak.h"
#include "pagecpak.h"
#include "pagecontrol.h"
#include "date.h"
#include "bbreg.h"
#include "gtime.h"

#ifdef _PARTNER
#include "texture/icon.h"
#include "texture/icon1.h"
#include "texture/icon2.h"
#include "texture/icon3.h"
#else
#include "os_bb.h"
#endif

extern s32 __osBbInsertSig(const char *name, BbEccSig sig, u8 block[BB_FL_BLOCK_SIZE]);
extern s32 __osBbLookupSig(const char *name, BbEccSig sig, u8 block[BB_FL_BLOCK_SIZE]);
extern s32 __osBbDeleteSig(const char *name, u8 block[BB_FL_BLOCK_SIZE]);
extern int __osBbIsSigDirty(const char *name, u8 block[BB_FL_BLOCK_SIZE]);
extern void __osBbFsFormatName(char fname[BB_INODE16_NAMELEN], const char* name);

int    gPersonalizeCnt;
int    gPersonalizeTotal;

BbTicket             gTicket  __attribute__ ((aligned (16)));
OSBbSaGameMetaData   gGameMeta  __attribute__ ((aligned (16)));

#ifndef _PARTNER
#define STA_SUFFIX   ".sta"
#define VW_HEAP_SIZE 64*1024
static OSBbFs gFs;
static u8     gSerialHeap[VW_HEAP_SIZE] __attribute__ ((aligned (16)));
static u8     gShuffleHeap[RECRYPT_CHUNK_SIZE] __attribute__ ((aligned (16)));
static u8     gBlockBuf[BB_FL_BLOCK_SIZE] __attribute__ ((aligned (16)));
#endif

static int days_in_month[2][13] = {
           {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
           {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
};

int uiSetPCLimit();

s32 sberrCorrect(char stateName[] /* 8.3 <cid>.sta */)
{
    s32 fd;
    u32 addr;
    int i;

    addr = IO_READ(PI_ERROR_REG);
    PRINTF("PI_ERROR_REG = %08x\n",addr);
    if(! ((addr & PI_ERROR_CORRECTABLE_ECC) && 
         !(addr & PI_ERROR_UNCORRECTABLE_ECC))) return 0;

    addr &= PI_ERROR_ADDR_MASK;
    addr -= osBbAtbGetVAddr();

    for(i=0; i<8 && stateName[i]!='.'; i++);
    stateName[i+1]='r';
    stateName[i+2]='e';
    stateName[i+3]='c';
    stateName[i+4]='\n';
    PRINTF("Fname: %s\n",stateName);
    if( (fd = osBbFOpen(stateName,"r")) < 0){
        stateName[i+1]='a';
        stateName[i+2]='p';
        stateName[i+3]='p';
        PRINTF("Fname: %s\n",stateName);
        if( (fd = osBbFOpen(stateName,"r")) < 0){
            return -1;
        }
    }
    PRINTF("Trying osBbFRepairBlock()\n");
    return osBbFRepairBlock(fd,addr&(~(BB_FL_BLOCK_SIZE-1)),gShuffleHeap,
                            BB_FL_BLOCK_SIZE);
}

int uiBbidCheck(void)
{
    char ftmp[] = "temp.tmp";
    char idsys[] = "id.sys";
#ifdef _PARTNER
    gBBID = 1234567890;
    return VW_OK;
#else
    int ret = 0; 
    s32 ifd;

    if ((ret = skGetId(&gBBID)) < 0) {;
        PRINTF("ERROR skGetId %d\n", ret);
        ret = VW_ERR_FATAL;
        goto exit;
    }
    PRINTF("gBBID=%d\n", gBBID);

    if(osBbFInit(&gFs)<0){
        PRINTF("ERROR osBbFInit()\n");
        ret = VW_ERR_FS;
        goto exit;
    }
    PRINTF("FS init done\n");

    bzero(gSerialHeap, sizeof(gSerialHeap));
#ifdef _BBID_GUARD
    ifd = osBbFOpen(idsys, "r");
    if (ifd>=0) {
        if (osBbFRead(ifd, 0, gSerialHeap, 16*1024)<0) {
            osBbFClose(ifd);
            ret = VW_ERR_FS;
        } else {
            gCardID = *((u32*)gSerialHeap);
            PRINTF("gCardID=%d\n", gCardID);
            osBbFClose(ifd);
            if (gBBID!=gCardID) 
                ret = VW_ERR_ID_MISMATCH;
        }
    } 
    else if (ifd==BBFS_ERR_ENTRY) {
#endif
        bcopy(&gBBID, gSerialHeap, 4);
        osBbFDelete(ftmp);
        osBbFCreate(ftmp, 1, 16*1024);
        if ((ifd = osBbFOpen(ftmp, "w"))<0) {
            PRINTF("temp.tmp creation failed\n", ifd);
            ret = VW_ERR_FS;
        } else {
            if(osBbFWrite(ifd, 0, gSerialHeap, 16*1024)<0){
                PRINTF("failed to write bbid\n");
                osBbFClose(ifd);
                osBbFDelete(ftmp);
                ret = VW_ERR_FS;
            }
            osBbFClose(ifd);
            osBbFRename(ftmp, idsys);
        }
#ifdef _BBID_GUARD
    } else {
        PRINTF("id.sys open failed: %d\n", ifd);
        ret = VW_ERR_FS;
    } 
#endif

exit: 
    return ret;
#endif
}

int uiParseTickets(void)
{
    int ret = 0;
    s32 ifd;
#ifdef _PARTNER
    int i; 
    gpTickets->numTickets = 10;
    for (i=0; i<gpTickets->numTickets; i++)
        gpTickets->ticket[i].cmd.head.id = 1234 + i;
    gpGameMeta[0].thumb_len = *((u16*)texIcon);
    gpGameMeta[0].thumb_data = (u8*)((u8*)texIcon + 2);
    gpGameMeta[0].title = (u8*)((u8*)texIcon + 2 + gpGameMeta[0].thumb_len);
    gpGameMeta[0].size = 8*1024*1024;
    gpGameMeta[0].type = 1;
    gpGameMeta[1].thumb_len = *((u16*)texIcon3);
    gpGameMeta[1].thumb_data = (u8*)((u8*)texIcon3 + 2);
    gpGameMeta[1].title = (u8*)((u8*)texIcon3 + 2 + gpGameMeta[1].thumb_len);
    gpGameMeta[1].size = 32*1024*1024;
    gpGameMeta[1].type = 2;
    gpGameMeta[1].code = BB_LIMIT_CODE_TIME;
    gpGameMeta[1].limit = 10;
    gpGameMeta[1].cc = 5;
    gpGameMeta[2].thumb_len = *((u16*)texIcon2);
    gpGameMeta[2].thumb_data = (u8*)((u8*)texIcon2 + 2);
    gpGameMeta[2].title = (u8*)((u8*)texIcon2 + 2 + gpGameMeta[2].thumb_len);
    gpGameMeta[2].size = 12*1024*1024;
    gpGameMeta[2].type = 3;
    gpGameMeta[2].code = BB_LIMIT_CODE_COUNT;
    gpGameMeta[2].limit = 2;
    gpGameMeta[2].cc = 1;
    gpGameMeta[3].thumb_len = *((u16*)texIcon1);
    gpGameMeta[3].thumb_data = (u8*)((u8*)texIcon1 + 2);
    gpGameMeta[3].title = (u8*)((u8*)texIcon1 + 2 + gpGameMeta[3].thumb_len);
    gpGameMeta[3].size = 8*1024*1024;
    gpGameMeta[3].type = 0;
    gpGameMeta[4].thumb_len = *((u16*)texIcon3);
    gpGameMeta[4].thumb_data = (u8*)((u8*)texIcon3 + 2);
    gpGameMeta[4].title = (u8*)((u8*)texIcon3 + 2 + gpGameMeta[4].thumb_len);
    gpGameMeta[4].size = 32*1024*1024;
    gpGameMeta[4].type = 1;
    gpGameMeta[5].thumb_len = *((u16*)texIcon);
    gpGameMeta[5].thumb_data = (u8*)((u8*)texIcon + 2);
    gpGameMeta[5].title = (u8*)((u8*)texIcon + 2 + gpGameMeta[5].thumb_len);
    gpGameMeta[5].size = 8*1024*1024;
    gpGameMeta[5].type = 1;
    gpGameMeta[6].thumb_len = *((u16*)texIcon2);
    gpGameMeta[6].thumb_data = (u8*)((u8*)texIcon2 + 2);
    gpGameMeta[6].title = (u8*)((u8*)texIcon2 + 2 + gpGameMeta[6].thumb_len);
    gpGameMeta[6].size = 12*1024*1024;
    gpGameMeta[6].type = 1;
    gpGameMeta[7].thumb_len = *((u16*)texIcon1);
    gpGameMeta[7].thumb_data = (u8*)((u8*)texIcon1 + 2);
    gpGameMeta[7].title = (u8*)((u8*)texIcon1 + 2 + gpGameMeta[7].thumb_len);
    gpGameMeta[7].size = 12*1024*1024;
    gpGameMeta[7].type = 2;
    gpGameMeta[7].code = BB_LIMIT_CODE_TIME;
    gpGameMeta[7].limit = 10;
    gpGameMeta[7].cc = 10;
    gpGameMeta[8].thumb_len = *((u16*)texIcon2);
    gpGameMeta[8].thumb_data = (u8*)((u8*)texIcon2 + 2);
    gpGameMeta[8].title = (u8*)((u8*)texIcon2 + 2 + gpGameMeta[8].thumb_len);
    gpGameMeta[8].size = 12*1024*1024;
    gpGameMeta[8].type = 0;
    gpGameMeta[9].thumb_len = *((u16*)texIcon);
    gpGameMeta[9].thumb_data = (u8*)((u8*)texIcon + 2);
    gpGameMeta[9].title = (u8*)((u8*)texIcon + 2 + gpGameMeta[9].thumb_len);
    gpGameMeta[9].size = 8*1024*1024;
    gpGameMeta[9].type = 1;
#else
    bzero(gpTickets, sizeof(OSBbSaTickets));
    ret = osBbSaMetaCleanTickets(gpTickets);

    if (!ret) {
        PRINTF("numTickets=%d\n", gpTickets->numTickets);
        bzero(gpGameMeta, sizeof(OSBbSaGameMetaData)*SA_META_MAX_TICKETS);
        osBbSaMetaGetData(gpTickets,gpGameMeta, 1);
        if (gpTickets->numTickets==0)
            ret = VW_ERR_NO_TICKET;
    } else {
        gpTickets->numTickets = 0;
        if ( (ifd=osBbFOpen("ticket.sys", "r")) == BBFS_ERR_ENTRY)
            ret = VW_ERR_NO_TICKET;
        else 
            ret = VW_ERR_TICKET;
        osBbFClose(ifd);
    }
#endif
    return ret;
}

int uiGetTicketIdx(u32 cid)
{
    int i;
    int idx = -1;

    for (i=0; i<gpTickets->numTickets; i++) {
        if (gpTickets->ticket[i].cmd.head.id == cid)
            idx = i;
    }
    return idx;
}

int uiGetTicketRow(u32 cid)
{
    int i;
    int idx = -1;
    int row = -1;
    extern int gGameRedirect[];

    for (i=0; i<gpTickets->numTickets; i++) {
        if (gpTickets->ticket[i].cmd.head.id == cid)
            idx = i;
    }

    for (i = 0; i < gpTickets->numTickets; ++i) {
        if (gGameRedirect[i] == idx) {
            row = i;
            break;
        }
    }
    
    return row;
}
extern u32 gBindings[4];

int uiPreLaunchGame()
{
    int ret = 0;
    u16 tid, window, cc[BB_MAX_CC];

#ifndef _PARTNER
        // auto advance window if LP game's tid is outside window 
        if ( gpTickets->ticket[gTidx].head.tid >= BB_TICKET_ID_LIMITED ) {
            skGetConsumption(&window, cc);
            tid = gpTickets->ticket[gTidx].head.tid & (BB_TICKET_ID_LIMITED-1);
            PRINTF("window=%d tid=%d\n", window, tid);
            while ( (tid - window) >= BB_MAX_CC ) {
                if ( (ret = skAdvanceTicketWindow()) < 0 ) 
                    return VW_ERR_LAUNCH;
                skGetConsumption(&window, cc);
            }
        }

        uiCpakRead(gCpakList);
        uiGetCpakBindings(gCid, gBindings);
        for (ret = 0; ret < 4; ++ret) 
            PRINTF("binding[%d] = %d\n", ret, gBindings[ret]);

        bzero(&gTicket, sizeof(BbTicket));
        bcopy(&(gpTickets->ticket[gTidx]), &gTicket, sizeof(BbTicket));
        bzero(&gGameMeta, sizeof(OSBbSaGameMetaData));
        bcopy(&(gpGameMeta[gTidx]), &gGameMeta, sizeof(OSBbSaGameMetaData));
        ret = osBbSaGamePrelaunch(&gTicket);
        if (ret==SALAUNCH_PERSONALIZE) {
            gPersonalizeCnt = 0;
            gPersonalizeTotal = (gGameMeta.size + RECRYPT_CHUNK_SIZE - 1) / RECRYPT_CHUNK_SIZE; 
            ret = VW_GAME_PERSONALIZE;
        }
        else if(ret==SALAUNCH_OK) {
            ret = uiSetPCLimit();
            if (ret==VW_ERR_FS) 
                ret = VW_ERR_LAUNCH;
        }
        else if (ret<0) {
            PRINTF("\nsaGameLaunch gTidx=%d gCid=%d gTid=%d failed %d\n", gTidx, gCid, gTid, ret);
            if (ret==SALAUNCH_ERR_EXPIRED)
                ret = VW_ERR_EXPIRED;
            else
                ret = VW_ERR_LAUNCH;
        }
#else
        ret = VW_OK;
        PRINTF("game gTidx=%d gCid=%d gTid=%d launched\n", gTidx, gCid, gTid);
#endif

    return ret;
}

int uiPersonalizeGame()
{
    int ret; 

    ret = osBbSaGamePersonalize(gShuffleHeap);
    if (ret==SALAUNCH_PERSONALIZE) {
        PRINTF("SALAUNCH_PERSONALIZE\n");
        return VW_GAME_PERSONALIZE;
    } else if (ret==SALAUNCH_OK) {
        PRINTF("SALAUNCH_OK\n");
        ret = uiSetPCLimit();
        if (ret==VW_ERR_FS) 
            ret = VW_ERR_LAUNCH;
        return ret;
    } else
        return VW_ERR_LAUNCH;
}

int uiLaunchGame()
{
    int ret;

    if ((ret = osBbSaGameLoadState(&(gGameMeta.launch.state), gBindings, gTid)) < 0) {
        return VW_ERR_LAUNCH; 
    }
    ret = osBbSaGameLaunch(&(gGameMeta.launch));

    // should never reach here if launch successful
    return VW_ERR_LAUNCH;
}

int uiCheckBirthday()
{
    char usersys[]="user.sys";
    s32 ifd;
    int ret = 0;
    char bday[4], bday2[4];
    char *ptr;

    bzero(gSerialHeap, sizeof(gSerialHeap));
    ifd = osBbFOpen(usersys, "r");
    if (ifd>=0) {
        if (osBbFRead(ifd, 0, gSerialHeap, 16*1024)<0) {
            osBbFClose(ifd);
        } else {
            ptr = ((UserRegFile*)gSerialHeap)->user_data + UR_BB_ID_LEN + 2;
            if (*ptr!= NULL && *(ptr+4)!=NULL ) {
                bcopy(ptr+4, bday, 4);
                sprintf(bday2, "%02d%02d", gpDate[VW_DATE_MON], gpDate[VW_DATE_DAY]);
                if (!bcmp(bday, bday2, 4))
                    ret = 1;
            }
            osBbFClose(ifd);
        }
    } 

    return ret;
}

int uiGpakFull(void)
{
#ifdef PAK_COPY
    int i, cnt = 0;
    s32 ret = 0; 
    static OSBbDirEnt dir[BB_INODE16_ENTRIES];

    // check .sta file count 
    ret = osBbFReadDir(dir, sizeof(dir)/sizeof(dir[0]));
    for (i=0; i<ret; i++) {
       if (!bcmp(dir[i].name+8, STA_SUFFIX, 4)) 
            cnt ++;
    }
    if (cnt > MAX_GPAK_CNT-1)
        return 1;
    else
#endif
        return 0;
}

/*----------------------------------------------------------------------*/
// Cpak functions
/*----------------------------------------------------------------------*/

SaCpak gCpakList[MAX_CONT_PAK];

#define CPAK_BINDING "pak.bnd"

// reads flash memory into local structure
void uiCpakRead(SaCpak *pCpaks)
{
    s32 fd;
    int i;
    char state_file[16];
    u32* ptr;

    bzero(gSerialHeap, sizeof(gSerialHeap));
    if ((fd = osBbFOpen(CPAK_BINDING, "r")) >= 0) {
        osBbFRead(fd, 0, gSerialHeap, BB_FL_BLOCK_SIZE);
        osBbFClose(fd);

        ptr = (u32*)gSerialHeap;
        for (i=0; i<MAX_CONT_PAK; i++) {
            pCpaks[i].cid = *ptr; ptr++;
            pCpaks[i].cont_id = *ptr; ptr++;
            if (pCpaks[i].cid==0) pCpaks[i].cont_id = -1;
            sprintf(state_file, "%d.pak", i);
            pCpaks[i].dirty = __osBbIsSigDirty(state_file, gBlockBuf);
        }
    } else {
        for (i=0; i<MAX_CONT_PAK; i++) {
            pCpaks[i].cid = 0;
            pCpaks[i].cont_id = -1;
            sprintf(state_file, "%d.pak", i);
            pCpaks[i].dirty = __osBbIsSigDirty(state_file, gBlockBuf);
        }
    }
}

// returns number of cpaks supported by cid
int uiGetCpakCnt(u32 cid)
{
    int i; 
    int count = 0;
    u32 *p;

    if (gpGameMeta[gTidx].launch.state.pakSize) {
        p = gpGameMeta[gTidx].launch.state.pakAddress;
        for (i=0; i<MAXCONTROLLERS; ++i)
            count += (p[i]!=0 && gControllers[i]);
    }

    return count;
}

int uiGetCpakBindings(u32 cid, u32 bindings[MAXCONTROLLERS] )
{
    int i;
    for (i = 0; i < 4; ++i) {
        bindings[i] = -1;
    }
    for (i = 0; i < MAX_CONT_PAK; ++i) {
        if (gCpakList[i].cid == cid && gCpakList[i].cont_id != -1) {
            if (gCpakList[i].cont_id < MAXCONTROLLERS) {
                bindings[gCpakList[i].cont_id] = i;
            }
        }
    }
    return 0;
} 

// save cell bindings
int uiSaveCpakBindings(SaCpak* pCpaks)
{
#ifndef _PARTNER
    s32 fd;
    int i;
    u32* ptr= (u32*)gBlockBuf;

    bzero(gBlockBuf, sizeof(gBlockBuf));
    for (i=0; i<MAX_CONT_PAK; i++) {
        bcopy(&(pCpaks[i].cid), ptr, sizeof(u32)); ptr++;
        bcopy(&(pCpaks[i].cont_id), ptr, sizeof(u32)); ptr++;
    }
    
    //bcopy(pCpaks, gSerialHeap, sizeof(SaCpak)*MAX_CONT_PAK);
    if ((fd = osBbFOpen(CPAK_BINDING, "w")) < 0) {
        if ((fd = osBbFCreate(CPAK_BINDING, 1, BB_FL_BLOCK_SIZE)) < 0) {
            return VW_ERR_FS;
        }
    }
    if (osBbFWrite(fd, 0, gBlockBuf, BB_FL_BLOCK_SIZE) < 0) {
        osBbFClose(fd);
        return VW_ERR_FS;
    }

    osBbFClose(fd);
#endif
    return VW_OK;
}

int uiEmptyCpak(int i)
{
#ifndef _PARTNER
    char state_file[16];
    sprintf(state_file, "%d.pak", i);
    osBbDeleteSignedFile(state_file, gSerialHeap);
#endif
    
    gCpakList[i].cid = 0;
    gCpakList[i].cont_id = -1;
    gCpakList[i].dirty = -1;
    uiSaveCpakBindings(gCpakList);

    return VW_OK;
}

PCTimer gTimer;
const char ftimer[]= "timer.sys";
const char fstmp[] = "pcstime.tmp";

int uiInitContVal(u8* contVal, const u8* lower, const u8* upper)
{
    s32 ifd;
    int leap;
    u8 max;
    int ret = 0;

    contVal[VW_PC_YEAR] = (gpDate[VW_DATE_YEAR]<lower[VW_PC_YEAR] || 
                           gpDate[VW_DATE_YEAR]>upper[VW_PC_YEAR] ) ? 
                           lower[VW_PC_YEAR] : gpDate[VW_DATE_YEAR];
    contVal[VW_PC_MON] = (gpDate[VW_DATE_MON]<lower[VW_PC_MON] ||
                          gpDate[VW_DATE_MON]>upper[VW_PC_MON]) ?
                          lower[VW_PC_MON] : gpDate[VW_DATE_MON]; 
    contVal[VW_PC_DAY] = (gpDate[VW_DATE_DAY]<lower[VW_PC_DAY] ||
                          gpDate[VW_DATE_DAY]>upper[VW_PC_DAY]) ?
                          lower[VW_PC_DAY] : gpDate[VW_DATE_DAY]; 
    contVal[VW_PC_HR] = (gpDate[VW_DATE_HR]<lower[VW_PC_HR] ||
                          gpDate[VW_DATE_HR]>upper[VW_PC_HR]) ?
                          lower[VW_PC_HR] : gpDate[VW_DATE_HR]; 
    contVal[VW_PC_MIN] = (gpDate[VW_DATE_MIN]<lower[VW_PC_MIN] ||
                          gpDate[VW_DATE_MIN]>upper[VW_PC_MIN]) ?
                          lower[VW_PC_MIN] : gpDate[VW_DATE_MIN]; 

    bzero(gBlockBuf, sizeof(gBlockBuf));
    ifd = osBbFOpen(ftimer, "r");
    if (ifd>=0 && osBbFRead(ifd, 0, gBlockBuf, 16*1024)>=0) {
        gTimer = *((PCTimer*)gBlockBuf);
        contVal[VW_PC_PWD0] = 0;
        contVal[VW_PC_PWD1] = 0; 
        contVal[VW_PC_PWD2] = 0;
        contVal[VW_PC_PWD3] = 0; 
        contVal[VW_PC_LIMIT] = (gTimer.limit==1440) ? 24 : gTimer.limit/6;
        contVal[VW_PC_EXPY] = gTimer.exp_y;
        contVal[VW_PC_EXPM] = gTimer.exp_m;
        contVal[VW_PC_EXPD] = gTimer.exp_d;

        if (contVal[VW_PC_YEAR]>gTimer.exp_y || 
            (contVal[VW_PC_YEAR]==gTimer.exp_y && 
             contVal[VW_PC_MON]>gTimer.exp_m) || 
            (contVal[VW_PC_YEAR]==gTimer.exp_y &&
             contVal[VW_PC_MON]==gTimer.exp_m && 
             contVal[VW_PC_DAY]>gTimer.exp_d) )
        {
            osBbFClose(ifd);
            osBbFDelete(ftimer);
            ret = 0;
        } else 
            ret = 1;
    } else {
        contVal[VW_PC_PWD0] = lower[VW_PC_PWD0];
        contVal[VW_PC_PWD1] = lower[VW_PC_PWD1];
        contVal[VW_PC_PWD2] = lower[VW_PC_PWD2];
        contVal[VW_PC_PWD3] = lower[VW_PC_PWD3];
        contVal[VW_PC_LIMIT] = upper[VW_PC_LIMIT];
        contVal[VW_PC_EXPD] = contVal[VW_PC_DAY];
        if (contVal[VW_PC_MON]==upper[VW_PC_MON]) {
            contVal[VW_PC_EXPM] = lower[VW_PC_EXPM];
            contVal[VW_PC_EXPY] = contVal[VW_PC_YEAR] + 1;
            if (contVal[VW_PC_EXPY]>upper[VW_PC_EXPY]) 
                contVal[VW_PC_EXPY] = upper[VW_PC_EXPY];
        } else {
            contVal[VW_PC_EXPY] = contVal[VW_PC_YEAR];
            contVal[VW_PC_EXPM] = contVal[VW_PC_MON] + 1;
        }
        leap = leap_year( contVal[VW_PC_EXPY] );
        max = days_in_month[leap][contVal[VW_PC_EXPM]] < upper[VW_PC_EXPD] ?
              days_in_month[leap][contVal[VW_PC_EXPM]] : upper[VW_PC_EXPD];
        if (contVal[VW_PC_EXPD] > max) contVal[VW_PC_EXPD] = max;

        ret = 0; 
    }
    osBbFClose(ifd);
    return ret;
}

int uiSaveContSettings(u8* contVal)
{
    int ret = VW_OK;
    s32 ifd;
    char ftmp[] = "temp.tmp";
    int dow=0;

    dow = day_in_week(contVal[VW_PC_DAY], contVal[VW_PC_MON], 2000+contVal[VW_PC_YEAR]);
    osBbRtcSet(contVal[VW_PC_YEAR], contVal[VW_PC_MON], contVal[VW_PC_DAY], dow, 
               contVal[VW_PC_HR], contVal[VW_PC_MIN], 0);
    
    gTimer.pwd[0] = contVal[VW_PC_PWD0];
    gTimer.pwd[1] = contVal[VW_PC_PWD1];
    gTimer.pwd[2] = contVal[VW_PC_PWD2];
    gTimer.pwd[3] = contVal[VW_PC_PWD3];
    gTimer.today_y = contVal[VW_PC_YEAR];
    gTimer.today_m = contVal[VW_PC_MON];
    gTimer.today_d = contVal[VW_PC_DAY];
#ifdef PC_TESTING
    // hard code to 2min for easier testing
    gTimer.limit = (contVal[VW_PC_LIMIT]==24) ? 1440 : 2;
#else
    gTimer.limit = (contVal[VW_PC_LIMIT]==24) ? 1440 : contVal[VW_PC_LIMIT]*6;
#endif
    gTimer.remain = gTimer.limit;
    gTimer.exp_y = contVal[VW_PC_EXPY];
    gTimer.exp_m = contVal[VW_PC_EXPM];
    gTimer.exp_d = contVal[VW_PC_EXPD];

    bzero(gBlockBuf, sizeof(gBlockBuf));
    bcopy(&gTimer, gBlockBuf, sizeof(PCTimer));
    osBbFDelete(ftmp);
    osBbFCreate(ftmp, 1, 16*1024);
    if ((ifd = osBbFOpen(ftmp, "w"))<0) {
         PRINTF("temp.tmp creation failed\n", ifd);
         ret = VW_ERR_FS;
    } else {
         if(osBbFWrite(ifd, 0, gBlockBuf, 16*1024)<0){
              PRINTF("failed to write timer.sys\n");
              osBbFClose(ifd);
              osBbFDelete(ftmp);
              ret = VW_ERR_FS;
         }
         osBbFClose(ifd);
         osBbFRename(ftmp, ftimer);
    }

    return ret;
}

int uiSetPCLimit()
{
    PCTimeMarker tmarker;
    int limit, rod;
    s32 ifd;
    char ftmp[] = "temp.tmp";

    /* COUNT based limited play, or Club: no PC control*/
    if (gTicket.head.code == BB_LIMIT_CODE_COUNT ||
        gTidx==gClubTicketIdx) 
        return VW_GAME_LAUNCH0;

    bzero(gBlockBuf, sizeof(gBlockBuf));
    ifd = osBbFOpen(ftimer, "r");
    if (ifd>=0 && osBbFRead(ifd, 0, gBlockBuf, 16*1024)>=0) {
        gTimer = *((PCTimer*)gBlockBuf);
        osBbFClose(ifd);

        /* no PC limit set or PC limit expired */
        if (gTimer.limit==1440) return VW_GAME_LAUNCH0;
        if (gTimer.exp_y < gpDate[VW_DATE_YEAR] || 
            (gTimer.exp_y==gpDate[VW_DATE_YEAR] && gTimer.exp_m<gpDate[VW_DATE_MON]) || 
            (gTimer.exp_y==gpDate[VW_DATE_YEAR] && gTimer.exp_m==gpDate[VW_DATE_MON] && gTimer.exp_d<gpDate[VW_DATE_DAY])) {
            osBbFDelete(ftimer);
            gPcFound = uiInitContVal(contVal, lower, upper);
            return VW_GAME_LAUNCH0;
        }

        /* update timer.sys if today's date is not correct in timer.sys */
        if ( gpDate[VW_DATE_YEAR]!=gTimer.today_y || 
             gpDate[VW_DATE_MON]!=gTimer.today_m || 
             gpDate[VW_DATE_DAY]!=gTimer.today_d ) { 

            gTimer.today_y = gpDate[VW_DATE_YEAR]; 
            gTimer.today_m = gpDate[VW_DATE_MON]; 
            gTimer.today_d = gpDate[VW_DATE_DAY]; 
            gTimer.remain = gTimer.limit;

            bzero(gBlockBuf, sizeof(gBlockBuf));
            bcopy(&gTimer, gBlockBuf, sizeof(PCTimer));
            osBbFDelete(ftmp);
            osBbFCreate(ftmp, 1, 16*1024);
            if ((ifd = osBbFOpen(ftmp, "w"))<0) {
                PRINTF("temp.tmp creation failed\n", ifd);
                return VW_ERR_FS;
            } else {
                if(osBbFWrite(ifd, 0, gBlockBuf, 16*1024)<0){
                    PRINTF("failed to write timer.sys\n");
                    osBbFClose(ifd);
                    osBbFDelete(ftmp);
                    return VW_ERR_FS;
                }
                osBbFClose(ifd);
                osBbFRename(ftmp, ftimer);
            }
        }

        /* PC limit is set and there's still time left */
        if (gTimer.remain>0) {
            rod = 60 - gpDate[VW_DATE_MIN] + (23-gpDate[VW_DATE_HR])*60;

	    if (gTimer.exp_y==gTimer.today_y && 
                gTimer.exp_m==gTimer.today_m &&
                gTimer.exp_d==gTimer.today_d &&
                rod<=gTimer.remain) { ; }  //PC expires before limit
	    else {
                limit = (rod<gTimer.remain) ? rod : gTimer.remain;

                if ( (gGameMeta.type & SA_META_TYPE_TRIAL) >> 1 ) 
                    skSetLimit( limit+gGameMeta.cc, BB_LIMIT_CODE_TIME2 );
                else {
                    int gtime = 0;
                    vwGetGtime(&gtime);
                    skSetLimit( gtime+limit, BB_LIMIT_CODE_TIME2 );
                }
            }

            /* record starting time */
            osBbRtcGet(gpDate+VW_DATE_YEAR, gpDate+VW_DATE_MON, 
                       gpDate+VW_DATE_DAY, gpDate+VW_DATE_DOW,
                       gpDate+VW_DATE_HR, gpDate+VW_DATE_MIN, gpDate+VW_DATE_SEC);
            tmarker.hr = gpDate[VW_DATE_HR];
            tmarker.min = gpDate[VW_DATE_MIN];
            tmarker.sec = gpDate[VW_DATE_SEC];

            bzero(gBlockBuf, sizeof(gBlockBuf));
            bcopy(&tmarker, gBlockBuf, sizeof(PCTimeMarker));
            osBbFDelete(fstmp);
            osBbFCreate(fstmp, 1, 16*1024);
            if ((ifd = osBbFOpen(fstmp, "w"))<0) {
                PRINTF("pcstime.tmp creation failed\n", ifd);
                return VW_ERR_FS;
            } else {
                if(osBbFWrite(ifd, 0, gBlockBuf, 16*1024)<0){
                    PRINTF("failed to write pcstime.tmp\n");
                    osBbFClose(ifd);
                    osBbFDelete(fstmp);
                    return VW_ERR_FS;
                }
                osBbFClose(ifd);
            }

            return VW_GAME_LAUNCH0;
        } else
            return VW_ERR_PCLIMIT_EXPIRED;

    } else {                    // no parental control
        osBbFClose(ifd);
        return VW_GAME_LAUNCH0; 
    }
}

int uiCheckExpiration(BbTicketId tid)
{
    int i, found=0;

    for (i=0; i<gpTickets->numTickets; i++) 
        if (gpTickets->ticket[i].head.tid == tid) {
            found = 1;
            break;
        }

    if ( (!found) ||  //LP ticket expired on LP limit, but ticket no longer available 
         ( ((gpGameMeta[i].type & SA_META_TYPE_TRIAL) >> 1) &&  
         (gpGameMeta[i].cc >= gpGameMeta[i].limit) ) )  // LP ticket expired on LP limit
        return VW_ERR_EXPIRED;
    else 
        return VW_ERR_PCLIMIT_EXPIRED;
}

int uiUpdateTimer(u16 tid, int reset_gtime)
{
    s32 ifd;
    int remain = 0, time_played = 0;
    char ftmp[]="temp.tmp";
    PCTimer timer;
    PCTimeMarker tmarker;
    u16 window, cc[BB_MAX_CC];
    int gtime=0;

    osBbRtcGet(gpDate+VW_DATE_YEAR, gpDate+VW_DATE_MON, 
               gpDate+VW_DATE_DAY, gpDate+VW_DATE_DOW,
               gpDate+VW_DATE_HR, gpDate+VW_DATE_MIN, gpDate+VW_DATE_SEC);

    // read "pcstime.tmp" if it exists
    bzero(gBlockBuf, sizeof(gBlockBuf));
    ifd = osBbFOpen(fstmp, "r");
    if (ifd>=0 && osBbFRead(ifd, 0, gBlockBuf, 16*1024)>=0) {
        tmarker = *((PCTimeMarker*)gBlockBuf);
        if (gTimer.today_y!=gpDate[VW_DATE_YEAR] || 
            gTimer.today_m!=gpDate[VW_DATE_MON] ||
            gTimer.today_d!=gpDate[VW_DATE_DAY]) {
            time_played = (23 - tmarker.hr)*60 + 
                          (59 - (int)(tmarker.min)) + 
                          ((59 - tmarker.sec)>=30 ? 1 : 0);
        } else {
            time_played = (gpDate[VW_DATE_HR] - tmarker.hr)*60 + 
                          ((int)gpDate[VW_DATE_MIN] - (int)(tmarker.min)) + 
                          (gpDate[VW_DATE_SEC] + 60 - tmarker.sec)/60 + 
                          ((gpDate[VW_DATE_SEC] + 60 - tmarker.sec)%60>=30 ? 1 : 0) 
                          - 1 /*compensate for game launching and exiting time*/; 
        }
        if (time_played<0) time_played = 0;
    }
    osBbFClose(ifd);
    osBbFDelete(fstmp);

    // update gTime
    if (reset_gtime) {
        vwStoreGtime(0);
    } else {
       if (tid >= BB_TICKET_ID_LIMITED) {
            skGetConsumption(&window, cc);
            tid =  tid & (BB_TICKET_ID_LIMITED-1);
            if (tid>=window && tid<window+BB_MAX_CC) // should always be true
                gtime = cc[tid-window];
        } else { 
            vwGetGtime(&gtime);
            gtime += time_played;
        }
        vwStoreGtime(gtime);
    }

    // update PC remain & today's date in timer.sys
    if (gPcFound) {
        bzero(gBlockBuf, sizeof(gBlockBuf));
        ifd = osBbFOpen(ftimer, "r");
        if (ifd>=0 && osBbFRead(ifd, 0, gBlockBuf, 16*1024)>=0) {
            bcopy(gBlockBuf, &timer, sizeof(PCTimer));
            osBbFClose(ifd);
        } 

        if (gpDate[VW_DATE_YEAR]!=timer.today_y || 
            gpDate[VW_DATE_MON]!=timer.today_m || 
            gpDate[VW_DATE_DAY]!=timer.today_d) 
        {
            if (gTimer.exp_y < gpDate[VW_DATE_YEAR] || 
                (gTimer.exp_y==gpDate[VW_DATE_YEAR] && gTimer.exp_m<gpDate[VW_DATE_MON]) || 
                (gTimer.exp_y==gpDate[VW_DATE_YEAR] && gTimer.exp_m==gpDate[VW_DATE_MON] && gTimer.exp_d<gpDate[VW_DATE_DAY])) {
                osBbFDelete(ftimer);
                gPcFound = uiInitContVal(contVal, lower, upper);
                return VW_OK;
            } else {
                gTimer.today_y = timer.today_y = gpDate[VW_DATE_YEAR];
                gTimer.today_m = timer.today_m = gpDate[VW_DATE_MON];
                gTimer.today_d = timer.today_d = gpDate[VW_DATE_DAY];
                remain = timer.limit;
            }
        } else {
            remain = timer.remain - time_played;
            if (remain<0) remain = 0;
        }
        gTimer.remain = timer.remain = remain;

        bzero(gBlockBuf, sizeof(gBlockBuf));
        bcopy(&timer, gBlockBuf, sizeof(PCTimer));
        osBbFDelete(ftmp);
        osBbFCreate(ftmp, 1, 16*1024);
        if ((ifd = osBbFOpen(ftmp, "w"))<0) {
             PRINTF("temp.tmp creation failed\n", ifd);
             return VW_ERR_FS;
        } else {
             if(osBbFWrite(ifd, 0, gBlockBuf, 16*1024)<0){
                  PRINTF("failed to write timer.sys\n");
                  osBbFClose(ifd);
                  osBbFDelete(ftmp);
                  return VW_ERR_FS;
             }
             osBbFClose(ifd);
             osBbFRename(ftmp, ftimer);
        }
    }

    return VW_OK;
}

#ifdef PAK_COPY
/* fill in pCids array with cids of games that have gpak */
int uiGetGpaks(SaGpak* pGpaks)
{
    int i, j;

    bzero(pGpaks, SA_META_MAX_TICKETS*sizeof(SaGpak));

    for (i=j=0; i<gpTickets->numTickets; i++) {
        u32 cid = gpTickets->ticket[i].cmd.head.id;
        int fd;
        char state_file[16];
        sprintf(state_file, "%08lx.sta", cid);
        if ((fd = osBbFOpen(state_file, "r")) >= 0) {
            osBbFClose(fd);
            pGpaks[j].cid = cid;
            if (__osBbIsSigDirty(state_file, gBlockBuf)!=0)
                pGpaks[j].dirty = 1;
            j++;
        }
    }
    return j;
}

/* delete gpak given game cid */ 
int uiDeleteGpak(u32 cid)
{
    char state_file[16];
    sprintf(state_file, "%08lx.sta", cid);
    osBbDeleteSignedFile(state_file, gSerialHeap);

    return VW_OK;
}

/* get gpak data given game cid */
int uiGetGpakCopy(u32 cid, SaGpakCopy* pGpak)
{
    OSBbStatBuf sbuf;
    int fd;
    char state_file[16];

    pGpak->cid = cid;
    bzero (pGpak->data, MAX_GPAK_DATA_SIZE);
    sprintf(state_file, "%08lx.sta", cid);
    if ((fd = osBbFOpen(state_file, "r")) >= 0) {
        osBbFStat(fd, &sbuf, 0, 0);
        pGpak->size = MIN(sbuf.size, MAX_GPAK_DATA_SIZE);
        osBbFRead(fd, 0, pGpak->data, pGpak->size);
        osBbFClose(fd);    
    }

    __osBbLookupSig(state_file, pGpak->sig, gBlockBuf);

    return VW_OK;
}

int uiGpakSrcCardOkay()
{
    resetViewer();
    initPageGpak(0, 0);
    if (gTicketStatus==VW_ERR_TICKET || gTicketStatus==VW_ERR_NO_TICKET)
        return VW_ERR_GP_CPY_SRC_NO_TICKET;
    else if (gNumGpaks==0)
        return VW_ERR_GP_CPY_SRC_NO_GPAK;
    else
        return VW_GP_CPY_SRC_SELECT;
}

int uiGpakDstCardOkay(SaGpakCopy* pGpak)
{
    int i, found = 0, cnt = 0;
    s32 fd, ret = 0; 
    char state_file[16];
    static OSBbDirEnt dir[BB_INODE16_ENTRIES];

    // check BBID
    if (uiBbidCheck()!=VW_OK)
        return VW_ERR_GP_CPY_WRONG_DST_CARD;
        
    // check ticket.sys
    gCardInit = 0;
    initGames();
    if (gTicketStatus==VW_ERR_NO_TICKET || gTicketStatus==VW_ERR_TICKET) 
        return VW_ERR_GP_CPY_DST_NO_TICKET;
    gPageGpakInit = 0;
    initPageGpak(0, 0);

    for (i=0; i<gpTickets->numTickets; i++) {
        if (gpTickets->ticket[i].cmd.head.id == pGpak->cid) {
            found = 1;
            break;
        }
    }
    if (!found) return VW_ERR_GP_CPY_DST_NO_TICKET;
        
    // check existing sta file 
    sprintf(state_file, "%08lx.sta", pGpak->cid);
    if ((fd = osBbFOpen(state_file, "r")) >=0 ) {
        osBbFClose(fd);
        return VW_GP_CPY_CNF;
    } else {
        // check .sta file count 
        ret = osBbFReadDir(dir, sizeof(dir)/sizeof(dir[0]));
        for (i=0; i<ret; i++) {
            if (!bcmp(dir[i].name+8, STA_SUFFIX, 4)) 
                cnt ++;
        }
        //if ((space + pGpak->size) > MAX_FS_GPAK_SIZE)
        if (cnt > MAX_GPAK_CNT-1)
            return VW_ERR_GP_CPY_DST_NO_SPACE;
        else
            return VW_GP_CPY_YES;
    }
}

int uiCopyGpak(SaGpakCopy* pGpak)
{
    s32 fd;
    char state_file[16];
    char fname[16];

    sprintf(state_file, "%08lx.sta", pGpak->cid);

    // copy state file 
    osBbFDelete(state_file);
    osBbFCreate(state_file, 1, pGpak->size);
    if ( (fd=osBbFOpen(state_file, "w"))>=0 ) {
        osBbFWrite(fd, 0, pGpak->data, pGpak->size);
        osBbFClose(fd);
    }

    // copy signature 
    __osBbDeleteSig(state_file, gBlockBuf); 
    if (!osBbVerifySig(state_file, pGpak->sig, gBlockBuf)) {
        bcopy(state_file, fname, sizeof(state_file));
        *fname |= 0x80;
        __osBbInsertSig(fname, pGpak->sig, gBlockBuf);
    } else
        __osBbInsertSig(state_file, pGpak->sig, gBlockBuf);

    return VW_OK;
}

int uiCpakSrcCardOkay()
{
    int rv, i, fd, found = 0;
    char state_file[16];

    // check ticket.sys
    resetViewer();

    bzero(gpTickets, sizeof(OSBbSaTickets));
    rv = osBbSaMetaGetTickets(gpTickets, 0);
    bzero(gpGameMeta, sizeof(OSBbSaGameMetaData)*SA_META_MAX_TICKETS);
    osBbSaMetaGetData(gpTickets,gpGameMeta, 0);
    initPageCpak(0);

    if (rv!=0)
        return VW_ERR_CP_CPY_SRC_NO_TICKET;
    else {
        for (i=0; i<MAX_CONT_PAK; i++) {
            sprintf(state_file, "%d.pak", i);
            if ((fd = osBbFOpen(state_file, "r")) >= 0) {
                osBbFClose(fd);
                found = 1;
            }
        }
        if (!found) 
            return VW_ERR_CP_CPY_SRC_NO_CPAK;
        else
            return VW_CP_CPY_SRC_SELECT;
    }
}

int uiCpakDstCardOkay(SaCpakCopy* pCpak)
{
    int i, found = 0;

    // check BBID
    if (uiBbidCheck()!=VW_OK)
        return VW_ERR_CP_CPY_WRONG_DST_CARD;
        
    // check ticket.sys
    gCardInit = 0;
    initGames();
    if (gTicketStatus==VW_ERR_NO_TICKET || gTicketStatus==VW_ERR_TICKET) 
        return VW_ERR_CP_CPY_DST_NO_TICKET;
    initPageCpak(0);

    for (i=0; i<gpTickets->numTickets; i++) {
        if (gpTickets->ticket[i].cmd.head.id == pCpak->cid) {
            found = 1;
            break;
        }
    }
    if (!found) return VW_ERR_CP_CPY_DST_NO_TICKET;
        
    return VW_CP_CPY_DST_SELECT;
}

int uiGetCpakCopy(int i, SaCpakCopy* pCpak)
{
    OSBbStatBuf sbuf;
    int fd;
    char state_file[16];

    pCpak->cid = gCpakList[i].cid;

    bzero (pCpak->data, MAX_CPAK_DATA_SIZE);
    sprintf(state_file, "%d.pak", i);
    if ((fd = osBbFOpen(state_file, "r")) >= 0) {
        osBbFStat(fd, &sbuf, 0, 0);
        osBbFRead(fd, 0, pCpak->data, MAX_CPAK_DATA_SIZE);
        osBbFClose(fd);    
    }

    __osBbLookupSig(state_file, pCpak->sig, gBlockBuf);

    return VW_OK;
}

int uiCopyCpak(int i, SaCpakCopy* pCpak)
{
    int fd;
    char state_file[16];
    char fname[16];

    sprintf(state_file, "%d.pak", i);

    // copy state file
    osBbFDelete(state_file);
    osBbFCreate(state_file, 1, MAX_CPAK_DATA_SIZE);
    if ( (fd=osBbFOpen(state_file, "w"))>=0 ) {
        osBbFWrite(fd, 0, pCpak->data, MAX_CPAK_DATA_SIZE);
        osBbFClose(fd);
    }

    // copy signature 
    __osBbDeleteSig(state_file, gBlockBuf); 

    if (!osBbVerifySig(state_file, pCpak->sig, gBlockBuf)) {
        bcopy(state_file, fname, sizeof(state_file));
        *fname |= 0x80;
        __osBbInsertSig(fname, pCpak->sig, gBlockBuf);
    } else 
        __osBbInsertSig(state_file, pCpak->sig, gBlockBuf);

    // save binding
    gCpakList[i].cid = pCpak->cid;
    uiSaveCpakBindings(gCpakList);
    return VW_OK;
}
#endif